U
    W[1                    @   s  d Z eZddlmZ ddlZddlZddlZddlm	Z	 ddl
mZmZmZ ddlmZ ddlmZ ddlmZ dd	lmZmZ dd
lmZ ddlmZ ddlmZmZ ddlmZ ddl m!Z!m"Z" ddl#m$Z$m%Z%m&Z& ddl'm(Z( ddl)m*Z* ddl+m,Z,m-Z- ddl.m/Z/ ddl0m1Z1m2Z2 G dd dZ3G dd dZ4G dd deZ5G dd dZ6G dd de6eZ7G dd  d e6Z8G d!d" d"e8eZ9G d#d$ d$e8eZ:G d%d& d&e8eZ;G d'd( d(e8eZ<G d)d* d*e6eZ=G d+d, d,e6eZ>dS )-z 
Tests for L{twisted.web.wsgi}.
    )exc_infoN)verifyObject)
intToBytesurlquote_PY3)Failure)getThreadID)
ThreadPool)DeferredgatherResults)reactor)ConnectionLost)TestCaseSkipTest)http)	IResourceResource)RequestSiteversion)WSGIResource)DummyChannel)globalLogPublisherLogger)EventLoggingObserver)IPv4AddressIPv6Addressc                   @   s   e Zd ZdZe Zdd ZdS )SynchronousThreadPoola  
    A single-threaded implementation of part of the L{ThreadPool} interface.
    This implementation calls functions synchronously rather than running
    them in a thread pool.  It is used to make the tests which are not
    directly for thread-related behavior deterministic.
    c                 O   s,   z||| W n   | j d Y nX dS )zp
        Call C{f(*a, **kw)} in this thread rather than scheduling it to be
        called in a thread.
        z<Callable passed to SynchronousThreadPool.callInThread failedN)_logZfailureselffakw r$   </usr/lib/python3/dist-packages/twisted/web/test/test_wsgi.pycallInThread-   s    z"SynchronousThreadPool.callInThreadN)__name__
__module____qualname____doc__r   r   r&   r$   r$   r$   r%   r   $   s   r   c                   @   s   e Zd ZdZdd ZdS )SynchronousReactorThreadsa  
    A single-threaded implementation of part of the L{IReactorThreads}
    interface.  This implementation assumes that it will only be invoked
    from the reactor thread, so it calls functions synchronously rather than
    trying to schedule them to run in the reactor thread.  It is used in
    conjunction with L{SynchronousThreadPool} to make the tests which are
    not directly for thread-related behavior deterministic.
    c                 O   s   ||| dS )ze
        Call C{f(*a, **kw)} in this thread which should also be the reactor
        thread.
        Nr$   r   r$   r$   r%   callFromThreadG   s    z(SynchronousReactorThreads.callFromThreadNr'   r(   r)   r*   r,   r$   r$   r$   r%   r+   >   s   r+   c                   @   s,   e Zd Zdd Zdd Zdd Zdd Zd	S )
WSGIResourceTestsc                 C   s   t t t dd | _dS )z
        Create a L{WSGIResource} with synchronous threading objects and a no-op
        application object.  This is useful for testing certain things about
        the resource implementation which are unrelated to WSGI.
        c                 S   s   d S Nr$   environstartResponser$   r$   r%   <lambda>Y       z)WSGIResourceTests.setUp.<locals>.<lambda>N)r   r+   r   resourcer    r$   r$   r%   setUpQ   s
     zWSGIResourceTests.setUpc                 C   s   t t| j | | jj dS )zW
        L{WSGIResource} implements L{IResource} and stops resource traversal.
        N)r   r   r5   
assertTrueZisLeafr6   r$   r$   r%   test_interfaces\   s    z!WSGIResourceTests.test_interfacesc                 C   s6   |  t| jjdtt d |  t| jjdt  dS )z
        A L{WSGIResource} cannot have L{IResource} children.  Its
        C{getChildWithDefault} and C{putChild} methods raise L{RuntimeError}.
           fooFN)assertRaisesRuntimeErrorr5   ZgetChildWithDefaultr   r   putChildr   r6   r$   r$   r%   test_unsupportedd   s     
 z"WSGIResourceTests.test_unsupportedc                    s   t | t}G dd dt G dd dt} fdd}G  fddd}t| t || _| j|t	 d	 | 
d
t| |d d }| |j  |   dS )z
        If an exception is thrown by the application, and then in the
        exception handling code, verify it should be propagated to the
        provided L{ThreadPool}.
        c                   @   s   e Zd ZdZdS )zIWSGIResourceTests.test_applicationAndRequestThrow.<locals>.ArbitraryErrorz;
            An arbitrary error for this class
            N)r'   r(   r)   r*   r$   r$   r$   r%   ArbitraryError~   s   r?   c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	zPWSGIResourceTests.test_applicationAndRequestThrow.<locals>.FinishThrowingRequestzL
            An L{IRequest} request whose finish method throws.
            c                 _   s(   t j| f|| d| _d| _d| _d S )N s   www.example.com/stuff)r   __init__ZprepathZpostpathuri)r    argskwargsr$   r$   r%   rA      s    zYWSGIResourceTests.test_applicationAndRequestThrow.<locals>.FinishThrowingRequest.__init__c                 S   s   dS )zi
                Return loopback address.

                @return: loopback ip address.
                	127.0.0.1r$   r6   r$   r$   r%   getClientIP   s    z\WSGIResourceTests.test_applicationAndRequestThrow.<locals>.FinishThrowingRequest.getClientIPc                 S   s   t dddS )z`
                Return a fake Address

                @return: A fake address
                TCPrE   i0u  )r   r6   r$   r$   r%   getHost   s    zXWSGIResourceTests.test_applicationAndRequestThrow.<locals>.FinishThrowingRequest.getHostN)r'   r(   r)   r*   rA   rF   rH   r$   r$   r$   r%   FinishThrowingRequest   s   	rI   c                    s
     dS )z
            An application object that throws an exception.

            @param environ: unused

            @param startResponse: unused
            Nr$   r0   r?   r$   r%   application   s    zFWSGIResourceTests.test_applicationAndRequestThrow.<locals>.applicationc                       s   e Zd ZdZ fddZdS )zQWSGIResourceTests.test_applicationAndRequestThrow.<locals>.ThrowingReactorThreadszt
            An L{IReactorThreads} implementation whose callFromThread raises
            an exception.
            c                    s
     dS )z
                Raise an exception to the caller.

                @param f: unused

                @param a: unused

                @param kw: unused
                Nr$   r   rJ   r$   r%   r,      s    
z`WSGIResourceTests.test_applicationAndRequestThrow.<locals>.ThrowingReactorThreads.callFromThreadNr-   r$   rJ   r$   r%   ThrowingReactorThreads   s   rL   F   r   log_failureN)r   createWithCleanupr   	Exceptionr   r   r   r5   renderr   assertEqualslenassertIsInstancevalueflushLoggedErrors)r    logObserverrI   rK   rL   r!   r$   rJ   r%   test_applicationAndRequestThrows   s$    z1WSGIResourceTests.test_applicationAndRequestThrowN)r'   r(   r)   r7   r9   r>   rX   r$   r$   r$   r%   r.   P   s   r.   c                   @   sT   e Zd ZdZeZdd Zdg ddfddZdd	 Ze	fd
dZ
dd ZdddZdS )WSGITestsMixinz
    @ivar channelFactory: A no-argument callable which will be invoked to
        create a new HTTP channel to associate with request objects.
    c                 C   s   t  | _t | _d S r/   )r   
threadpoolr+   r   r6   r$   r$   r%   r7      s    zWSGITestsMixin.setUpNr@   c                    s  dd }t | j| j| }|  |D ]}t }|||| |}q&| }t||_||d}|	D ]\}}|j	|||| qd|
d |
r|j|
 |jd dd fdd|D  }|dk	r|d	d
 fdd|D  7 }|||||d||  |S )a  
        @param method: A C{str} giving the request method to use.

        @param version: A C{str} like C{'1.1'} giving the request version.

        @param resourceSegments: A C{list} of unencoded path segments which
            specifies the location in the resource hierarchy at which the
            L{WSGIResource} will be placed, eg C{['']} for I{/}, C{['foo',
            'bar', '']} for I{/foo/bar/}, etc.

        @param requestSegments: A C{list} of unencoded path segments giving the
            request URI.

        @param query: A C{list} of two-tuples of C{str} giving unencoded query
            argument keys and values.

        @param headers: A C{list} of two-tuples of C{str} giving request header
            names and corresponding values.

        @param safe: A C{str} giving the bytes which are to be considered
            I{safe} for inclusion in the request URI and not quoted.

        @return: A L{Deferred} which will be called back with a two-tuple of
            the arguments passed which would be passed to the WSGI application
            object for this configuration and request (ie, the environment and
            start_response callable).
        c                 S   s   t | tr| S | dS d S )Nz
iso-8859-1)
isinstancebytesencode)stringr$   r$   r%   _toByteString   s    
z4WSGITestsMixin.lowLevelRender.<locals>._toByteStringFr   /c                    s   g | ]}t | qS r$   )r   ).0segsafer$   r%   
<listcomp>  s     z1WSGITestsMixin.lowLevelRender.<locals>.<listcomp>N?&c                    s*   g | ]"\}}d  t| t| gqS )=)joinr   )ra   kvrc   r$   r%   re     s   s   HTTP/)r   r   rZ   reverser   r=   r   siterequestHeadersaddRawHeader	gotLengthcontentwriteseekri   requestReceived)r    requestFactoryapplicationFactorychannelFactorymethodr   ZresourceSegmentsZrequestSegmentsZqueryheadersZbodyrd   r_   rootrb   Ztmpchannelrequestrj   rk   rB   r$   rc   r%   lowLevelRender   sD    	  

 
 
zWSGITestsMixin.lowLevelRenderc                    s:   t    fdd}|d| j}| jt||f||  S )Nc                     s    fdd} | S )Nc                     s$   | \}}  |  |dg  tdS N200 OKr$   callbackiterrC   r1   r2   resultr$   r%   rK     s    

zFWSGITestsMixin.render.<locals>.applicationFactory.<locals>.applicationr$   rK   r   r$   r%   rv     s    z1WSGITestsMixin.render.<locals>.applicationFactoryrw   )r
   poprw   r}   r   )r    r"   r#   rv   rw   r$   r   r%   rQ     s      zWSGITestsMixin.renderc                    s   t    fdd} |fS )Nc                     s   | |}|    |S r/   )ZnotifyFinishZchainDeferred)r"   r#   r|   drequestClassr$   r%   ru   +  s    
z<WSGITestsMixin.requestFactoryFactory.<locals>.requestFactoryr
   )r    r   ru   r$   r   r%   requestFactoryFactory)  s    z$WSGITestsMixin.requestFactoryFactoryc                 C   s   | ddd S )N   

rM   )split)r    responser$   r$   r%   getContentFromResponse6  s    z%WSGITestsMixin.getContentFromResponsec                    sv   t   fdd}t| j| j|}t }|d| |  }t||_G dd dt	}||dd}|
d |fS )	aj  
        Prepare a L{Request} which, when a request is received, captures the
        C{environ} and C{start_response} callable passed to a WSGI app.

        @param application: An optional WSGI application callable that accepts
            the familiar C{environ} and C{start_response} args and returns an
            iterable of body content. If not supplied, C{start_response} will
            be called with a "200 OK" status and no headers, and no content
            will be yielded.

        @return: A two-tuple of (C{request}, C{deferred}). The former is a
            Twisted L{Request}. The latter is a L{Deferred} which will be
            called back with a two-tuple of the arguments passed to a WSGI
            application (i.e. the C{environ} and C{start_response} callable),
            or will errback with any error arising within the WSGI app.
        c                    sh   z* d kr|dg  t d}n
 | |}W n&     |dg  t d Y S X | |f |S d S )Nr   r$   z	500 Error)r   Zerrbackr   )r1   r2   rq   rK   r   r$   r%   outerApplicationM  s    


z7WSGITestsMixin.prepareRequest.<locals>.outerApplications   resc                   @   s   e Zd ZdZdddZdS )	z4WSGITestsMixin.prepareRequest.<locals>.CannedRequestz
            Convenient L{Request} derivative which has canned values for all
            of C{requestReceived}'s arguments.
               GET   /res   1.1c                 S   s   t j| |||dS )N)commandpathr   )r   rt   )r    r   r   r   r$   r$   r%   rt   j  s       zDWSGITestsMixin.prepareRequest.<locals>.CannedRequest.requestReceivedN)r   r   r   )r'   r(   r)   r*   rt   r$   r$   r$   r%   CannedRequeste  s
        r   F)Zqueuedr   )r
   r   r   rZ   r   r=   rw   r   rm   r   rp   )r    rK   r   r5   rz   r{   r   r|   r$   r   r%   prepareRequest:  s      


zWSGITestsMixin.prepareRequest)N)r'   r(   r)   r*   r   rw   r7   r}   rQ   r   r   r   r   r$   r$   r$   r%   rY      s     
DrY   c                   @   s  e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zd d! Zd"d# Zd$d% Zd&d' Zd(d) Zd*d+ Zd,d- Zd.d/ Zd0d1 Zd2d3 Zd4d5 Zd6d7 Zd8d9 Zd:d; Z d<d= Z!d>d? Z"d@S )AEnvironTestsz
    Tests for the values in the C{environ} C{dict} passed to the application
    object by L{twisted.web.wsgi.WSGIResource}.
    c                    s    fdd}|S )Nc                    s   | \}} |   S r/   assertEqualr   r1   r2   keyr    rU   r$   r%   assertEnvironKeyEqual|  s    z;EnvironTests.environKeyEqual.<locals>.assertEnvironKeyEqualr$   )r    r   rU   r   r$   r   r%   environKeyEqual{  s    zEnvironTests.environKeyEqualc                    s,     ddg dg} fdd}|| |S )z
        L{WSGIResource} calls the application object with an C{environ}
        parameter which is exactly of type C{dict}.
        GET1.1r@   c                    s2   | \}}  t|t |D ]} |t qd S r/   )ZassertIdenticaltypedictrT   str)r   r1   r2   namer6   r$   r%   
cbRendered  s    z3EnvironTests.test_environIsDict.<locals>.cbRendered)rQ   addCallback)r    r   r   r$   r6   r%   test_environIsDict  s    
zEnvironTests.test_environIsDictc                 C   sT   |  ddg dg}|| dd |  ddg dg}|| dd t||gS )z
        The C{'REQUEST_METHOD'} key of the C{environ} C{dict} passed to the
        application contains the HTTP method in the request (RFC 3875, section
        4.1.12).
        r   r   r@   REQUEST_METHODZPOSTrQ   r   r   r   )r    getZpostr$   r$   r%   test_requestMethod  s
    zEnvironTests.test_requestMethodc                 C   sH   dD ]>}|   \}}|| || dd | | |t qdS )z
        The C{'REQUEST_METHOD'} key of the C{environ} C{dict} passed to the
        application is always a native string.
        )r   r   r   r   Nr   rt   r   r   rT   successResultOfr   )r    rx   r|   r   r$   r$   r%    test_requestMethodIsNativeString  s
    
z-EnvironTests.test_requestMethodIsNativeStringc                 C   s  |  ddg dg}|| dd |  dddgdg}|| dd |  dddgdg}|| dd |  ddddgddg}|| dd |  dddgdd	g}|| dd |  ddddd
gddd
g}|| dd t||||||gS )z
        The C{'SCRIPT_NAME'} key of the C{environ} C{dict} passed to the
        application contains the I{abs_path} (RFC 2396, section 3) to this
        resource (RFC 3875, section 4.1.13).
        r   r   r@   SCRIPT_NAMEr`   fooz/fooz/foo/bar   bar   /foo///barÿr   )r    rz   
emptyChildleaf	containerZinternal	unencodedr$   r$   r%   test_scriptName  s6       
     zEnvironTests.test_scriptNamec                 C   s   |   \}}|jdd || dd | | |t tr`|   \}}| jt	|jdd n<|   \}}|jdd || dd | | |t dS )z
        The C{'SCRIPT_NAME'} key of the C{environ} C{dict} passed to the
        application is always a native string.
        r   r   r   z/resN
r   rt   r   r   rT   r   r   r   r;   	TypeErrorr    r|   r   r$   r$   r%   test_scriptNameIsNativeString  s    z*EnvironTests.test_scriptNameIsNativeStringc           	      C   s  |  dd}| ddg dg}||  dd | dddgdg}|| | dddgdg}|| | ddddgddg}|| | dddgddg}||  dd | dddgddg}||  dd | ddg ddd	g}||  dd
 t||||||gS )z
        The C{'PATH_INFO'} key of the C{environ} C{dict} passed to the
        application contains the suffix of the request URI path which is not
        included in the value for the C{'SCRIPT_NAME'} key (RFC 3875, section
        4.1.5).
        	PATH_INFOr@   r   r   r`   r   r   z/barr   r   )r   rQ   r   r   )	r    ZassertKeyEmptyrz   r   r   r   ZinternalLeafZinternalContainerr   r$   r$   r%   test_pathInfo  s2    



    zEnvironTests.test_pathInfoc                 C   s   |   \}}|jdd || dd | | |t tr`|   \}}| jt	|jdd n<|   \}}|jdd || dd | | |t dS )z
        The C{'PATH_INFO'} key of the C{environ} C{dict} passed to the
        application is always a native string.
        s   /res/foo/barr   r   z/foo/barz/res/foo/barNr   r   r$   r$   r%   test_pathInfoIsNativeString
  s      z(EnvironTests.test_pathInfoIsNativeStringc                 C   s   |  ddg dgd}|| dd |  ddg dgg }|| dd |  ddg dgdg}|| dd |  ddg dgdg}|| dd	 | j ddg dgd
gdd}|| dd t|||||gS )z
        The C{'QUERY_STRING'} key of the C{environ} C{dict} passed to the
        application contains the portion of the request URI after the first
        I{?} (RFC 3875, section 4.1.7).
        r   r   r@   NQUERY_STRINGr   r   foo=bar)r`   r`   z%2F=%2F)r   z?barrf   rc   zfoo=?barr   )r    missingemptypresentr   ZdoubleQuestionr$   r$   r%   test_queryString!  s4         
    zEnvironTests.test_queryStringc                 C   s   |   \}}|jdd || dd | | |t tr`|   \}}| jt	|jdd n<|   \}}|jdd || dd | | |t dS )z
        The C{'QUERY_STRING'} key of the C{environ} C{dict} passed to the
        application is always a native string.
        s   /res?foo=barr   r   r   z/res?foo=barNr   r   r$   r$   r%   test_queryStringIsNativeString?  s      z+EnvironTests.test_queryStringIsNativeStringc                 C   sZ   |  ddg dg}|| dd |  ddg dgddg}|| dd t||gS )z
        The C{'CONTENT_TYPE'} key of the C{environ} C{dict} passed to the
        application contains the value of the I{Content-Type} request header
        (RFC 3875, section 4.1.3).
        r   r   r@   CONTENT_TYPEN)content-type	x-foo/barr   r   r    r   r   r$   r$   r%   test_contentTypeV  s         zEnvironTests.test_contentTypec                 C   sT   dD ]J}|   \}}|jd| |  || dd | | |t qdS )z
        The C{'CONTENT_TYPE'} key of the C{environ} C{dict} passed to the
        application is always a native string.
        )s	   x-foo/barr   s   Content-Typer   r   N	r   rn   ro   rt   r   r   rT   r   r   )r    contentTyper|   r   r$   r$   r%   test_contentTypeIsNativeStringf  s    z+EnvironTests.test_contentTypeIsNativeStringc                 C   sZ   |  ddg dg}|| dd |  ddg dgddg}|| dd t||gS )z
        The C{'CONTENT_LENGTH'} key of the C{environ} C{dict} passed to the
        application contains the value of the I{Content-Length} request header
        (RFC 3875, section 4.1.2).
        r   r   r@   CONTENT_LENGTHN)content-length1234r   r   r   r$   r$   r%   test_contentLengths  s         zEnvironTests.test_contentLengthc                 C   sT   dD ]J}|   \}}|jd| |  || dd | | |t qdS )z
        The C{'CONTENT_LENGTH'} key of the C{environ} C{dict} passed to the
        application is always a native string.
        )s   1234r   s   Content-Lengthr   r   Nr   )r    ZcontentLengthr|   r   r$   r$   r%    test_contentLengthIsNativeString  s    z-EnvironTests.test_contentLengthIsNativeStringc                 C   sZ   |  ddg dg}|| dd |  ddg dgddg}|| dd t||gS )	a_  
        The C{'SERVER_NAME'} key of the C{environ} C{dict} passed to the
        application contains the best determination of the server hostname
        possible, using either the value of the I{Host} header in the request
        or the address the server is listening on if that header is not
        present (RFC 3875, section 4.1.14).
        r   r   r@   SERVER_NAMEz10.0.0.1N)Zhostexample.orgr   r   r   r$   r$   r%   test_serverName  s         zEnvironTests.test_serverNamec                    sT   dD ]J |   \}} fdd|_|  || dd | | |t qdS )z
        The C{'SERVER_NAME'} key of the C{environ} C{dict} passed to the
        application is always a native string.
        )s   host.example.comhost.example.comc                      s    S r/   r$   r$   Z
serverNamer$   r%   r3     r4   z<EnvironTests.test_serverNameIsNativeString.<locals>.<lambda>r   r   N)r   ZgetRequestHostnamert   r   r   rT   r   r   r   r$   r   r%   test_serverNameIsNativeString  s    z*EnvironTests.test_serverNameIsNativeStringc                    sB   d  fdd}|| _ | ddg dg}|| dt  |S )z
        The C{'SERVER_PORT'} key of the C{environ} C{dict} passed to the
        application contains the port number of the server which received the
        request (RFC 3875, section 4.1.15).
        iB0  c                     s   t  } t  | _ | j_| S r/   )r   rG   	transportZportr{   Z
portNumberr$   r%   makeChannel  s    
z1EnvironTests.test_serverPort.<locals>.makeChannelr   r   r@   SERVER_PORT)rw   rQ   r   r   r   )r    r   r   r$   r   r%   test_serverPort  s    zEnvironTests.test_serverPortc                 C   s<   |   \}}|  || dd | | |t dS )z
        The C{'SERVER_PORT'} key of the C{environ} C{dict} passed to the
        application is always a native string.
        r   Z80Nr   r   r$   r$   r%   test_serverPortIsNativeString  s    z*EnvironTests.test_serverPortIsNativeStringc                 C   sT   |  ddg dg}|| dd |  ddg dg}|| dd t||gS )z
        The C{'SERVER_PROTOCOL'} key of the C{environ} C{dict} passed to the
        application contains the HTTP version number received in the request
        (RFC 3875, section 4.1.16).
        r   z1.0r@   SERVER_PROTOCOLzHTTP/1.0r   zHTTP/1.1r   )r    oldnewr$   r$   r%   test_serverProtocol  s
    z EnvironTests.test_serverProtocolc                 C   sT   dD ]J}|   \}}dd |_|jdd || dd | | |t qdS )	z
        The C{'SERVER_PROTOCOL'} key of the C{environ} C{dict} passed to the
        application is always a native string.
        )r   r   c                 S   s   d S r/   r$   )datar$   r$   r%   r3     r4   z@EnvironTests.test_serverProtocolIsNativeString.<locals>.<lambda>r   )r   r   r   N)r   rr   rt   r   r   rT   r   r   )r    ZserverProtocolr|   r   r$   r$   r%   !test_serverProtocolIsNativeString  s    
z.EnvironTests.test_serverProtocolIsNativeStringc                 C   s(   |  ddg dg}|| dd |S )z
        The C{'REMOTE_ADDR'} key of the C{environ} C{dict} passed to the
        application contains the address of the client making the request.
        r   r   r@   REMOTE_ADDRz192.168.1.1rQ   r   r   r    r   r$   r$   r%   test_remoteAddr  s    zEnvironTests.test_remoteAddrc                 C   s4   dd }| j ddg dg|d}|| dd |S )	z
        The C{'REMOTE_ADDR'} key of the C{environ} C{dict} passed to
        the application contains the address of the client making the
        request when connecting over IPv6.
        c                   S   s   t tddddS )NrG   ::1i  )Zpeer)r   r   r$   r$   r$   r%   rw     s    z8EnvironTests.test_remoteAddrIPv6.<locals>.channelFactoryr   r   r@   )rw   r   r   r   )r    rw   r   r$   r$   r%   test_remoteAddrIPv6  s    z EnvironTests.test_remoteAddrIPv6c              	      s     ddg dgdddg} fdd}||   ddg dgddd	g}| d
d   ddg dgddg}| dd   ddg dgddg}| d
d t||||gS )z
        HTTP request headers are copied into the C{environ} C{dict} passed to
        the application with a C{HTTP_} prefix added to their names.
        r   r   r@   Nr   bazquuxc                    s,   | \}}  |d d   |d d d S )NHTTP_FOOr   ZHTTP_BAZr   r   r   r6   r$   r%   r     s    z-EnvironTests.test_headers.<locals>.cbRendered)r   r   r   zbar,baz)zfoo-barr   ZHTTP_FOO_BARr   )r   zbar
	bazzbar 	bazr   )r    ZsingleValuer   Z
multiValueZ
withHyphenZ	multiLiner$   r6   r%   test_headers
  sL         
               zEnvironTests.test_headersc                 C   s(   |  ddg dg}|| dd |S )z
        The C{'wsgi.version'} key of the C{environ} C{dict} passed to the
        application has the value C{(1, 0)} indicating that this is a WSGI 1.0
        container.
        r   r   r@   zwsgi.version)rM   r   r   )r    ZversionDeferredr$   r$   r%   test_wsgiVersion&  s    zEnvironTests.test_wsgiVersionc                 C   s(   |  ddg dg}|| dd |S )z|
        The C{'wsgi.run_once'} key of the C{environ} C{dict} passed to the
        application is set to C{False}.
        r   r   r@   zwsgi.run_onceFr   )r    oncer$   r$   r%   test_wsgiRunOnce1  s    zEnvironTests.test_wsgiRunOncec                 C   s(   |  ddg dg}|| dd |S )z~
        The C{'wsgi.multithread'} key of the C{environ} C{dict} passed to the
        application is set to C{True}.
        r   r   r@   zwsgi.multithreadTr   )r    threadr$   r$   r%   test_wsgiMultithread;  s    z!EnvironTests.test_wsgiMultithreadc                 C   s(   |  ddg dg}|| dd |S )z
        The C{'wsgi.multiprocess'} key of the C{environ} C{dict} passed to the
        application is set to C{False}.
        r   r   r@   zwsgi.multiprocessFr   )r    Zprocessr$   r$   r%   test_wsgiMultiprocessE  s    z"EnvironTests.test_wsgiMultiprocessc                 C   sh   dd }t | _| ddg dg}|| dd || _| ddg dg}|| dd t||gS )	z
        The C{'wsgi.url_scheme'} key of the C{environ} C{dict} passed to the
        application has the request URL scheme.
        c                  S   s   t  } t  | _| S r/   )r   ZSSLr   r   r$   r$   r%   rw   V  s    
z7EnvironTests.test_wsgiURLScheme.<locals>.channelFactoryr   r   r@   zwsgi.url_schemer   Zhttps)r   rw   rQ   r   r   r   )r    rw   ZhttpDeferredZhttpsDeferredr$   r$   r%   test_wsgiURLSchemeO  s    zEnvironTests.test_wsgiURLSchemec                    s:   t t ddg dg} fdd}|| |S )a`  
        The C{'wsgi.errors'} key of the C{environ} C{dict} passed to the
        application is a file-like object (as defined in the U{Input and Errors
        Streams<http://www.python.org/dev/peps/pep-0333/#input-and-error-streams>}
        section of PEP 333) which converts bytes written to it into events for
        the logging system.
        r   r   r@   c                    s   | \}}|d }| d |dg |   d d d  d d d  d d	   d
 d d  d
 d d  d
 d	  t d d S )Nwsgi.errorssome message
another
message
r   message)r   systemZwsgiZisErrorrM   )r      )rr   
writelinesflushr   r8   rS   )r   r1   ZstartApplicationerrorsZeventsr    r$   r%   cbErrorst  s    
z.EnvironTests.test_wsgiErrors.<locals>.cbErrors)r   rO   r   rQ   r   )r    r  r  r$   r  r%   test_wsgiErrorsf  s    
zEnvironTests.test_wsgiErrorsc              	   C   s   t rtd|  \}}|  | |\}}|d }tjdd}|d W 5 Q R X | dt	| | t
|d j | dt|d j d	S )
a-  
        The C{'wsgi.errors'} file-like object from the C{environ} C{dict}
        expects writes of only native strings in Python 2. Some existing WSGI
        applications may write non-native (i.e. C{unicode}) strings so, for
        compatibility, these elicit only a warning in Python 2.
        zNot relevant in Python 3r   TrecordZfredrM   r   z5write() argument should be str, not u'fred' (unicode)N)r   r   r   rt   r   warningscatch_warningsrr   r   rS   UnicodeWarningcategoryr   r  )r    r|   r   r1   _r  caughtr$   r$   r%   0test_wsgiErrorsExpectsOnlyNativeStringsInPython2  s    z=EnvironTests.test_wsgiErrorsExpectsOnlyNativeStringsInPython2c                 C   sZ   t std|  \}}|  | |\}}|d }| t|jd}| dt	| dS )z
        The C{'wsgi.errors'} file-like object from the C{environ} C{dict}
        permits writes of only native strings in Python 3, and raises
        C{TypeError} for writes of non-native strings.
        zRelevant only in Python 3r   s   fredz1write() argument must be str, not b'fred' (bytes)N)
r   r   r   rt   r   r;   r   rr   r   r   )r    r|   r   r1   r  r  errorr$   r$   r%   0test_wsgiErrorsAcceptsOnlyNativeStringsInPython3  s    z=EnvironTests.test_wsgiErrorsAcceptsOnlyNativeStringsInPython3N)#r'   r(   r)   r*   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r	  r  r  r$   r$   r$   r%   r   v  s@    $


r   c                   @   s   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zd d! Zd"d# Zd$d% Zd&d' Zd(d) Zd*d+ Zd,d- Zd.S )/InputStreamTestMixinz
    A mixin for L{TestCase} subclasses which defines a number of tests against
    L{_InputStream}.  The subclass is expected to create a file-like object to
    be wrapped by an L{_InputStream} under test.
    c                 C   s   t d| jjf d S )Nz%s.getFile must be implemented)NotImplementedError	__class__r'   r6   r$   r$   r%   getFileType  s    z InputStreamTestMixin.getFileTypec                    sR   |    G  fdddt}dd }||\}}| ||tddg dgd g |
 |S )Nc                       s   e Zd Z fddZdS )zLInputStreamTestMixin._renderAndReturnReaderResult.<locals>.CustomizedRequestc                    s     | _ d S r/   )rq   )r    Zlengthr   r$   r%   rp     s    zVInputStreamTestMixin._renderAndReturnReaderResult.<locals>.CustomizedRequest.gotLengthN)r'   r(   r)   rp   r$   r  r$   r%   CustomizedRequest  s   r  c                    s   t   fdd}|fS )Nc                     s    fdd} | S )Nc                     s,   | \}}  |d  |dg  tdS )Nz
wsgi.inputr   r$   r   r   readerr   r$   r%   rK     s    
z}InputStreamTestMixin._renderAndReturnReaderResult.<locals>.appFactoryFactory.<locals>.applicationFactory.<locals>.applicationr$   r   r  r$   r%   rv     s    zhInputStreamTestMixin._renderAndReturnReaderResult.<locals>.appFactoryFactory.<locals>.applicationFactoryr   )r  rv   r$   r  r%   appFactoryFactory  s    zLInputStreamTestMixin._renderAndReturnReaderResult.<locals>.appFactoryFactoryZPUTr   r@   )r  r   r}   r   )r    r  rq   r  r  r   Z
appFactoryr$   r  r%   _renderAndReturnReaderResult  s"    
       z1InputStreamTestMixin._renderAndReturnReaderResultc                 C   s&   d}|  dd |}|| j| |S )zi
        Calling L{_InputStream.read} with no arguments returns the entire input
        stream.
           some bytes are herec                 S   s   |   S r/   readinputr$   r$   r%   r3     r4   z3InputStreamTestMixin.test_readAll.<locals>.<lambda>r  r   r   r    r\   r   r$   r$   r%   test_readAll  s    z!InputStreamTestMixin.test_readAllc                 C   s&   d}|  dd |}|| jd |S )z
        Calling L{_InputStream.read} with an integer returns that many bytes
        from the input stream, as long as it is less than or equal to the total
        number of bytes available.
        s   hello, world.c                 S   s
   |  dS N   r   r"  r$   r$   r%   r3     r4   z4InputStreamTestMixin.test_readSome.<locals>.<lambda>s   helr$  r%  r$   r$   r%   test_readSome  s    z"InputStreamTestMixin.test_readSomec                    s*   d |   fdd }|| j  |S )z
        Calling L{_InputStream.read} with an integer that is greater than the
        total number of bytes in the input stream returns all bytes in the
        input stream.
        r  c                    s   |  t d S r'  )r!  rS   r"  r\   r$   r%   r3     r4   z8InputStreamTestMixin.test_readMoreThan.<locals>.<lambda>r$  r   r$   r*  r%   test_readMoreThan  s    
 z&InputStreamTestMixin.test_readMoreThanc                 C   s2   d}dd }|  ||}|| j|dd  |S )z
        Calling L{_InputStream.read} a second time returns bytes starting from
        the position after the last byte returned by the previous read.
        s   some bytes, helloc                 S   s   |  d |   S r'  r   r"  r$   r$   r%   r!    s    
z1InputStreamTestMixin.test_readTwice.<locals>.readr(  Nr$  )r    r\   r!  r   r$   r$   r%   test_readTwice  s
    z#InputStreamTestMixin.test_readTwicec                 C   s&   d}|  dd |}|| j| |S )zy
        Calling L{_InputStream.read} with L{None} as an argument returns all
        bytes in the input stream.
        s   the entire streamc                 S   s
   |  d S r/   r   r"  r$   r$   r%   r3     r4   z4InputStreamTestMixin.test_readNone.<locals>.<lambda>r$  r%  r$   r$   r%   test_readNone
  s     z"InputStreamTestMixin.test_readNonec                 C   s&   d}|  dd |}|| j| |S )z
        Calling L{_InputStream.read} with a negative integer as an argument
        returns all bytes in the input stream.
        s   all of the inputc                 S   s
   |  dS Nr   r"  r$   r$   r%   r3     r4   z8InputStreamTestMixin.test_readNegative.<locals>.<lambda>r$  r%  r$   r$   r%   test_readNegative  s     z&InputStreamTestMixin.test_readNegativec                 C   s&   d}|  dd |}|| jd |S )zs
        Calling L{_InputStream.readline} with no argument returns one line from
        the input stream.
        s   hello
worldc                 S   s   |   S r/   readliner"  r$   r$   r%   r3   )  r4   z4InputStreamTestMixin.test_readline.<locals>.<lambda>s   hello
r$  r%  r$   r$   r%   test_readline"  s     z"InputStreamTestMixin.test_readlinec                 C   s&   d}|  dd |}|| jd |S )a  
        Calling L{_InputStream.readline} with an integer returns at most that
        many bytes, even if it is not enough to make up a complete line.

        COMPATIBILITY NOTE: the size argument is excluded from the WSGI
        specification, but is provided here anyhow, because useful libraries
        such as python stdlib's cgi.py assume their input file-like-object
        supports readline with a size argument. If you use it, be aware your
        application may not be portable to other conformant WSGI servers.
        s   goodbye
worldc                 S   s
   |  dS r'  r1  r"  r$   r$   r%   r3   ;  r4   z8InputStreamTestMixin.test_readlineSome.<locals>.<lambda>s   goor$  r%  r$   r$   r%   test_readlineSome.  s     z&InputStreamTestMixin.test_readlineSomec                 C   s&   d}|  dd |}|| jd |S )z
        Calling L{_InputStream.readline} with an integer which is greater than
        the number of bytes in the next line returns only the next line.
        s   some lines
of textc                 S   s
   |  dS )N   r1  r"  r$   r$   r%   r3   G  r4   z<InputStreamTestMixin.test_readlineMoreThan.<locals>.<lambda>s   some lines
r$  r%  r$   r$   r%   test_readlineMoreThan@  s     z*InputStreamTestMixin.test_readlineMoreThanc                 C   s*   d}dd }|  ||}|| jd |S )z
        Calling L{_InputStream.readline} a second time returns the line
        following the line returned by the first call.
        s    first line
second line
last linec                 S   s   |    |   S r/   r1  r"  r$   r$   r%   r2  R  s    z9InputStreamTestMixin.test_readlineTwice.<locals>.readlines   second line
r$  )r    r\   r2  r   r$   r$   r%   test_readlineTwiceL  s
    z'InputStreamTestMixin.test_readlineTwicec                 C   s&   d}|  dd |}|| jd |S )z~
        Calling L{_InputStream.readline} with L{None} as an argument returns
        one line from the input stream.
        s%   this is one line
this is another linec                 S   s
   |  d S r/   r1  r"  r$   r$   r%   r3   a  r4   z8InputStreamTestMixin.test_readlineNone.<locals>.<lambda>s   this is one line
r$  r%  r$   r$   r%   test_readlineNoneZ  s     z&InputStreamTestMixin.test_readlineNonec                 C   s&   d}|  dd |}|| jd |S )z
        Calling L{_InputStream.readline} with a negative integer as an argument
        returns one line from the input stream.
        s   input stream line one
line twoc                 S   s
   |  dS r.  r1  r"  r$   r$   r%   r3   m  r4   z<InputStreamTestMixin.test_readlineNegative.<locals>.<lambda>s   input stream line one
r$  r%  r$   r$   r%   test_readlineNegativef  s     z*InputStreamTestMixin.test_readlineNegativec                 C   s,   d}|  dd |}|| jdddg |S )z
        Calling L{_InputStream.readlines} with no arguments returns a list of
        all lines from the input stream.
        s   alice
bob
carolc                 S   s   |   S r/   	readlinesr"  r$   r$   r%   r3   y  r4   z5InputStreamTestMixin.test_readlines.<locals>.<lambda>s   alice
s   bob
s   carolr$  r%  r$   r$   r%   test_readlinesr  s     z#InputStreamTestMixin.test_readlinesc                    s.   d}  dd |} fdd}|| |S )z
        Calling L{_InputStream.readlines} with an integer as an argument
        returns a list of lines from the input stream with the argument serving
        as an approximate bound on the total number of bytes to read.
        s   123
456
789
0c                 S   s
   |  dS )N   r:  r"  r$   r$   r%   r3     r4   z9InputStreamTestMixin.test_readlinesSome.<locals>.<lambda>c                    s     | d d ddg d S )Nr  s   123
s   456
r   )linesr6   r$   r%   cbLines  s    z8InputStreamTestMixin.test_readlinesSome.<locals>.cbLines)r  r   )r    r\   r   r?  r$   r6   r%   test_readlinesSome~  s     
z'InputStreamTestMixin.test_readlinesSomec                 C   s,   d}|  dd |}|| jdddg |S )z
        Calling L{_InputStream.readlines} with an integer which is greater than
        the total number of bytes in the input stream returns a list of all
        lines from the input.
        s"   one potato
two potato
three potatoc                 S   s
   |  dS )Nd   r:  r"  r$   r$   r%   r3     r4   z=InputStreamTestMixin.test_readlinesMoreThan.<locals>.<lambda>s   one potato
s   two potato
s   three potator$  r%  r$   r$   r%   test_readlinesMoreThan  s     z+InputStreamTestMixin.test_readlinesMoreThanc                 C   s.   d}dd }|  ||}|| jddg |S )z
        Calling L{_InputStream.readlines} after a call to L{_InputStream.read}
        returns lines starting at the byte after the last byte returned by the
        C{read} call.
        s   hello
world
fooc                 S   s   |  d |  S )N   )r!  r;  r"  r$   r$   r%   r;    s    
z?InputStreamTestMixin.test_readlinesAfterRead.<locals>.readliness   orld
r:   r$  )r    r\   r;  r   r$   r$   r%   test_readlinesAfterRead  s
    z,InputStreamTestMixin.test_readlinesAfterReadc                 C   s*   d}|  dd |}|| jddg |S )zy
        Calling L{_InputStream.readlines} with L{None} as an argument returns
        all lines from the input.
        s   one fish
two fish
c                 S   s
   |  d S r/   r:  r"  r$   r$   r%   r3     r4   z9InputStreamTestMixin.test_readlinesNone.<locals>.<lambda>s	   one fish
s	   two fish
r$  r%  r$   r$   r%   test_readlinesNone  s     z'InputStreamTestMixin.test_readlinesNonec                 C   s*   d}|  dd |}|| jddg |S )z
        Calling L{_InputStream.readlines} with a negative integer as an
        argument returns a list of all lines from the input.
        s   red fish
blue fish
c                 S   s
   |  dS r.  r:  r"  r$   r$   r%   r3     r4   z=InputStreamTestMixin.test_readlinesNegative.<locals>.<lambda>s	   red fish
s
   blue fish
r$  r%  r$   r$   r%   test_readlinesNegative  s     z+InputStreamTestMixin.test_readlinesNegativec                 C   s*   d}|  dd |}|| jddg |S )zV
        Iterating over L{_InputStream} produces lines from the input stream.
           green eggs
and ham
c                 S   s   t | S r/   )listr"  r$   r$   r%   r3     r4   z4InputStreamTestMixin.test_iterable.<locals>.<lambda>s   green eggs
   and ham
r$  r%  r$   r$   r%   test_iterable  s    z"InputStreamTestMixin.test_iterablec                 C   s.   d}dd }|  ||}|| jddg |S )z
        Iterating over L{_InputStream} after calling L{_InputStream.read}
        produces lines from the input stream starting from the first byte after
        the last byte returned by the C{read} call.
        rG  c                 S   s   |  d t| S r'  )r!  rH  r"  r$   r$   r%   iterate  s    
z<InputStreamTestMixin.test_iterableAfterRead.<locals>.iterates   en eggs
rI  r$  )r    r\   rK  r   r$   r$   r%   test_iterableAfterRead  s
    z+InputStreamTestMixin.test_iterableAfterReadN)r'   r(   r)   r*   r  r  r&  r)  r+  r,  r-  r0  r3  r4  r6  r7  r8  r9  r<  r@  rB  rD  rE  rF  rJ  rL  r$   r$   r$   r%   r    s.   
r  c                   @   s   e Zd ZdZdd ZdS )InputStreamStringIOTestsz
    Tests for L{_InputStream} when it is wrapped around a
    L{StringIO.StringIO}.

    This is only available in Python 2.
    c                 C   s6   zddl m } W n tk
r,   tdY nX |S d S )Nr   StringIOz#StringIO.StringIO is not available.)rO  ImportErrorr   r    rO  r$   r$   r%   r    s
    z$InputStreamStringIOTests.getFileTypeNr'   r(   r)   r*   r  r$   r$   r$   r%   rM    s   rM  c                   @   s   e Zd ZdZdd ZdS )InputStreamCStringIOTestsz
    Tests for L{_InputStream} when it is wrapped around a
    L{cStringIO.StringIO}.

    This is only available in Python 2.
    c                 C   s6   zddl m} W n tk
r,   tdY nX |S d S )Nr   rN  z$cStringIO.StringIO is not available.)	cStringIOrO  rP  r   rQ  r$   r$   r%   r    s
    z%InputStreamCStringIOTests.getFileTypeNrR  r$   r$   r$   r%   rS    s   rS  c                   @   s   e Zd ZdZdd ZdS )InputStreamBytesIOTestszO
    Tests for L{_InputStream} when it is wrapped around an L{io.BytesIO}.
    c                 C   s   ddl m} |S )Nr   )BytesIO)iorV  )r    rV  r$   r$   r%   r    s    z#InputStreamBytesIOTests.getFileTypeNrR  r$   r$   r$   r%   rU    s   rU  c                   @   s   e Zd ZdZdd ZdS )InputStreamTemporaryFileTestszZ
    Tests for L{_InputStream} when it is wrapped around a L{tempfile.TemporaryFile}.
    c                 C   s   t jS r/   )tempfileZTemporaryFiler6   r$   r$   r%   r    s    z)InputStreamTemporaryFileTests.getFileTypeNrR  r$   r$   r$   r%   rX    s   rX  c                   @   s   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zd d! Zd"d# Zd$d% Zd&d' Zd(d) Zd*d+ Zd,S )-StartResponseTestszl
    Tests for the I{start_response} parameter passed to the application object
    by L{WSGIResource}.
    c                    sZ   t   dd } \}} fdd}|| || fddddg d	gd
g 	 |S )z
        The response status passed to the I{start_response} callable is written
        as the status of the response to the request.
        c                  S   s   dd } | S )Nc                 S   s   |dg  t dS )Nz107 Strange messager$   r   r0   r$   r$   r%   rK   !  s    
zOStartResponseTests.test_status.<locals>.applicationFactory.<locals>.applicationr$   r   r$   r$   r%   rv      s    z:StartResponseTests.test_status.<locals>.applicationFactoryc                    s     jj d d S )Ns   HTTP/1.1 107 Strange messager8   r   writtengetvalue
startswithignoredr{   r    r$   r%   r   '  s
    z2StartResponseTests.test_status.<locals>.cbRenderedc                      s    S r/   r$   r$   r   r$   r%   r3   /  r4   z0StartResponseTests.test_status.<locals>.<lambda>r   r   r@   Nr   r   r   r}   r    rv   r   ru   r   r$   rb  r%   test_status  s"    
 
      zStartResponseTests.test_statusc                    sL   t rdndfdd} |\}}|   fdd} |t|S )z
        The response status passed to the I{start_response} callable MUST be a
        native string in Python 2 and Python 3.
        s   200 OKr   c                    s   | g  t dS )Nr$   r[  r0   )statusr$   r%   rK   ;  s    
zEStartResponseTests.test_statusMustBeNativeString.<locals>.applicationc                    s*   t r dt|  n dt|  d S )Nz)status must be str, not b'200 OK' (bytes)z+status must be str, not u'200 OK' (unicode)r   r   r   r  r6   r$   r%   checkMessageB  s      zFStartResponseTests.test_statusMustBeNativeString.<locals>.checkMessager   r   rt   assertFailurer   r   r    rK   r|   r   ri  r$   )r    rf  r%   test_statusMustBeNativeString4  s    z0StartResponseTests.test_statusMustBeNativeStringc                    sr    tddd  t  fdd} \}}fdd}|| ||fddd	d
g dgdg 	 |S )a  
        Verify that if the response headers given by C{appHeaders} are passed
        to the I{start_response} callable, then the response header lines given
        by C{expectedHeaders} plus I{Server} and I{Date} header lines are
        included in the response.
        ZdatetimeToStringc                   S   s   dS )NZTuesdayr$   r$   r$   r$   r%   r3   U  r4   z1StartResponseTests._headersTest.<locals>.<lambda>c                     s    fdd} | S )Nc                    s   |d  t dS r~   r[  r0   
appHeadersr$   r%   rK   Z  s    
zPStartResponseTests._headersTest.<locals>.applicationFactory.<locals>.applicationr$   r   rn  r$   r%   rv   Y  s    z;StartResponseTests._headersTest.<locals>.applicationFactoryc                    s`    j j }|dd\}}|ddd  }|  ddt dg }|  || d S )Nr   rM   s   
s   Date: Tuesdays   Server: s   Transfer-Encoding: chunked)r   r]  r^  r   sortr   r   )ra  r   ry   restZheaderLinesZallExpectedHeaders)r{   expectedHeadersr    r$   r%   r   `  s    z3StartResponseTests._headersTest.<locals>.cbRenderedc                      s    S r/   r$   r$   r   r$   r%   r3   p  r4   r   r   r@   N)Zpatchr   r   r   r   r}   )r    ro  rr  rv   r   ru   r   r$   )ro  r{   rr  r    r%   _headersTestM  s$    
 
      zStartResponseTests._headersTestc                 C   s   |  ddgddgS )z
        The headers passed to the I{start_response} callable are included in
        the response as are the required I{Date} and I{Server} headers and the
        necessary connection (hop to hop) header I{Transfer-Encoding}.
        r   r   s	   Baz: quuxs   Foo: barrs  r6   r$   r$   r%   r   t  s    zStartResponseTests.test_headersc                    sF   dg  fdd} |\}}|  fdd}|t|S )zb
        The headers passed to the I{start_response} callable MUST be a
        sequence.
        r   rU   c                    s   |dt   t dS r~   r[  r0   )ry   r$   r%   rK     s    zBStartResponseTests.test_headersMustBeSequence.<locals>.applicationc                    s     t| d d S )NzKheaders must be a list, not <(list_?|sequence)iterator .+> [(]\1iterator[)]ZassertRegexr   rh  r6   r$   r%   ri    s     zCStartResponseTests.test_headersMustBeSequence.<locals>.checkMessager   rt   rk  r   r   rl  r$   )ry   r    r%   test_headersMustBeSequence  s    z-StartResponseTests.test_headersMustBeSequencec              	   C   s|   dd }|  |\}}tjdd}|  | |}W 5 Q R X | dt| | t|d j | dt	|d j
 dS )	a  
        According to PEP-3333, the headers passed to the I{start_response}
        callable MUST be a plain list:

          The response_headers argument ... must be a Python list; i.e.
          type(response_headers) is ListType

        However, for bug-compatibility, any sequence is accepted. In both
        Python 2 and Python 3, only a warning is issued when a sequence other
        than a list is encountered.
        c                 S   s   |dd t dS )Nr   ))notrH  r$   r[  r0   r$   r$   r%   rK     s    
zEStartResponseTests.test_headersShouldBePlainList.<locals>.applicationTr
  rM   r   z8headers should be a list, not (('not', 'list'),) (tuple)Nr   r  r  rt   r   r   rS   RuntimeWarningr  r   r  r    rK   r|   r   r  r$   r$   r%   test_headersShouldBePlainList  s    z0StartResponseTests.test_headersShouldBePlainListc                    sD   d  fdd} |\}}|  fdd}|t|S )zb
        Each header passed to the I{start_response} callable MUST be a
        sequence.
        ru  c                    s   |dt  g t dS r~   r[  r0   )headerr$   r%   rK     s    zFStartResponseTests.test_headersMustEachBeSequence.<locals>.applicationc                    s     t| d d S )Nz[header must be a [(]str, str[)] tuple, not <(tuple_?|sequence)iterator .+> [(]\1iterator[)]rv  rh  r6   r$   r%   ri    s     zGStartResponseTests.test_headersMustEachBeSequence.<locals>.checkMessagerw  rl  r$   )r~  r    r%   test_headersMustEachBeSequence  s    z1StartResponseTests.test_headersMustEachBeSequencec              	   C   s|   dd }|  |\}}tjdd}|  | |}W 5 Q R X | dt| | t|d j | dt	|d j
 dS )	a  
        According to PEP-3333, each header passed to the I{start_response}
        callable should be a tuple:

          The response_headers argument is a list of (header_name,
          header_value) tuples

        However, for bug-compatibility, any 2 element sequence is also
        accepted. In both Python 2 and Python 3, only a warning is issued when
        a sequence other than a tuple is encountered.
        c                 S   s   |dddgg t dS )Nr   ry  tupler$   r[  r0   r$   r$   r%   rK     s    zEStartResponseTests.test_headersShouldEachBeTuple.<locals>.applicationTr
  rM   r   z@header should be a (str, str) tuple, not ['not', 'tuple'] (list)Nrz  r|  r$   r$   r%   test_headersShouldEachBeTuple  s    z0StartResponseTests.test_headersShouldEachBeTuplec                    s<   dd }  |\}}|   fdd} |t|S )z
        Each header passed to the I{start_response} callable MUST hold a key
        and a value, and ONLY a key and a value.
        c                 S   s   |ddg t dS )Nr   )ZtooZmanyZcooksr$   r[  r0   r$   r$   r%   rK     s    zMStartResponseTests.test_headersShouldEachHaveKeyAndValue.<locals>.applicationc                    s     dt|  d S )Nz?header must be a (str, str) tuple, not ('too', 'many', 'cooks')r   r   rh  r6   r$   r%   ri    s    zNStartResponseTests.test_headersShouldEachHaveKeyAndValue.<locals>.checkMessagerw  rl  r$   r6   r%   %test_headersShouldEachHaveKeyAndValue  s
    z8StartResponseTests.test_headersShouldEachHaveKeyAndValuec                    sN   t rdnd  fdd}|\}}|   fdd}|t|S )z
        Each header key passed to the I{start_response} callable MUST be at
        native string in Python 2 and Python 3.
        s   keyr   c                    s   |d dfg t dS )Nr   rU   r$   r[  r0   )r   r$   r%   rK     s    zHStartResponseTests.test_headerKeyMustBeNativeString.<locals>.applicationc                    s    d f t|  d S )Nz2header must be (str, str) tuple, not (%r, 'value')r  rh  r   r    r$   r%   ri    s    zIStartResponseTests.test_headerKeyMustBeNativeString.<locals>.checkMessagerj  rl  r$   r  r%    test_headerKeyMustBeNativeString  s    z3StartResponseTests.test_headerKeyMustBeNativeStringc                    sN   t rdndfdd} |\}}|   fdd} |t|S )z
        Each header value passed to the I{start_response} callable MUST be at
        native string in Python 2 and Python 3.
        s   valuerU   c                    s   |dd fg t dS )Nr   r   r$   r[  r0   )rU   r$   r%   rK     s    zJStartResponseTests.test_headerValueMustBeNativeString.<locals>.applicationc                    s     df t|  d S )Nz0header must be (str, str) tuple, not ('key', %r)r  rh  r    rU   r$   r%   ri    s    zKStartResponseTests.test_headerValueMustBeNativeString.<locals>.checkMessagerj  rl  r$   r  r%   "test_headerValueMustBeNativeString  s    z5StartResponseTests.test_headerValueMustBeNativeStringc                 C   s   |  dgdgS )z
        If I{Content-Type} is included in the headers passed to the
        I{start_response} callable, one I{Content-Type} header is included in
        the response.
        )r   zmonkeys are greats   Content-Type: monkeys are greatrt  r6   r$   r$   r%   #test_applicationProvidedContentType#  s    z6StartResponseTests.test_applicationProvidedContentTypec                 C   s   |  ddddgg S )z
        If either I{Server} or I{Date} is included in the headers passed to the
        I{start_response} callable, they are disregarded.
        )Zserverr   )ZServerr   )dater   )ZdATEr   rt  r6   r$   r$   r%   %test_applicationProvidedServerAndDate.  s     z8StartResponseTests.test_applicationProvidedServerAndDatec                    sp   t   g  fddfdd} \}}fdd}|| || fddd	d
g dgdg 	 |S )a  
        Nothing is written in response to a request when the I{start_response}
        callable is invoked.  If the iterator returned by the application
        object produces only empty strings, the response is written after the
        last element is produced.
        c                      s     jj  d S r/   appendr   r]  r^  r$   r{   intermediateValuesr$   r%   r  C  s    z:StartResponseTests.test_delayedUntilReturn.<locals>.recordc                     s    fdd} | S )Nc                 3   s   |dddg dV     d S )Nr   r   r   r4   r$   r0   r
  r$   r%   rK   G  s    z[StartResponseTests.test_delayedUntilReturn.<locals>.applicationFactory.<locals>.applicationr$   r   r
  r$   r%   rv   F  s    zFStartResponseTests.test_delayedUntilReturn.<locals>.applicationFactoryc                    s     dg d S )Nr4   r   r`  r  r    r$   r%   r   N  s    z>StartResponseTests.test_delayedUntilReturn.<locals>.cbRenderedc                      s    S r/   r$   r$   r   r$   r%   r3   T  r4   z<StartResponseTests.test_delayedUntilReturn.<locals>.<lambda>r   r   r@   Nrc  rd  r$   r{   r  r  r    r%   test_delayedUntilReturn9  s&    
 
      z*StartResponseTests.test_delayedUntilReturnc                    sp   t   g  fddfdd} \}}fdd}|| || fddd	d
g dgdg 	 |S )a  
        Nothing is written in response to a request when the I{start_response}
        callable is invoked.  Once a non-empty string has been produced by the
        iterator returned by the application object, the response status and
        headers are written.
        c                      s     jj  d S r/   r  r$   r  r$   r%   r  c  s    z;StartResponseTests.test_delayedUntilContent.<locals>.recordc                     s    fdd} | S )Nc                 3   s(   |ddg dV     dV     d S )Nr   r   r4   r:   r$   r0   r
  r$   r%   rK   g  s
    z\StartResponseTests.test_delayedUntilContent.<locals>.applicationFactory.<locals>.applicationr$   r   r
  r$   r%   rv   f  s    zGStartResponseTests.test_delayedUntilContent.<locals>.applicationFactoryc                    s      d   d  d S )Nr   rM   )assertFalser8   r`  r  r$   r%   r   p  s    z?StartResponseTests.test_delayedUntilContent.<locals>.cbRenderedc                      s    S r/   r$   r$   r   r$   r%   r3   w  r4   z=StartResponseTests.test_delayedUntilContent.<locals>.<lambda>r   r   r@   Nrc  rd  r$   r  r%   test_delayedUntilContentY  s&    	
 
      z+StartResponseTests.test_delayedUntilContentc                    sp   t   g  fddfdd} \}}fdd}|| || fddd	d
g dgdg 	 |S )z
        Content produced by the iterator returned by the application object is
        written to the request as it is produced.
        c                      s     jj  d S r/   r  r$   r  r$   r%   r    s    z/StartResponseTests.test_content.<locals>.recordc                     s    fdd} | S )Nc                 3   s(   |ddg dV     dV     d S )Nr   r   6r:      barr$   r0   r
  r$   r%   rK     s
    zPStartResponseTests.test_content.<locals>.applicationFactory.<locals>.applicationr$   r   r
  r$   r%   rv     s    z;StartResponseTests.test_content.<locals>.applicationFactoryc                    s0     d d   d d d S Nr   r:   rM   s   foobarr   r   r`  r  r$   r%   r     s    z3StartResponseTests.test_content.<locals>.cbRenderedc                      s    S r/   r$   r$   r   r$   r%   r3     r4   z1StartResponseTests.test_content.<locals>.<lambda>r   r   r@   Nrc  rd  r$   r  r%   test_content|  s&    	
 
      zStartResponseTests.test_contentc                    sZ   t   dd } \}} fdd}|| || fddddg d	gd
g 	 |S )z
        If the I{start_response} callable is invoked multiple times before a
        data for the response body is produced, the values from the last call
        are used.
        c                  S   s   dd } | S )Nc                 S   s   |dg  |dg  t dS )N100 Fooz200 Barr$   r[  r0   r$   r$   r%   rK     s    

z^StartResponseTests.test_multipleStartResponse.<locals>.applicationFactory.<locals>.applicationr$   r   r$   r$   r%   rv     s    zIStartResponseTests.test_multipleStartResponse.<locals>.applicationFactoryc                    s     jj d d S )Ns   HTTP/1.1 200 Bar
r\  r`  rb  r$   r%   r     s
    zAStartResponseTests.test_multipleStartResponse.<locals>.cbRenderedc                      s    S r/   r$   r$   r   r$   r%   r3     r4   z?StartResponseTests.test_multipleStartResponse.<locals>.<lambda>r   r   r@   Nrc  rd  r$   rb  r%   test_multipleStartResponse  s"    
 
      z-StartResponseTests.test_multipleStartResponsec                    sZ   t   dd } \}} fdd}|| || fddddg d	gd
g 	 |S )z
        If the I{start_response} callable is invoked with a third positional
        argument before the status and headers have been written to the
        response, the status and headers become the newly supplied values.
        c                  S   s   dd } | S )Nc                 S   s   |dg t t dd f tdS )Nr  r   r$   )rP   r   r0   r$   r$   r%   rK     s    zcStartResponseTests.test_startResponseWithException.<locals>.applicationFactory.<locals>.applicationr$   r   r$   r$   r%   rv     s    zNStartResponseTests.test_startResponseWithException.<locals>.applicationFactoryc                    s     jj d d S )Ns   HTTP/1.1 100 Foo
r\  r`  rb  r$   r%   r     s
    zFStartResponseTests.test_startResponseWithException.<locals>.cbRenderedc                      s    S r/   r$   r$   r   r$   r%   r3     r4   zDStartResponseTests.test_startResponseWithException.<locals>.<lambda>r   r   r@   Nrc  rd  r$   rb  r%   test_startResponseWithException  s"    
 
      z2StartResponseTests.test_startResponseWithExceptionc                    s   t   G dd dt}z
| W n   t Y nX g fdd} \}} fdd}|| || fddd	d
g dgdg 	 |S )z
        If the I{start_response} callable is invoked with a third positional
        argument after the status and headers have been written to the
        response, the supplied I{exc_info} values are re-raised to the
        application.
        c                   @   s   e Zd ZdS )zPStartResponseTests.test_startResponseWithExceptionTooLate.<locals>.SomeExceptionN)r'   r(   r)   r$   r$   r$   r%   SomeException  s   r  c                     s    fdd} | S )Nc                 3   s>   |dg  dV  z|dg   W n    t  Y nX d S )Nr   r:   z500 ERR)r  r   r0   excInforeraisedr$   r%   rK     s    
zjStartResponseTests.test_startResponseWithExceptionTooLate.<locals>.applicationFactory.<locals>.applicationr$   r   r  r$   r%   rv     s    zUStartResponseTests.test_startResponseWithExceptionTooLate.<locals>.applicationFactoryc                    s     jj d d d d  d d d  d d j}d }t|t	t
krvdnd t|d  d S )Ns   HTTP/1.1 200 OK
r   rM   r  )r8   r   r]  r^  r_  r   tb_next	traceback
extract_tbr   r\   )ra  Ztb1Ztb2r{   r  r  r    r$   r%   r     s    zMStartResponseTests.test_startResponseWithExceptionTooLate.<locals>.cbRenderedc                      s    S r/   r$   r$   r   r$   r%   r3     r4   zKStartResponseTests.test_startResponseWithExceptionTooLate.<locals>.<lambda>r   r   r@   N)r   rP   r   r   r   r}   )r    r  rv   r   ru   r   r$   r  r%   &test_startResponseWithExceptionTooLate  s.    


 
      z9StartResponseTests.test_startResponseWithExceptionTooLatec                    sp   t   g  fddfdd} \}}fdd}|| || fddd	d
g dgdg 	 |S )z
        I{start_response} returns the I{write} callable which can be used to
        write bytes to the response body without buffering.
        c                      s     jj  d S r/   r  r$   r  r$   r%   r    s    z-StartResponseTests.test_write.<locals>.recordc                     s    fdd} | S )Nc                    s0   |ddg}|d    |d    t dS )Nr  r  r:   r  r$   r[  r1   r2   rr   r
  r$   r%   rK     s    zNStartResponseTests.test_write.<locals>.applicationFactory.<locals>.applicationr$   r   r
  r$   r%   rv     s    z9StartResponseTests.test_write.<locals>.applicationFactoryc                    s0     d d   d d d S r  r  r`  r  r$   r%   r   (  s    z1StartResponseTests.test_write.<locals>.cbRenderedc                      s    S r/   r$   r$   r   r$   r%   r3   3  r4   z/StartResponseTests.test_write.<locals>.<lambda>r   r   r@   Nrc  rd  r$   r  r%   
test_write  s&    

 
      zStartResponseTests.test_writec                    s<   dd }  |\}}|   fdd} |t|S )zj
        The C{write} callable returned from C{start_response} only accepts
        byte strings.
        c                 S   s   |dg }|d t dS )Nr   Zbogusr$   r[  r  r$   r$   r%   rK   =  s    
zHStartResponseTests.test_writeAcceptsOnlyByteStrings.<locals>.applicationc                    s*   t r dt|  n dt|  d S )Nz0Can only write bytes to a transport, not 'bogus'z1Can only write bytes to a transport, not u'bogus'rg  rh  r6   r$   r%   ri  E  s    zIStartResponseTests.test_writeAcceptsOnlyByteStrings.<locals>.checkMessagerw  rl  r$   r6   r%    test_writeAcceptsOnlyByteStrings8  s
    
z3StartResponseTests.test_writeAcceptsOnlyByteStringsN)r'   r(   r)   r*   re  rm  rs  r   rx  r}  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r$   r$   r$   r%   rZ    s,   ' #%8&rZ  c                   @   sx   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd ZdS )ApplicationTestszd
    Tests for things which are done to the application object and the iterator
    it returns.
    c                 C   s*   t | _ t | _| j  | | jj d S r/   )r   r	   rZ   startZ
addCleanupstopr6   r$   r$   r%   enableThreadsX  s    
zApplicationTests.enableThreadsc              	      sp   t   G dd d}| fdd} \}} fdd}|| || fddd	d
g dg |S )z
        If the application object returns an iterator which also has a I{close}
        method, that method is called after iteration is complete.
        c                   @   s$   e Zd Zdd Zdd Zdd ZdS )z+ApplicationTests.test_close.<locals>.Resultc                 S   s
   d| _ d S )NTopenr6   r$   r$   r%   rA   g  s    z4ApplicationTests.test_close.<locals>.Result.__init__c                 s   s"   t dD ]}| jrt|V  qd S r'  )ranger  r   )r    ir$   r$   r%   __iter__j  s    z4ApplicationTests.test_close.<locals>.Result.__iter__c                 S   s
   d| _ d S )NFr  r6   r$   r$   r%   closeo  s    z1ApplicationTests.test_close.<locals>.Result.closeNr'   r(   r)   rA   r  r  r$   r$   r$   r%   Resultf  s   r  c                     s    fdd} | S )Nc                    s   |ddg  S )Nr   r   3r$   r0   r   r$   r%   rK   t  s    zLApplicationTests.test_close.<locals>.applicationFactory.<locals>.applicationr$   r   r   r$   r%   rv   s  s    z7ApplicationTests.test_close.<locals>.applicationFactoryc                    s*     jj d j d S )Ns   012)r   r   r   r]  r^  r  r  r`  r{   r   r    r$   r%   r   z  s    
z/ApplicationTests.test_close.<locals>.cbRenderedc                      s    S r/   r$   r$   r   r$   r%   r3     r4   z-ApplicationTests.test_close.<locals>.<lambda>r   r   r@   rc  )r    r  rv   r   ru   r   r$   r  r%   
test_close_  s"    
 
    zApplicationTests.test_closec              	      sX      g   fdd} \}} fdd}|| ||tddg dg |S )zu
        The application object is invoked and iterated in a thread which is not
        the reactor thread.
        c                     s    fdd} | S )Nc                    s*    fdd}  t  |ddg | S )Nc                  3   s(   t dD ]}  t  t| V  qd S r'  )r  r  r   r   )r  invokedr$   r%   r     s    zpApplicationTests.test_applicationCalledInThread.<locals>.applicationFactory.<locals>.application.<locals>.resultr   r  )r  r   )r1   r2   r   r  r$   r%   rK     s    z`ApplicationTests.test_applicationCalledInThread.<locals>.applicationFactory.<locals>.applicationr$   r   r  r$   r%   rv     s    zKApplicationTests.test_applicationCalledInThread.<locals>.applicationFactoryc                    s&    t   tt d d S )NrM   )ZassertNotInr   r   rS   setr`  r  r    r$   r%   r     s    zCApplicationTests.test_applicationCalledInThread.<locals>.cbRenderedr   r   r@   )r  r   r   r}   r   rd  r$   r  r%   test_applicationCalledInThread  s     
     z/ApplicationTests.test_applicationCalledInThreadc              	      sj      g  G  fdddt}dd }|\}} fdd}|| ||tddg d	g |S )
z
        The I{write} callable returned by I{start_response} calls the request's
        C{write} method in the reactor thread.
        c                       s   e Zd Z fddZdS )zCApplicationTests.test_writeCalledFromThread.<locals>.ThreadVerifierc                    s     t  t| |S r/   r  r   r   rr   r    r\   r  r$   r%   rr     s    zIApplicationTests.test_writeCalledFromThread.<locals>.ThreadVerifier.writeNr'   r(   r)   rr   r$   r  r$   r%   ThreadVerifier  s   r  c                  S   s   dd } | S )Nc                 S   s   |dg }|d t dS )Nr   r:   r$   r[  r  r$   r$   r%   rK     s    
z\ApplicationTests.test_writeCalledFromThread.<locals>.applicationFactory.<locals>.applicationr$   r   r$   r$   r%   rv     s    zGApplicationTests.test_writeCalledFromThread.<locals>.applicationFactoryc                    s    t tt g d S r/   r   r  r   r`  r  r$   r%   r     s    z?ApplicationTests.test_writeCalledFromThread.<locals>.cbRenderedr   r   r@   r  r   r   r   r}   r   r    r  rv   r   ru   r   r$   r  r%   test_writeCalledFromThread  s"    
     z+ApplicationTests.test_writeCalledFromThreadc              	      sj      g  G  fdddt}dd }|\}} fdd}|| ||tddg d	g |S )
z
        Strings produced by the iterator returned by the application object are
        written to the request in the reactor thread.
        c                       s   e Zd Z fddZdS )zMApplicationTests.test_iteratedValuesWrittenFromThread.<locals>.ThreadVerifierc                    s     t  t| |S r/   r  r  r  r$   r%   rr     s    zSApplicationTests.test_iteratedValuesWrittenFromThread.<locals>.ThreadVerifier.writeNr  r$   r  r$   r%   r    s   r  c                  S   s   dd } | S )Nc                 s   s   |dg  dV  d S )Nr   r:   r$   r0   r$   r$   r%   rK     s    
zfApplicationTests.test_iteratedValuesWrittenFromThread.<locals>.applicationFactory.<locals>.applicationr$   r   r$   r$   r%   rv     s    zQApplicationTests.test_iteratedValuesWrittenFromThread.<locals>.applicationFactoryc                    s    t tt g d S r/   r  r`  r  r$   r%   r     s    zIApplicationTests.test_iteratedValuesWrittenFromThread.<locals>.cbRenderedr   r   r@   r  r  r$   r  r%   $test_iteratedValuesWrittenFromThread  s"    
     z5ApplicationTests.test_iteratedValuesWrittenFromThreadc              	      sj      g  G  fdddt}dd }|\}} fdd}|| ||tddg d	g |S )
zY
        The response status is set on the request object in the reactor thread.
        c                       s   e Zd Z fddZdS )zEApplicationTests.test_statusWrittenFromThread.<locals>.ThreadVerifierc                    s     t  t| ||S r/   )r  r   r   setResponseCode)r    coder  r  r$   r%   r    s    zUApplicationTests.test_statusWrittenFromThread.<locals>.ThreadVerifier.setResponseCodeN)r'   r(   r)   r  r$   r  r$   r%   r    s   r  c                  S   s   dd } | S )Nc                 S   s   |dg  t dS r~   r[  r0   r$   r$   r%   rK     s    
z^ApplicationTests.test_statusWrittenFromThread.<locals>.applicationFactory.<locals>.applicationr$   r   r$   r$   r%   rv     s    zIApplicationTests.test_statusWrittenFromThread.<locals>.applicationFactoryc                    s    t tt g d S r/   r  r`  r  r$   r%   r     s    zAApplicationTests.test_statusWrittenFromThread.<locals>.cbRenderedr   r   r@   r  r  r$   r  r%   test_statusWrittenFromThread  s"    
     z-ApplicationTests.test_statusWrittenFromThreadc              	      sv   G dd dt }d_fdd  fdd}|\}}fdd	}|| ||td
dg dg |tS )z
        If the request connection is lost while the application object is being
        iterated, iteration is stopped.
        c                   @   s   e Zd ZdZdd ZdS )zSApplicationTests.test_connectionClosedDuringIteration.<locals>.UnreliableConnectionz
            This is a request which pretends its connection is lost immediately
            after the first write is done to it.
            c                 S   s   |  ttd d S )NzNo more connection)connectionLostr   r   r  r$   r$   r%   rr     s    zYApplicationTests.test_connectionClosedDuringIteration.<locals>.UnreliableConnection.writeN)r'   r(   r)   r*   rr   r$   r$   r$   r%   UnreliableConnection  s   r  Fc                   3   s   dV  d _ tdd S )Nr:   TzShould not have gotten here)badIterrP   r$   r6   r$   r%   appIter  s    zFApplicationTests.test_connectionClosedDuringIteration.<locals>.appIterc                     s    fdd} | S )Nc                    s   |dg    S Nr   r$   r0   r  r$   r%   rK     s    
zfApplicationTests.test_connectionClosedDuringIteration.<locals>.applicationFactory.<locals>.applicationr$   r   r  r$   r%   rv     s    zQApplicationTests.test_connectionClosedDuringIteration.<locals>.applicationFactoryc                    s      jd d S )Nz!Should not have resumed iteration)r  r  r`  r6   r$   r%   r      s    zIApplicationTests.test_connectionClosedDuringIteration.<locals>.cbRenderedr   r   r@   )r   r  r   r   r}   r   rk  r   )r    r  rv   r   ru   r   r$   )r  r    r%   $test_connectionClosedDuringIteration  s"    
     z5ApplicationTests.test_connectionClosedDuringIterationc                    s^   t   fdd} \}}fdd}|| ||fddddg d	gd g 	 |S )
Nc                      s    S r/   r$   r$   r   r$   r%   rv   .  s    zEApplicationTests._internalServerErrorTest.<locals>.applicationFactoryc                    s6    t}t|d  jj d d S )NrM   s"   HTTP/1.1 500 Internal Server Error)	rV   r<   r   rS   r8   r   r]  r^  r_  )ra  r  rb  r$   r%   r   2  s    
z=ApplicationTests._internalServerErrorTest.<locals>.cbRenderedc                      s    S r/   r$   r$   r   r$   r%   r3   =  r4   z;ApplicationTests._internalServerErrorTest.<locals>.<lambda>r   r   r@   rc  )r    rK   rv   r   ru   r   r$   )rK   r{   r    r%   _internalServerErrorTest+  s"    
 
      z)ApplicationTests._internalServerErrorTestc                 C   s   dd }|  |S )z
        If the application raises an exception before calling I{start_response}
        then the response status is I{500} and the exception is logged.
        c                 S   s   t dd S N This application had some error.r<   r0   r$   r$   r%   rK   G  s    zRApplicationTests.test_applicationExceptionBeforeStartResponse.<locals>.applicationr  r    rK   r$   r$   r%   ,test_applicationExceptionBeforeStartResponseB  s    z=ApplicationTests.test_applicationExceptionBeforeStartResponsec                 C   s   dd }|  |S )z
        If the application calls I{start_response} but then raises an exception
        before any data is written to the response then the response status is
        I{500} and the exception is logged.
        c                 S   s   |dg  t dd S Nr   r  r  r0   r$   r$   r%   rK   R  s    
zQApplicationTests.test_applicationExceptionAfterStartResponse.<locals>.applicationr  r  r$   r$   r%   +test_applicationExceptionAfterStartResponseL  s    z<ApplicationTests.test_applicationExceptionAfterStartResponsec                    s   t  tt fdd} \}g fdd}fdd}|| ||fddd	d
g dgd g 	 jj	 d 
ttd |S )Nc                      s    S r/   r$   r$   r   r$   r%   rv   `  s    zBApplicationTests._connectionClosedTest.<locals>.applicationFactoryc                     s     | | d S r.  )r  )r"   r#   )ru   requestsr$   r%   requestFactoryWrapperg  s    zEApplicationTests._connectionClosedTest.<locals>.requestFactoryWrapperc                    sd    dt d }|d }|jt t  jj }	|
d | d S )NrM   r   rN   s   HTTP/1.1 200 OK)rR   rS   rT   rU   r<   rV   r   r]  r^  r8   r_  ZassertIn)ra  Zeventr!   r   )r{   rW   responseContentr    r$   r%   
ebRenderedk  s    
z:ApplicationTests._connectionClosedTest.<locals>.ebRenderedc                      s    S r/   r$   r$   r   r$   r%   r3   z  r4   z8ApplicationTests._connectionClosedTest.<locals>.<lambda>r   r   r@   r   zAll gone)r   r   rO   r   r   Z
addErrbackr}   r8   r   Zdisconnectedr  r   r   )r    rK   r  rv   r   r  r  r$   )rK   r{   rW   ru   r  r  r    r%   _connectionClosedTestX  s2    
 
      z&ApplicationTests._connectionClosedTestc                    s   d  fdd}|  | S )z
        If the application raises an exception after the response status has
        already been sent then the connection is closed and the exception is
        logged.
        s?   Some bytes, triggering the server to start sending the responsec                 3   s   |dg   V  t dd S r  r  r0   r  r$   r%   rK     s    
zIApplicationTests.test_applicationExceptionAfterWrite.<locals>.application)r  r  r$   r  r%   #test_applicationExceptionAfterWrite  s    z4ApplicationTests.test_applicationExceptionAfterWritec                    s$   d G  fdddt }| | S )z
        If the application returns a closeable iterator and the C{close} method
        raises an exception when called then the connection is still closed and
        the exception is logged.
        r:   c                       s(   e Zd Zdd Z fddZdd ZdS )zDApplicationTests.test_applicationCloseException.<locals>.Applicationc                 S   s   |dg  d S r  r$   )r    r1   r2   r$   r$   r%   rA     s    zMApplicationTests.test_applicationCloseException.<locals>.Application.__init__c                 3   s
    V  d S r/   r$   r6   r  r$   r%   r    s    zMApplicationTests.test_applicationCloseException.<locals>.Application.__iter__c                 S   s   t dd S r  r  r6   r$   r$   r%   r    s    zJApplicationTests.test_applicationCloseException.<locals>.Application.closeNr  r$   r  r$   r%   Application  s   r  )objectr  )r    r  r$   r  r%   test_applicationCloseException  s    
z/ApplicationTests.test_applicationCloseExceptionN)r'   r(   r)   r*   r  r  r  r  r  r  r  r  r  r  r  r  r  r$   r$   r$   r%   r  S  s   *  %
,r  )?r*   r   Z__metaclass__sysr   rY  r  r  Zzope.interface.verifyr   Ztwisted.python.compatr   r   r   Ztwisted.python.failurer   Ztwisted.python.threadabler   Ztwisted.python.threadpoolr	   Ztwisted.internet.deferr
   r   Ztwisted.internetr   Ztwisted.internet.errorr   Ztwisted.trial.unittestr   r   Ztwisted.webr   Ztwisted.web.resourcer   r   Ztwisted.web.serverr   r   r   Ztwisted.web.wsgir   Ztwisted.web.test.test_webr   Ztwisted.loggerr   r   Ztwisted.test.proto_helpersr   Ztwisted.internet.addressr   r   r   r+   r.   rY   r   r  rM  rS  rU  rX  rZ  r  r$   r$   r$   r%   <module>   sZ   z -    @  /
	    C