
    tfʷ                       d Z ddlmZ ddlmZ ddlmZ ddlmZm	Z	m
Z
mZ ddlmZmZ ddlmZmZ ddlmZ dd	lmZ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  ddl!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3 ddl4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z= ddl>m?Z? ddl@mAZA ddlBmCZCmDZD ddlEmFZFmGZG  G d deH          ZI G d deH          ZJ eAddgi          ZKd ZLd ZMd ZNd ZOd ZP G d d e           ZQ G d! d"          ZR G d# d$eRe           ZS G d% d&eRe           ZT G d' d(e           ZU G d) d*          ZV G d+ d,          ZW G d- d.e           ZX eeC           G d/ d0                      ZY G d1 d2e           ZZ G d3 d4e           Z[ G d5 d6e           Z\ G d7 d8e           Z] G d9 d:e           Z^d;S )<z&
Tests for L{twisted.web._newclient}.
    )Optional)implementer)verifyObject)CancelledErrorDeferredfailsucceed)ConnectionDoneConnectionLost)	IConsumerIPushProducer)Protocol)AccumulatingProtocolEventLoggingObserverStringTransport StringTransportWithDisconnection)globalLogPublisher)LineReceiver)Failure)TestCase)BODYDONEHEADERSTATUSUNKNOWN_LENGTH
BadHeadersBadResponseVersionChunkedEncoderConnectionAbortedExcessWriteHTTPClientParser
HTTPParserLengthEnforcingConsumer
ParseErrorRequestNotSentTransportProxyProducerWrongBodyLengthmakeStatefulDispatcher)	HTTP11ClientProtocolPotentialDataLossRequestRequestGenerationFailedRequestTransmissionFailedResponseResponseDoneResponseFailedResponseNeverReceived)	_DataLoss)Headers)IBodyProducer	IResponse)bytesLinearWhitespaceComponentssanitizedBytesc                       e Zd ZdZdS )ArbitraryExceptionze
    A unique, arbitrary exception type which L{twisted.web._newclient} knows
    nothing about.
    N__name__
__module____qualname____doc__     ^/var/www/surfInsights/venv3-11/lib/python3.11/site-packages/twisted/web/test/test_newclient.pyr9   r9   C   s           r@   r9   c                       e Zd ZdZdS )AnotherArbitraryExceptionzI
    Similar to L{ArbitraryException} but with a different identity.
    Nr:   r?   r@   rA   rC   rC   J   s           r@   rC      host   example.comc                 l      fd}                      ||          }|                    |           |S )a  
    Assert that the given L{Deferred} fails with the exception given by
    C{mainType} and that the exceptions wrapped by the instance of C{mainType}
    it fails with match the list of exception types given by C{reasonTypes}.

    This is a helper for testing failures of exceptions which subclass
    L{_newclient._WrapperException}.

    @param self: A L{TestCase} instance which will be used to make the
        assertions.

    @param deferred: The L{Deferred} which is expected to fail with
        C{mainType}.

    @param mainType: A L{_newclient._WrapperException} subclass which will be
        trapped on C{deferred}.

    @param reasonTypes: A sequence of exception types which will be trapped on
        the resulting C{mainType} exception instance's C{reasons} sequence.

    @return: A L{Deferred} which fires with the C{mainType} instance
        C{deferred} fails with, or which fails somehow.
    c           	          t          | j                  D ]\  }}|                    |                               t	          | j                  t	                    d| j         d d           | S )Nzlen(z	) != len())zipreasonstrapassertEquallen)errreasontypereasonTypesselfs      rA   cbFailedz-assertWrapperExceptionTypes.<locals>.cbFailedn   s    [99 	 	LFDKK73;77777	
 	
 	

 
r@   )assertFailureaddCallback)rR   deferredmainTyperQ   rS   ds   `  `  rA   assertWrapperExceptionTypesrY   U   sP    2      	8X..AMM(Hr@   c                 0    t          | |t          |          S )zo
    A simple helper to invoke L{assertWrapperExceptionTypes} with a C{mainType}
    of L{ResponseFailed}.
    )rY   r0   rR   rV   rQ   s      rA   assertResponseFailedr\   }   s    
 'tX~{SSSr@   c                 0    t          | |t          |          S )zx
    A simple helper to invoke L{assertWrapperExceptionTypes} with a C{mainType}
    of L{RequestGenerationFailed}.
    )rY   r,   r[   s      rA   assertRequestGenerationFailedr^      s     
 'h/  r@   c                 0    t          | |t          |          S )zz
    A simple helper to invoke L{assertWrapperExceptionTypes} with a C{mainType}
    of L{RequestTransmissionFailed}.
    )rY   r-   r[   s      rA   assertRequestTransmissionFailedr`      s     
 'h1;  r@   c                 2    t          dddt          |           S )z
    Helper function for creating a Response which uses the given transport.
    All of the other parameters to L{Response.__init__} are filled with
    arbitrary values.  Only use this method if you don't care about any of
    them.
    s   HTTP   rc         OK)r.   _boringHeaders)	transports    rA   justTransportResponserh      s     OS%KKKr@   c                       e Zd ZdZd ZdS )MakeStatefulDispatcherTestsz.
    Tests for L{makeStatefulDispatcher}.
    c                 0    G d d          } |            }|                      |                                d           d|_        |                      |                                d           d|_        |                     t          |j                   dS )z
        A method defined with L{makeStatefulDispatcher} invokes a second
        method based on the current state of the object.
        c                   <    e Zd ZdZd Z ede          Zd Zd ZdS )CMakeStatefulDispatcherTests.test_functionCalledByState.<locals>.FooAc                     d S Nr?   rR   s    rA   barzGMakeStatefulDispatcherTests.test_functionCalledByState.<locals>.Foo.bar   s    r@   quuxc                     dS )Nar?   rq   s    rA   _quux_AzKMakeStatefulDispatcherTests.test_functionCalledByState.<locals>.Foo._quux_A       sr@   c                     dS )Nbr?   rq   s    rA   _quux_BzKMakeStatefulDispatcherTests.test_functionCalledByState.<locals>.Foo._quux_B   rw   r@   N)r;   r<   r=   _staterr   r(   rv   rz   r?   r@   rA   Foorm      sZ        F   )(55C      r@   r|   ru   Bry   CN)rL   rr   r{   assertRaisesRuntimeError)rR   r|   statefuls      rA   test_functionCalledByStatez6MakeStatefulDispatcherTests.test_functionCalledByState   s    	 	 	 	 	 	 	 	 355------,55555r@   N)r;   r<   r=   r>   r   r?   r@   rA   rj   rj      s-         6 6 6 6 6r@   rj   c                   j    e Zd ZU dZdZee         ed<   d Zd Z	d Z
d Zd Zd	 Zd
 Zd Zd Zd ZdS )_HTTPParserTestszt
    Base test class for L{HTTPParser} which is responsible for the bulk of
    the task of parsing HTTP bytes.
    Nsepc                 h   g }t                      }|j        |_        |                    t	                                 |                     |j        t                     |                    d| j	        z              |                     |dg           |                     |j        t                     dS )zj
        L{HTTPParser} calls its C{statusReceived} method when it receives a
        status line.
           HTTP/1.1 200 OKN)r"   appendstatusReceivedmakeConnectionr   rL   stater   dataReceivedr   r   )rR   statusprotocols      rA   test_statusCallbackz$_HTTPParserTests.test_statusCallback   s    
 <<"(- 1 1222000048;<<<"4!566600000r@   c                     i }t                      }|j        |_        |                    t	                                 |                    d| j        z              ||fS )Nr   )r"   __setitem__headerReceivedr   r   r   r   rR   headerr   s      rA   _headerTestSetupz!_HTTPParserTests._headerTestSetup   s\    <<"("4 1 1222048;<<<xr@   c                    |                                  \  }}|                    d| j        z              |                    | j                   |                     |ddi           |                     |j        t
                     dS )ze
        L{HTTPParser} calls its C{headerReceived} method when it receives a
        header.
        s	   X-Foo:bar   X-Foo   barNr   r   r   rL   r   r   r   s      rA   test_headerCallbackz$_HTTPParserTests.test_headerCallback   s    
  0022lTX5666 	dh'''(F!3444.....r@   c                    |                                  \  }}|                    d| j        z              |                    d| j        z              |                    d| j        z              |                    | j                   |                     |ddi           |                     |j        t
                     dS )z
        If a header is split over multiple lines, L{HTTPParser} calls
        C{headerReceived} with the entire value once it is received.
        
   X-Foo: bars    bazs   	quuxr   s   bar baz	quuxNr   r   s      rA   test_continuedHeaderCallbackz-_HTTPParserTests.test_continuedHeaderCallback   s    
  0022mdh6777g0111i$(2333dh'''(,<!=>>>.....r@   c                 2   |                                  \  }}| j                            g d          }|                    d|z              |                    d|z              |                    | j                   |                     |ddd           dS )z
        Leading and trailing linear whitespace is stripped from the header
        value passed to the C{headerReceived} callback.
        )s    	 s    bar 	s    	r@   s   X-Bar:s   X-Foo:r   )r   s   X-BarN)r   r   joinr   rL   )rR   r   r   values       rA   test_fieldContentWhitespacez,_HTTPParserTests.test_fieldContentWhitespace   s    
  0022@@@AAi%/000i%/000dh'''Ff!E!EFFFFFr@   c                    g |                                  \  }fd}|_                            | j                   |                     t
          g           |                     j        t                     dS )zg
        After the last header is received, L{HTTPParser} calls
        C{allHeadersReceived}.
        c                  T                          j                   t          _        d S rp   )r   r   r   )calledr   s   rA   allHeadersReceivedzD_HTTPParserTests.test_allHeadersCallback.<locals>.allHeadersReceived  s"    MM(.)))#HNNNr@   N)r   r   r   r   rL   r   r   r   )rR   r   r   r   r   s      @@rA   test_allHeadersCallbackz(_HTTPParserTests.test_allHeadersCallback  s    
 0022	$ 	$ 	$ 	$ 	$ 	$ '9#dh'''&***00000r@   c                     |                                  \  }}|                    | j                   |                     |i            |                     |j        t
                     dS )zp
        If there are no headers in the message, L{HTTPParser} does not call
        C{headerReceived}.
        Nr   r   s      rA   test_noHeaderCallbackz&_HTTPParserTests.test_noHeaderCallback  sd    
  0022dh'''$$$.....r@   c                    t                      }|                    t                                 |                    d| j        z              |                    d| j        z              |                    d| j        z              |                    | j                   dddgfg}|                     |t          |j                                                             dS )zc
        All headers received by L{HTTPParser} are added to
        L{HTTPParser.headers}.
        r   r   
   X-Foo: bazr   r      bazN)	r"   r   r   r   r   rL   listheadersgetAllRawHeaders)rR   r   expecteds      rA   test_headersSavedOnResponsez,_HTTPParserTests.test_headersSavedOnResponse#  s    
 << 1 1222048;<<<mdh6777mdh6777dh'''/014(8(I(I(K(K#L#LMMMMMr@   c                     t                      }g d}|D ]/}|                     |                    |          d|d           0|                     |                    d          d           dS )z
        L{HTTPParser.isConnectionControlHeader} returns C{True} for headers
        which are always connection control headers (similar to "hop-by-hop"
        headers from RFC 2616 section 13.5.1) and C{False} for other headers.
        )   content-length
   connections
   keep-alives   tes   trailerss   transfer-encodings   upgrades   proxy-connectionz
Expecting z. to be a connection control header, but wasn'ts   datez`Expecting the arbitrarily selected 'date' header to not be a connection control header, but was.N)r"   
assertTrueisConnectionControlHeaderassertFalse)rR   r   connHeaderNamesr   s       rA   test_connectionControlHeadersz._HTTPParserTests.test_connectionControlHeaders1  s     <<	
 	
 	
 & 	 	FOO226:::"FF%   
 	..w774	
 	
 	
 	
 	
r@   c                     t                      }|                    t                                 |                    t	                                 |                     t          |j        t	                                 dS )zi
        L{HTTPParser.switchToBodyMode} raises L{RuntimeError} if called more
        than once.
        N)r"   r   r   switchToBodyModeobjectr   r   rR   r   s     rA   test_switchToBodyModez&_HTTPParserTests.test_switchToBodyModeO  sd    
 << 1 1222!!&((+++,(A688LLLLLr@   )r;   r<   r=   r>   r   r   bytes__annotations__r   r   r   r   r   r   r   r   r   r   r?   r@   rA   r   r      s          
  C%1 1 1     / / // / /
G 
G 
G1 1 1"/ / /N N N
 
 
<M M M M Mr@   r   c                       e Zd ZdZdZdS )$HTTPParserRFCComplaintDelimeterTestsz<
    L{_HTTPParserTests} using standard CR LF newlines.
       
Nr;   r<   r=   r>   r   r?   r@   rA   r   r   Z  s          CCCr@   r   c                       e Zd ZdZdZdS )'HTTPParserNonRFCComplaintDelimeterTestsz5
    L{_HTTPParserTests} using bare LF newlines.
       
Nr   r?   r@   rA   r   r   b  s          CCCr@   r   c                       e Zd ZdZd Zd Zd Zd Zd Zd Z	d Z
d	 Zd
 Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Z d Z!d  Z"d! Z#d" Z$d# Z%d$S )%HTTPClientParserTestszd
    Tests for L{HTTPClientParser} which is responsible for parsing HTTP
    response messages.
    c                 x    t          dd          }|                     |                    d          d           dS )zj
        L{HTTPClientParser.parseVersion} parses a status line into its three
        components.
        Ns	   CANDY/7.2)s   CANDY      )r!   rL   parseVersionr   s     rA   test_parseVersionz'HTTPClientParserTests.test_parseVersionp  s>    
 $D$//..|<<>NOOOOOr@   c                      t          dd          }t          |j         fd} |d            |d            |d            |d            |d            |d           dS )	zr
        L{HTTPClientParser.parseVersion} raises L{ValueError} when passed an
        unparsable version.
        Nc                 l                         |           }                    |j        |            d S rp   )r   rL   data)sexcefrR   s     rA   checkParsingz@HTTPClientParserTests.test_parseBadVersion.<locals>.checkParsing  s8    ##Aq!,,CSXq)))))r@      foos   foo/bar/bazs   foo/s   foo/..s   foo/a.bs	   foo/-1.-1)r!   r   r   )rR   r   r   r   r   s   `  @@rA   test_parseBadVersionz*HTTPClientParserTests.test_parseBadVersionx  s    
 $D$//!	* 	* 	* 	* 	* 	* 	* 	V^$$$WYZ   \"""""r@   c                    t          ddt          d          }t          |d          }|                    t	                                 |                    d           |                     |j        j        d           |                     |j        j	        d           |                     |j        j
        d           dS )z
        L{HTTPClientParser.statusReceived} parses the version, code, and phrase
        from the status line and stores them on the response object.
           GET   /N   HTTP/1.1 200 OK
rb   rd   re   r+   rf   r!   r   r   r   rL   responseversioncodephraserR   requestr   s      rA   test_responseStatusParsingz0HTTPClientParserTests.test_responseStatusParsing  s    
 &$==#GT22 1 12224555*2ODDD*/555*1599999r@   c                    t          ddt          d          }t          |d          }|                    t	                                 |                    d           |                     |j        j        d           |                     |j        j	        d           |                     |j        j
        d           dS )z
        L{HTTPClientParser.statusReceived} can parse a status line without a
        phrase (though such lines are a violation of RFC 7230, section 3.1.2;
        nevertheless some broken servers omit the phrase).
        r   r   Ns   HTTP/1.1 200
rb   rd   r@   r   r   s      rA    test_responseStatusWithoutPhrasez6HTTPClientParserTests.test_responseStatusWithoutPhrase  s     &$==#GT22 1 12221222*2ODDD*/555*1377777r@   c                 b     t          dd           fd} |d            |d           dS )z
        L{HTTPClientParser.statusReceived} raises L{ParseError} if it is called
        with a status line which cannot be parsed.
        Nc                                          t          j        |           }                    |j        |            d S rp   )r   r$   r   rL   r   )r   r   r   rR   s     rA   r   zBHTTPClientParserTests.test_badResponseStatus.<locals>.checkParsing  s;    ##J0GKKCSXq)))))r@   r   s   HTTP/1.1 bar OK)r!   )rR   r   r   s   ` @rA   test_badResponseStatusz,HTTPClientParserTests.test_badResponseStatus  s^    
 $D$//	* 	* 	* 	* 	* 	* 	V 	'(((((r@   c                 r  	 i }g }g }g 	t          ||j                  }|j        |_        t	                      }|                    |           |                    |           |j        |j        _        	fd|j        _	        |                    |           | 
                    |j        d           | 
                    |j        t                     | 
                    |g            | 
                    |dg           | 
                    	dg           | 
                    |j        j        d           |S )a0  
        Assert that L{HTTPClientParser} parses the given C{response} to
        C{request}, resulting in a response with no body and no extra bytes and
        leaving the transport in the producing state.

        @param request: A L{Request} instance which might have caused a server
            to return the given response.
        @param status: A string giving the status line of the response to be
            parsed.
        @param response: A string giving the response to be parsed.

        @return: A C{dict} of headers from the response.
        c                  .                          d          S NTr   )bodyDataFinisheds   rA   <lambda>z3HTTPClientParserTests._noBodyTest.<locals>.<lambda>  s    6F6M6Md6S6S r@   	producingr@   Tr   )r!   r   r   r   r   r   r   r   _bodyDataReceived_bodyDataFinishedrL   producerStater   r   length)
rR   r   r   r   r   finishedbodyr   rg   r   s
            @rA   _noBodyTestz!HTTPClientParserTests._noBodyTest  s9    #GX_=="("4#%%		*** 	f%%%.2k+.S.S.S.S+h'''0+>>>...r"""C5))))D6222*11555r@   c                     t          ddt          d          }d}d}|                     |||          }|                     |ddi           dS )z
        If the response is to a HEAD request, no body is expected, the body
        callback is not invoked, and the I{Content-Length} header is passed to
        the header callback.
           HEADr   Nr   s   Content-Length: 10

s   Content-Lengths   10)r+   rf   r   rL   )rR   r   r   r   r   s        rA   test_headResponsez'HTTPClientParserTests.test_headResponse  sZ     '4>>'4!!'68<<"3U!;<<<<<r@   c                 j    t          ddt          d          }d}d}|                     |||           dS )z
        If the response code is I{NO CONTENT} (204), no body is expected and
        the body callback is not invoked.
        r   r   Ns   HTTP/1.1 204 NO CONTENT
r   r+   rf   r   rR   r   r   r   s       rA   test_noContentResponsez,HTTPClientParserTests.test_noContentResponse  s?    
 &$==/&(33333r@   c                 j    t          ddt          d          }d}d}|                     |||           dS )z
        If the response code is I{NOT MODIFIED} (304), no body is expected and
        the body callback is not invoked.
        r   r   Ns   HTTP/1.1 304 NOT MODIFIED
r   r   r   s       rA   test_notModifiedResponsez.HTTPClientParserTests.test_notModifiedResponse  s?    
 &$==1&(33333r@   c                    t          t          ddt          d          d           }|                    t	                                 |                    d           |                    d           |                    d           |                     |j        t          i                      |                     |j	        j
        t          dd	gi                     |                     |j	        j        t                     dS )
zq
        The response headers are added to the response object's C{headers}
        L{Headers} instance.
        r   r   Nc                     d S rp   r?   rests    rA   r   z<HTTPClientParserTests.test_responseHeaders.<locals>.<lambda>      d r@   r   s   X-Foo: bar
r      x-foor   r!   r+   rf   r   r   r   rL   connHeadersr3   r   r   assertIdenticalr   r   r   s     rA   test_responseHeadersz*HTTPClientParserTests.test_responseHeaders   s    
 $FD.$779J9J
 
 	 1 12224555/000g&&&-wr{{;;;*2GXx<P4Q4QRRRX.5~FFFFFr@   c                 6   t          t          ddt          d          d           }|                    t	                                 |                    d           |                    d           |                    d           |                    d           |                     |j        t          i                      |                     |j	        j
        t          d	d
gi                     |                     |j	        j        t                     dS )z
        The multi-line response headers are folded and added to the response
        object's C{headers} L{Headers} instance.
        r   r   Nc                     d S rp   r?   r  s    rA   r   zEHTTPClientParserTests.test_responseHeadersMultiline.<locals>.<lambda>  r  r@   r   s   X-Multiline: a
s       b
r   s   x-multilines   a    br  r   s     rA   test_responseHeadersMultilinez3HTTPClientParserTests.test_responseHeadersMultiline  s   
 $FD.$779J9J
 
 	 1 122245553444l+++g&&&-wr{{;;;%w/L'M'M	
 	
 	
 	X.5~FFFFFr@   c                 0   t          t          ddt          d          d           }|                    t	                                 |                    d           |                    d           |                    d           |                    d           |                     |j        j        t          i                      |                     |j
        t          d	gd
gd                     |                     |j        j        d           dS )zv
        The connection control headers are added to the parser's C{connHeaders}
        L{Headers} instance.
        r   r   Nc                     d S rp   r?   r  s    rA   r   z>HTTPClientParserTests.test_connectionHeaders.<locals>.<lambda>)  r  r@   r      Content-Length: 123
s   Connection: close
r      123s   close)r   r   {   r!   r+   rf   r   r   r   rL   r   r   r3   r  r   r   s     rA   test_connectionHeadersz,HTTPClientParserTests.test_connectionHeaders#  s   
 $FD.$779J9J
 
 	 1 1222455589996777g&&&*2GBKK@@@ (LLMM	
 	
 	
 	*1377777r@   c                    t          t          ddt          d          d           }|                    t	                                 |                    d           |                    d           |                    d           |                     |j        j        t          dd	gi                     |                     |j
        t          i                      |                     |j        j        d
           dS )z
        If a HEAD request is made, the I{Content-Length} header in the response
        is added to the response headers, not the connection control headers.
        r   r   Nc                     d S rp   r?   r  s    rA   r   zRHTTPClientParserTests.test_headResponseContentLengthEntityHeader.<locals>.<lambda>=  s    t r@   r   r  r   r   r  r   r  r   s     rA   *test_headResponseContentLengthEntityHeaderz@HTTPClientParserTests.test_headResponseContentLengthEntityHeader7  s    
 $GT>488:K:K
 
 	 1 122245558999g&&&%w0AF8/L'M'M	
 	
 	
 	-wr{{;;;*1155555r@   c                    g }t          t          ddt          d          |j                  }t	                      }|                    |           |                    d           g }|j        |j        _        |                    d           |                    d           | 	                    |j
        d           | 	                    |j        t                     |                    d           | 	                    |dg           | 	                    |j        t                     |                    d	           | 	                    |dd	g           | 	                    |j        t                     | 	                    |d
g           dS )z
        If a response includes a body with a length given by the
        I{Content-Length} header, the bytes which make up the body are passed
        to the C{_bodyDataReceived} callback on the L{HTTPParser}.
        r   r   Nr   s   Content-Length: 10
r   pauseds   xxxxxxs   yyyyr@   )r!   r+   rf   r   r   r   r   r   r   rL   r   r   r   r   rR   r   r   rg   r   s        rA   test_contentLengthz(HTTPClientParserTests.test_contentLengthI  sz    #FD.$77
 
 $%%		***4555.2k+7888g&&& 	0(;;;...h'''z***...h'''(3444...C5)))))r@   c                    g }t          t          ddt          d          |j                  }|                    t                                 |                    d           g }|j        |j        _        |                    d           |                    d           | 	                    |j
        t                     | 	                    |g            | 	                    |dg           | 	                    |j        j        d           dS )	z
        If a response includes a I{Content-Length} header indicating zero bytes
        in the response, L{Response.length} is set accordingly and no data is
        delivered to L{Response._bodyDataReceived}.
        r   r   Nr      Content-Length: 0
r   r@   r   )r!   r+   rf   r   r   r   r   r   r   rL   r   r   r   rR   r   r   r   s       rA   test_zeroContentLengthz,HTTPClientParserTests.test_zeroContentLengthh  s    #FD.$77
 
 	 1 12224555.2k+6777g&&&...r"""C5)))*1155555r@   c                     t          t          ddt          d          d          }|                    t	                                 |                     t          |j        d           dS )z
        If a response includes multiple, distinct I{Content-Length} headers,
        L{HTTPClientParser.dataReceived} raises L{ValueError} to indicate that
        the response is invalid and the transport is now unusable.
        r   r   Ns9   HTTP/1.1 200 OK
Content-Length: 1
Content-Length: 2

r!   r+   rf   r   r   r   
ValueErrorr   r   s     rA   )test_multipleDistinctContentLengthHeadersz?HTTPClientParserTests.test_multipleDistinctContentLengthHeaders  sl     $GFD.$$O$OQUVV 1 1222!	
 	
 	
 	
 	
r@   c                 <   t          t          ddt          d          d          }|                    t	                                 |                    d           |                     |j        j        d           |                     |j	        t                     dS )z
        If a response includes multiple, yet equal, I{Content-Length} headers,
        L{HTTPClientParser.dataReceived} successfully handles and passes single
        length for body processing
        r   r   Ns9   HTTP/1.1 200 OK
Content-Length: 1
Content-Length: 1

rc   r!   r+   rf   r   r   r   rL   r   r   r   r   r   s     rA   &test_multipleEqualContentLengthHeadersz<HTTPClientParserTests.test_multipleEqualContentLengthHeaders  s     $GFD.$$O$OQUVV 1 1222	
 	
 	
 	*11555.....r@   c                     t          t          ddt          d          d          }|                    t	                                 |                     t          |j        d           dS )z
        If a response includes multiple, distinct I{Content-Length} header
        field-values, L{HTTPClientParser.dataReceived} raises L{ValueError} to
        indicate that the response is invalid and the transport is now unusable.
        r   r   Ns)   HTTP/1.1 200 OK
Content-Length: 1, 2

r   r   s     rA   3test_multipleDistinctContentLengthHeaderFieldValueszIHTTPClientParserTests.test_multipleDistinctContentLengthHeaderFieldValues  sj     $GFD.$$O$OQUVV 1 1222!F	
 	
 	
 	
 	
r@   c                 <   t          t          ddt          d          d          }|                    t	                                 |                    d           |                     |j        j        d           |                     |j	        t                     dS )a%  
        If a response includes multiple, equal I{Content-Length} header
        field-values, L{HTTPClientParser.dataReceived} successfully handles and
        passes single content-length header for body processing. Field-values
        are considered equal by parsed decimal value.
        r   r   Ns+   HTTP/1.1 200 OK
Content-Length: 1, 001

rc   r$  r   s     rA   0test_multipleEqualContentLengthHeaderFieldValueszFHTTPClientParserTests.test_multipleEqualContentLengthHeaderFieldValues  s     $GFD.$$O$OQUVV 1 1222H	
 	
 	
 	*11555.....r@   c                     t          t          ddt          d          d          }|                    t	                                 |                     t          |j        d           dS )z
        If the I{Content-Length} header contains anything other than digits
        L{HTTPClientParser.dataReceived} raises L{ValueError} to
        indicate that the response is invalid and the transport is now unusable.
        r   r   Ns'   HTTP/1.1 200 OK
Content-Length: +1

r   r   s     rA   test_contentLengthTooPositivez3HTTPClientParserTests.test_contentLengthTooPositive  j     $GFD.$$O$OQUVV 1 1222!<	
 	
 	
 	
 	
r@   c                     t          t          ddt          d          d          }|                    t	                                 |                     t          |j        d           dS )z
        If the I{Content-Length} header has a negative value
        L{HTTPClientParser.dataReceived} raises L{ValueError} to
        indicate that the response is invalid and the transport is now unusable.
        r   r   Ns'   HTTP/1.1 200 OK
Content-Length: -1

r   r   s     rA   test_contentLengthNegativez0HTTPClientParserTests.test_contentLengthNegative  r,  r@   c                    g }t          t          ddt          d          |j                  }|                    t                                 |                    d           |                    d           |                    d           |                     |j        t                     |                     |dg           dS )zy
        If extra bytes are received past the end of a response, they are passed
        to the finish callback.
        r   r   Nr   r     
Here is another thing!   Here is another thing!
r!   r+   rf   r   r   r   r   rL   r   r   rR   r   r   s      rA   test_extraBytesPassedBackz/HTTPClientParserTests.test_extraBytesPassedBack  s    
 #FD.$77
 
 	 1 122245556777;<<<...$=#>?????r@   c                    g }t          t          ddt          d          |j                  }|                    t                                 |                    d           |                    d           |                    d           |                     |j        t                     |                     |dg           dS )z
        If extra bytes are received past the end of the headers of a response
        to a HEAD request, they are passed to the finish callback.
        r   r   Nr   s   Content-Length: 12
r0  r1  r2  r3  s      rA   test_extraBytesPassedBackHEADz3HTTPClientParserTests.test_extraBytesPassedBackHEAD  s    
 #GT>488(/
 
 	 1 122245557888;<<<...$=#>?????r@   c                    g }t          t          ddt          d          |j                  }|                    t                                 |                    d           g }|j        |j        _        |                    d           |                    d           | 	                    |g            | 
                    |j        j        t                     |                    d           | 	                    |dg           |                    d	           | 	                    |dd
g           |                    d           | 	                    |dg           dS )z
        If the response headers indicate the response body is encoded with the
        I{chunked} transfer encoding, the body is decoded according to that
        transfer encoding before being passed to L{Response._bodyDataReceived}.
        r   r   Nr   s   Transfer-Encoding: chunked
r   s   3
a   as   bc
s   bcs
   0

extras   extra)r!   r+   rf   r   r   r   r   r   r   rL   r  r   r   r  s       rA   test_chunkedResponseBodyz.HTTPClientParserTests.test_chunkedResponseBody  s`    #FD.$77
 
 	 1 12224555.2k+?@@@g&&& 	r""" 	X.5~FFF 	i(((v&&&i(((e}---
 	/000H:.....r@   c                    g }t          t          ddt          d          |j                  }t	                      }|                    |           |                    d           g }|j        |j        _        |                    d           |                    d           |                    d           | 	                    |ddg           |
                    t          d                     | 	                    |d	g           dS )
z
        If a response does not include a I{Transfer-Encoding} or a
        I{Content-Length}, the end of response body is indicated by the
        connection being closed.
        r   r   Nr   r   r   r   zsimulated end of connectionr@   )r!   r+   rf   r   r   r   r   r   r   rL   connectionLostr
   r  s        rA   test_unknownContentLengthz/HTTPClientParserTests.test_unknownContentLength)  s    #FD.$77
 
 $%%		***4555.2k+g&&&f%%%f%%%/000/L M MNNNC5)))))r@   c                 z   g }t          t          ddt          d          |j                  }t	                      }|                    |           |                    d           g }|j        |j        _        |                    d           | 	                    |dg           | 	                    |dg           dS )z
        According to RFC 2616, section 4.4, point 3, if I{Content-Length} and
        I{Transfer-Encoding: chunked} are present, I{Content-Length} MUST be
        ignored
        r   r   Nr   s@   Content-Length: 102
Transfer-Encoding: chunked

3
abc
0

   abcr@   )
r!   r+   rf   r   r   r   r   r   r   rL   r  s        rA   %test_contentLengthAndTransferEncodingz;HTTPClientParserTests.test_contentLengthAndTransferEncodingA  s     #FD.$77
 
 $%%		***4555.2k+	
 	
 	
 	x(((C5)))))r@   c                 *   t                      }t          t          ddt          d          d          }|                    |           |j        }|                    t          t                                           t          | |t          g          S )z
        If L{HTTPClientParser.connectionLost} is called before the headers are
        finished, the C{_responseDeferred} is fired with the L{Failure} passed
        to C{connectionLost}.
        r   r   N)
r   r!   r+   rf   r   _responseDeferredr;  r   r9   r\   )rR   rg   r   responseDeferreds       rA   test_connectionLostBeforeBodyz3HTTPClientParserTests.test_connectionLostBeforeBody_  s     $%%	#GFD.$$O$OQUVV	***#5(:(<(< = =>>>#D*:=O<PQQQr@   c                 `   t          j        | t                    }t                      }t	          t          ddt          d          d          }|                    |           g }|j        	                    |j
                   |                    d           |d         }d	d}||_        |                    d           |                     dt          |                     |d         }|d         }|                     |j        t$                     |                     t$                     dS )
z
        If one of the L{Response} methods called by
        L{HTTPClientParser.connectionLost} raises an exception, the exception
        is logged and not re-raised.
        r   r   N&   HTTP/1.1 200 OK
Content-Length: 1

r   c                     t                      rp   r9   )rN   s    rA   fakeBodyDataFinishedzPHTTPClientParserTests.test_connectionLostWithError.<locals>.fakeBodyDataFinished  s    $&&&r@   rc   log_failurerp   )r   createWithCleanupr   r   r!   r+   rf   r   rA  rU   r   r   r   r;  assertEqualsrM   assertIsInstancer   r9   flushLoggedErrors)rR   logObserverrg   r   r   rH  eventr   s           rA   test_connectionLostWithErrorz2HTTPClientParserTests.test_connectionLostWithErrorn  s'    +<TCUVV#%%	#GFD.$$O$OQUVV	***"..x???UVVVA;	' 	' 	' 	' &:"%%%!S--...A- ag'9:::122222r@   c                    t          t          ddt          d          d           }|j        }|                    t                                 |                    t                                 |                     |t                    S )z
        If no response at all was received and the connection is lost, the
        resulting error is L{ResponseNeverReceived}.
        r   r   Nc                     d S rp   r?   igns    rA   r   z<HTTPClientParserTests.test_noResponseAtAll.<locals>.<lambda>  r  r@   )
r!   r+   rf   rA  r   r   r;  r   rT   r1   rR   r   rX   s      rA   test_noResponseAtAllz*HTTPClientParserTests.test_noResponseAtAll  s    
 $GT>488:J:J
 
 & 1 1222 0 0111!!!%:;;;r@   c                 |   t          t          ddt          d          d           }|j        }|                    t                                 |                    d           |                    t                                 | 	                    |t                                        | j        t                    S )z
        If a partial response was received and the connection is lost, the
        resulting error is L{ResponseFailed}, but not
        L{ResponseNeverReceived}.
        r   r   Nc                     d S rp   r?   rS  s    rA   r   zBHTTPClientParserTests.test_someResponseButNotAll.<locals>.<lambda>  r  r@      2)r!   r+   rf   rA  r   r   r   r;  r   rT   r0   rU   rL  rU  s      rA   test_someResponseButNotAllz0HTTPClientParserTests.test_someResponseButNotAll  s     $GT>488:J:J
 
 & 1 1222d### 0 0111!!!^44@@!>
 
 	
r@   c                    d}t          t          ddt          d          d           }|                    t	                                 |                    |           |                     t          |dd          du            |                     |j	        t                     |                     t          t          |j                                                            d           |                     t          t          |j                                                            d           |                     |j                   dS )zy
        If a response in the 1XX range is received it just gets swallowed and
        the parser resets itself.
           HTTP/1.1 103 Early Hints
Server: socketserver/1.0.0
Link: </other/styles.css>; rel=preload; as=style
Link: </other/action.js>; rel=preload; as=script

r   r   Nc                     d S rp   r?   rS  s    rA   r   zCHTTPClientParserTests.test_1XXResponseIsSwallowed.<locals>.<lambda>      T r@   r   r   )r!   r+   rf   r   r   r   r   getattrrL   r   r   rM   r   r   r   r  _everReceivedData)rR   sample103Responser   s      rA   test_1XXResponseIsSwallowedz1HTTPClientParserTests.test_1XXResponseIsSwallowed  s'    	 $FD.$779I9I
 
 	 1 1222/000 	*d;;tCDDD000T("2"C"C"E"EFFGGKKKT("6"G"G"I"IJJKKQOOO233333r@   c                    d}d}t          t          ddt          d          d           }|                    t	                                 |                    ||z              |                     |j        j        d           |                     |j        j	        t          i                      |                     |j        t          dd	gi                     |                     |j        j        d
           dS )z
        When a 1XX response is swallowed, the final response that follows it is
        the only one that gets sent to the application.
        r\  (   HTTP/1.1 200 OK
Content-Length: 123

r   r   Nc                     d S rp   r?   rS  s    rA   r   zUHTTPClientParserTests.test_1XXFollowedByFinalResponseOnlyEmitsFinal.<locals>.<lambda>  r^  r@   rd   r   r  r  r!   r+   rf   r   r   r   rL   r   r   r   r3   r  r   rR   ra  following200Responser   s       rA   -test_1XXFollowedByFinalResponseOnlyEmitsFinalzCHTTPClientParserTests.test_1XXFollowedByFinalResponseOnlyEmitsFinal  s     	  Y#FD.$779I9I
 
 	 1 1222/2FFGGG*/555*2GBKK@@@-w8IF87T/U/UVVV*1377777r@   c                    d}d}t          t          ddt          d          d           }|                    t	                                 |                    ||z   |z   |z              |                     |j        j        d           |                     |j        j	        t          i                      |                     |j        t          dd	gi                     |                     |j        j        d
           dS )zp
        It is acceptable for multiple 1XX responses to come through, all of
        which get ignored.
        r\  rd  r   r   Nc                     d S rp   r?   rS  s    rA   r   zKHTTPClientParserTests.test_multiple1XXResponsesAreIgnored.<locals>.<lambda>  r^  r@   rd   r   r  r  rf  rg  s       rA   #test_multiple1XXResponsesAreIgnoredz9HTTPClientParserTests.test_multiple1XXResponsesAreIgnored  s    	  Y#FD.$779I9I
 
 	 1 1222   ##	
 	
 	
 	*/555*2GBKK@@@-w8IF87T/U/UVVV*1377777r@   c                    t          j        | t                    }d}t          t	          ddt
          d          d           }|                    t                                 |                    |           | 	                    dt          |                     |d         }| 	                    |d         d	           | 	                    |d
         d           dS )zF
        When a 1XX response is ignored, Twisted emits a log.
        r\  r   r   Nc                     d S rp   r?   rS  s    rA   r   zHHTTPClientParserTests.test_ignored1XXResponseCausesLog.<locals>.<lambda>
  r^  r@   rc   r   
log_formatz#Ignoring unexpected {code} responser   g   )r   rJ  r   r!   r+   rf   r   r   r   rK  rM   )rR   rN  ra  r   rO  s        rA    test_ignored1XXResponseCausesLogz6HTTPClientParserTests.test_ignored1XXResponseCausesLog  s     +<TCUVV 	 $FD.$779I9I
 
 	 1 1222/000!S--...A%-/TUUU%------r@   N)&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.  r4  r6  r9  r<  r?  rC  rP  rV  rZ  rb  ri  rl  rq  r?   r@   rA   r   r   j  s0        
P P P# # #,: : :8 8 8) ) )&" " "H
= 
= 
=4 4 44 4 4G G G G G G&8 8 8(6 6 6$* * *>6 6 62
 
 
$/ / /$
 
 
/ / / 
 
 

 
 
@ @ @"@ @ @"#/ #/ #/J* * *0* * *<R R R3 3 3:< < <
 
 
$4 4 448 8 828 8 8<. . . . .r@   r   c                   *    e Zd ZdZdZdZdZd Zd ZdS )SlowRequesta  
    L{SlowRequest} is a fake implementation of L{Request} which is easily
    controlled externally (for example, by code in a test method).

    @ivar stopped: A flag indicating whether C{stopWriting} has been called.

    @ivar finished: After C{writeTo} is called, a L{Deferred} which was
        returned by that method.  L{SlowRequest} will never fire this
        L{Deferred}.
    r   Fc                 6    t                      | _        | j        S rp   )r   r   rR   rg   s     rA   writeTozSlowRequest.writeTo%  s     

}r@   c                     d| _         d S r   stoppedrq   s    rA   stopWritingzSlowRequest.stopWriting)      r@   N)	r;   r<   r=   r>   methodry  
persistentrv  rz  r?   r@   rA   rs  rs    sM        	 	 FGJ      r@   rs  c                       e Zd ZdZdZd ZdS )SimpleRequesta  
    L{SimpleRequest} is a fake implementation of L{Request} which writes a
    short, fixed string to the transport passed to its C{writeTo} method and
    returns a succeeded L{Deferred}.  This vaguely emulates the behavior of a
    L{Request} with no body producer.
    Fc                 J    |                     d           t          d           S )N
   SOME BYTES)writer	   ru  s     rA   rv  zSimpleRequest.writeTo7  s     &&&t}}r@   N)r;   r<   r=   r>   r}  rv  r?   r@   rA   r  r  -  s4          J    r@   r  c                       e Zd ZdZd Zd Zd Zd Zd Zd Z	d&d	Z
d
 Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Z d  Z!d! Z"d" Z#d# Z$d$ Z%d% Z&dS )'HTTP11ClientProtocolTestsz]
    Tests for the HTTP 1.1 client protocol implementation,
    L{HTTP11ClientProtocol}.
    c                     t                      | _        t                      | _        | j                            | j                   dS )zR
        Create an L{HTTP11ClientProtocol} connected to a fake transport.
        N)r   rg   r)   r   r   rq   s    rA   setUpzHTTP11ClientProtocolTests.setUpB  s<     )**,..$$T^44444r@   c                     | j                             t                                 |                     | j                                        d           dS )z
        L{HTTP11ClientProtocol.request} accepts a L{Request} and calls its
        C{writeTo} method with its own transport.
        r  N)r   r   r  rL   rg   r   rq   s    rA   test_requestz&HTTP11ClientProtocolTests.test_requestJ  sH    
 	moo...--//?????r@   c                      j                             t                                  fd}                      j                             t	                                t
                    }|                    |           |S )z
        The second time L{HTTP11ClientProtocol.request} is called, it returns a
        L{Deferred} which immediately fires with a L{Failure} wrapping a
        L{RequestNotSent} exception.
        c                 b                         j                                        d           d S Nr@   rL   rg   r   ignoredrR   s    rA   	cbNotSentz?HTTP11ClientProtocolTests.test_secondRequest.<locals>.cbNotSentZ  -    T^1133S99999r@   )r   r   rs  rT   r  r%   rU   rR   r  rX   s   `  rA   test_secondRequestz,HTTP11ClientProtocolTests.test_secondRequestR  sz     	kmm,,,	: 	: 	: 	: 	: t}44]__EE~VV	i   r@   c                 "     j                             t          t          d                                fd}                      j                             t                                t                    }|                    |           |S )z
        L{HTTP11ClientProtocol.request} returns a L{Deferred} which immediately
        fires with a L{Failure} wrapping a L{RequestNotSent} if called after
        the protocol has been disconnected.
        zsad transportc                 b                         j                                        d           d S r  r  r  s    rA   r  zLHTTP11ClientProtocolTests.test_requestAfterConnectionLost.<locals>.cbNotSenti  r  r@   )	r   r;  r   r
   rT   r   r  r%   rU   r  s   `  rA   test_requestAfterConnectionLostz9HTTP11ClientProtocolTests.test_requestAfterConnectionLosta  s     	$$W^O-L-L%M%MNNN	: 	: 	: 	: 	: t}44]__EE~VV	i   r@   c                       G d d          } j                              |                      } fd}t           |t          g          }|                    |           |S )a%  
        If the L{Deferred} returned by L{Request.writeTo} fires with a
        L{Failure}, L{HTTP11ClientProtocol.request} disconnects its transport
        and returns a L{Deferred} which fires with a L{Failure} of
        L{RequestGenerationFailed} wrapping the underlying failure.
        c                       e Zd ZdZd ZdS )CHTTP11ClientProtocolTests.test_failedWriteTo.<locals>.BrokenRequestFc                 8    t          t                                S rp   )r   r9   ru  s     rA   rv  zKHTTP11ClientProtocolTests.test_failedWriteTo.<locals>.BrokenRequest.writeTo{  s    .00111r@   Nr;   r<   r=   r}  rv  r?   r@   rA   BrokenRequestr  x  s(        J2 2 2 2 2r@   r  c                                          j        j                   j                            t          t          d                               d S )Nzyou asked for it)r   rg   disconnectingr   r;  r   r
   r  s    rA   rS   z>HTTP11ClientProtocolTests.test_failedWriteTo.<locals>.cbFailed  sI    OODN8999 M((@R1S1S)T)TUUUUUr@   )r   r   r^   r9   rU   )rR   r  rX   rS   s   `   rA   test_failedWriteToz,HTTP11ClientProtocolTests.test_failedWriteTop  s    	2 	2 	2 	2 	2 	2 	2 	2 M!!--//22	V 	V 	V 	V 	V *$4F3GHH	hr@   c                      G d d          }| j                              |                      }t          | |t          g          S )z
        If L{Request.writeTo} raises an exception,
        L{HTTP11ClientProtocol.request} returns a L{Deferred} which fires with
        a L{Failure} of L{RequestGenerationFailed} wrapping that exception.
        c                       e Zd ZdZd ZdS )MHTTP11ClientProtocolTests.test_synchronousWriteToError.<locals>.BrokenRequestFc                     t                      rp   rG  ru  s     rA   rv  zUHTTP11ClientProtocolTests.test_synchronousWriteToError.<locals>.BrokenRequest.writeTo  s    (***r@   Nr  r?   r@   rA   r  r    s(        J+ + + + +r@   r  )r   r   r^   r9   )rR   r  rX   s      rA   test_synchronousWriteToErrorz6HTTP11ClientProtocolTests.test_synchronousWriteToError  s]    	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ M!!--//22,T17I6JKKKr@   Nc                    t                      }| j                            |          }t          | |t          g          }|                     |j                   | j                            t          t	                                           | 	                    |j                   |dk    r|j
                            d           nx|dk    rq|j
                            t          t                                           |                     t                    }|                     t!          |          d           n	 |S )a2  
        If L{HTTP11ClientProtocol}'s transport is disconnected before the
        L{Deferred} returned by L{Request.writeTo} fires, the L{Deferred}
        returned by L{HTTP11ClientProtocol.request} fires with a L{Failure} of
        L{RequestTransmissionFailed} wrapping the underlying failure.
        callbackNerrbackrc   )rs  r   r   r`   r9   r   ry  r;  r   r   r   r  r  rC   rM  rL   rM   )rR   moder   rX   errorss        rA   *test_connectionLostDuringRequestGenerationzDHTTP11ClientProtocolTests.test_connectionLostDuringRequestGeneration  s    --M!!'**+D!6H5IJJ 	)))$$W-?-A-A%B%BCCC 	(((:%%d++++Y$$W-F-H-H%I%IJJJ++,EFFFS[[!,,,, r@   c                 ,    |                      d          S )z
        If the request passed to L{HTTP11ClientProtocol} finishes generation
        successfully after the L{HTTP11ClientProtocol}'s connection has been
        lost, nothing happens.
        r  r  rq   s    rA   +test_connectionLostBeforeGenerationFinishedzEHTTP11ClientProtocolTests.test_connectionLostBeforeGenerationFinished  s     >>zJJJr@   c                 ,    |                      d          S )z
        If the request passed to L{HTTP11ClientProtocol} finished generation
        with an error after the L{HTTP11ClientProtocol}'s connection has been
        lost, nothing happens.
        r  r  rq   s    rA   )test_connectionLostBeforeGenerationFailedzCHTTP11ClientProtocolTests.test_connectionLostBeforeGenerationFailed  s     >>yIIIr@   c                      t          j         t                     fd}                     d                              |          S )a	  
        If the request passed to L{HTTP11ClientProtocol} finished generation
        with an error after the L{HTTP11ClientProtocol}'s connection has been
        lost, an error is logged that gives a non-confusing hint to user on what
        went wrong.
        c                                          dt                               d         }                    d|                               |d         d                               |d         d           d S )Nrc   r   rI  ro  zJError writing request, but not in valid state to finalize request: {state}r   CONNECTION_LOST)rK  rM   assertInrL   )ignorerO  rN  rR   s     rA   checkznHTTP11ClientProtocolTests.test_errorMessageOnConnectionLostBeforeGenerationFailedDoesNotConfuse.<locals>.check  s    a[!1!1222NEMM-///l#/  
 U7^->?????r@   r  )r   rJ  r   r  rU   )rR   r  rN  s   ` @rA   Etest_errorMessageOnConnectionLostBeforeGenerationFailedDoesNotConfusez_HTTP11ClientProtocolTests.test_errorMessageOnConnectionLostBeforeGenerationFailedDoesNotConfuse  sh     +<TCUVV		@ 		@ 		@ 		@ 		@ 		@ >>yIIUU
 
 	
r@   c                       j                             t          ddt          d                    } fd}|                    |            j                             d           |S )z
        When a response is delivered to L{HTTP11ClientProtocol}, the
        L{Deferred} previously returned by the C{request} method is called back
        with a L{Response} instance and the connection is closed.
        r   r   Nc                 
                        | j        d                                | j        t                                                     j        j                                        j        j        d           d S )Nrd   	QUIESCENT)	rL   r   r   r3   r   rg   r  r   r   )r   rR   s    rA   	cbRequestzIHTTP11ClientProtocolTests.test_receiveSimplestResponse.<locals>.cbRequest  sp    X]C000X-wyy999OODN8999T]0+>>>>>r@   s9   HTTP/1.1 200 OK
Content-Length: 0
Connection: close

r   r   r+   rf   rU   r   rR   rX   r  s   `  rA   test_receiveSimplestResponsez6HTTP11ClientProtocolTests.test_receiveSimplestResponse  s{     M!!'&$"M"MNN	? 	? 	? 	? 	? 	
i   ""	
 	
 	
 r@   c                       j                             t          ddt          d                    } fd}|                    |            j                             d           |S )z
        The headers included in a response delivered to L{HTTP11ClientProtocol}
        are included on the L{Response} instance passed to the callback
        returned by the C{request} method.
        r   r   Nc                 d    t          dddgi          }                    | j        |           d S )Nr  r   r   )r3   rL   r   )r   r   rR   s     rA   r  zHHTTP11ClientProtocolTests.test_receiveResponseHeaders.<locals>.cbRequest  s9    66*:;<<HX-x88888r@   s+   HTTP/1.1 200 OK
X-Foo: bar
X-Foo: baz

r  r  s   `  rA   test_receiveResponseHeadersz5HTTP11ClientProtocolTests.test_receiveResponseHeaders  sy     M!!'&$"M"MNN	9 	9 	9 	9 	9 	
i   ""N	
 	
 	
 r@   c                 b    g t                      t          j                                                 t	                                                    }                    d            fd}|                    |            fd}|                    |           |S )a[  
        If response bytes are delivered to L{HTTP11ClientProtocol} before the
        L{Deferred} returned by L{Request.writeTo} fires, those response bytes
        are parsed as part of the response.

        The connection is also closed, because we're in a confusing state, and
        therefore the C{quiescentCallback} isn't called.
        s8   HTTP/1.1 200 OK
X-Foo: bar
Content-Length: 6

foobarc                 @    t                      t                      x}_                                                            j        d                               j                                       g            |                     fd          S )N%TRANSMITTING_AFTER_RECEIVING_RESPONSEc                     j         fS rp   r   rT  pr   s    rA   r   zoHTTP11ClientProtocolTests.test_receiveResponseBeforeRequestGenerationDone.<locals>.cbResponse.<locals>.<lambda>*      168J r@   )	r   r   closedDeferreddeliverBodyrL   r   r   r  rU   )r   whenFinishedr  r   quiescentResultrR   rg   s   ` @rA   
cbResponsez]HTTP11ClientProtocolTests.test_receiveResponseBeforeRequestGenerationDone.<locals>.cbResponse#  s    $&&A.6jj8L1+  ###X^-TUUUOOI3444_b111++,J,J,J,J,JKKKr@   c                 j   | \  }}                     |j        d                                |j        d                                |j        d                                |j        t          ddgi                                          |d           j                            d            d S )Nrb   rd   re   r  r      foobar)rL   r   r   r   r   r3   r   r  )resultr   r   r   rR   s      rA   cbAllResponsez`HTTP11ClientProtocolTests.test_receiveResponseBeforeRequestGenerationDone.<locals>.cbAllResponse.  s    #NHdX-???X]C000X_e444X-w6(7K/L/LMMMT9--- %%d+++++r@   )r   r)   r   r   rs  r   r   rU   )rR   rX   r  r  r   r  r   rg   s   `   @@@@rA   /test_receiveResponseBeforeRequestGenerationDonezIHTTP11ClientProtocolTests.test_receiveResponseBeforeRequestGenerationDone  s     #%%	'(>??	***--W%%	
 	
 	
	L 	L 	L 	L 	L 	L 	L 	L 	
j!!!
	, 
	, 
	, 
	, 
	, 
	, 	
m$$$r@   c                 H   t                      }t                      }||_        |                    |           dt          j        z  }|                    t          ddt          d                    }|	                    d|z   dz              t          | |t          g          S )zy
        The connection is closed when the server respond with a header which
        is above the maximum line.
        r8  r   r   Ns   HTTP/1.1 200 OK
X-Foo: s   
X-Ignored: ignored

)r   r)   r   r   r   
MAX_LENGTHr   r+   rf   r   r\   r
   )rR   rg   r   longLinerX   s        rA   "test_receiveResponseHeadersTooLongz<HTTP11ClientProtocolTests.test_receiveResponseHeadersTooLong=  s    
 566	'))%		***,11WVT>4HHII!"%	
 	
 	
 $D!n-=>>>r@   c                      t                       j                                      } j                            d           d }|                    |            fd}|                    |           |S )z
        If response bytes are delivered to L{HTTP11ClientProtocol} before the
        request completes, calling C{connectionLost} on the protocol will
        result in protocol being moved to C{'CONNECTION_LOST'} state.
        s8   HTTP/1.1 400 BAD REQUEST
Content-Length: 9

tisk tiskc                      t                      t                      x}_                                        |                     fd          S )Nc                     j         fS rp   r  r  s    rA   r   zHTTP11ClientProtocolTests.test_connectionLostAfterReceivingResponseBeforeRequestGenerationDone.<locals>.cbResponse.<locals>.<lambda>j  r  r@   )r   r   r  r  rU   )r   r  r  s   ` @rA   r  zrHTTP11ClientProtocolTests.test_connectionLostAfterReceivingResponseBeforeRequestGenerationDone.<locals>.cbResponsef  sU    $&&A.6jj8L1+  ###++,J,J,J,J,JKKKr@   c                     j                             d            j                            t	          t                                                               j        j        d           d S )Nr  )r   r  r   r;  r   r9   rL   r{   )r  r   rR   s    rA   r  zuHTTP11ClientProtocolTests.test_connectionLostAfterReceivingResponseBeforeRequestGenerationDone.<locals>.cbAllResponsen  sa    %%d+++M((1C1E1E)F)FGGGT]13DEEEEEr@   )rs  r   r   r   rU   )rR   rX   r  r  r   s   `   @rA   Dtest_connectionLostAfterReceivingResponseBeforeRequestGenerationDonez^HTTP11ClientProtocolTests.test_connectionLostAfterReceivingResponseBeforeRequestGenerationDoneW  s     --M!!'**""	
 	
 	
	L 	L 	L 	
j!!!	F 	F 	F 	F 	F 	F 	
m$$$r@   c                 R    t                      t                      x}_         j                            t          ddt          d                    } j                            d           g }|                    |j	                    
                    |g             j                            d           |d         }|                                j                            d            j                            d            fd	}|                    |           |S )
z
        The C{deliverBody} method of the response object with which the
        L{Deferred} returned by L{HTTP11ClientProtocol.request} fires can be
        used to get the body of the response.
        r   r   Ns%   HTTP/1.1 200 OK
Content-Length: 6
r   r   r   r   c                 |                         j        d           j                            t                     d S )Nr  )rL   r   closedReasonrK   r/   )r  r   rR   s    rA   r  zIHTTP11ClientProtocolTests.test_receiveResponseBody.<locals>.cbAllResponse  s8    X]I666!&&|44444r@   )r   r   r  r   r   r+   rf   r   rU   r   rL   r  )rR   r  requestDeferredr  r   r  r   s   `     @rA   test_receiveResponseBodyz2HTTP11ClientProtocolTests.test_receiveResponseBodyw  s7    ())19;x.-//FD.$77
 
 	""A	
 	
 	
 ##FM222$$$ 	""5)))!9X&&&""6***""6***	5 	5 	5 	5 	5 	5 	  ///r@   c                 j   | j                             t          ddt          d                    }| j                             d           g }|                    |j                   |d         }t                      }|                    |           | j                             d           | j                             d           | 	                    |j
        d           | j                             t          t          d	                               |j                            t                      dS )
z
        If the length of the response body is unknown, the protocol passed to
        the response's C{deliverBody} method has its C{connectionLost}
        method called with a L{Failure} wrapping a L{PotentialDataLoss}
        exception.
        r   r   Ns   HTTP/1.1 200 OK

r   r   r   r  z low-level transport disconnected)r   r   r+   rf   r   rU   r   r   r  rL   r   r;  r   r
   r  rK   r*   rR   r  r  r   r   s        rA   Etest_responseBodyFinishedWhenConnectionLostWhenContentLengthIsUnknownz_HTTP11ClientProtocolTests.test_responseBodyFinishedWhenConnectionLostWhenContentLengthIsUnknown  s    -//FD.$77
 
 	""#ABBB##FM222!9'))X&&&""6***""6***	222$$N#EFFGG	
 	
 	
 	""#455555r@   c                    | j                             t          ddt          d                    }| j                             d           g }|                    |j                   |d         }t                      }|                    |           | j                             d           | j                             d           | 	                    |j
        d           | j                             t          t                                           t          | t          |j                  t          t"          g          S )	a  
        If the final chunk has not been received when the connection is lost
        (for any reason), the protocol passed to C{deliverBody} has its
        C{connectionLost} method called with a L{Failure} wrapping the
        exception for that reason.
        r   r   Ns/   HTTP/1.1 200 OK
Transfer-Encoding: chunked

r      3
foo
s   3
bar
r  )r   r   r+   rf   r   rU   r   r   r  rL   r   r;  r   r9   r\   r   r  r2   r  s        rA   4test_chunkedResponseBodyUnfinishedWhenConnectionLostzNHTTP11ClientProtocolTests.test_chunkedResponseBodyUnfinishedWhenConnectionLost  s#    -//FD.$77
 
 	""L	
 	
 	
 ##FM222!9'))X&&&""?333""?333	222$$W-?-A-A%B%BCCC#$x,--0BI/N
 
 	
r@   c                       j                             t          ddt          d                    } j                             d           t           |t          g          } fd}|                    |           |S )a!  
        If the parser L{HTTP11ClientProtocol} delivers bytes to in
        C{dataReceived} raises an exception, the exception is wrapped in a
        L{Failure} and passed to the parser's C{connectionLost} and then the
        L{HTTP11ClientProtocol}'s transport is disconnected.
        r   r   Ns   unparseable garbage goes here
c                                         j        j                                       | j        d         j        j        d           j                            t          t          d                               d S )Nr   s   unparseable garbage goes herez
it is done)r   rg   r  rL   rJ   r   r   r   r;  r   r
   )r   rR   s    rA   rS   zLHTTP11ClientProtocolTests.test_parserDataReceivedException.<locals>.cbFailed  sr    OODN8999A$)+K   M((1M1M)N)NOOOOOr@   )r   r   r+   rf   r   r\   r$   rU   )rR   r  rX   rS   s   `   rA    test_parserDataReceivedExceptionz:HTTP11ClientProtocolTests.test_parserDataReceivedException  s     -//FD.$77
 
 	""#GHHH EE
	P 
	P 
	P 
	P 
	P 	
hr@   c                    | j                             t          ddt          d                    }| j         j        j        }|                     |j        | j                   | j                             t          t          d                               |                     |j        d           t          | |t          g          S )z
        When the HTTP response parser is disconnected, the
        L{TransportProxyProducer} which was connected to it as a transport is
        stopped.
        r   r   Nzconnection done)r   r   r+   rf   _parserrg   r  	_producer_disconnectParserr   r
   r\   )rR   r  rg   s      rA   test_proxyStoppedz+HTTP11ClientProtocolTests.test_proxyStopped  s     -//FD.$77
 
 M)3	Y0$.AAA''?P0Q0Q(R(RSSSY0$777#D/N;KLLLr@   c                 @   t                      }t                      }|                    |           g }g }|                                                    |j                   |                                                    |j                   |                     ||fg g f           |                     |j                   |	                    t          t                                           |                     |dg           |                     |dg           dS )z
        L{HTTP11ClientProtocol.abort} will tell the transport to close its
        connection when it is invoked, and returns a C{Deferred} that fires
        when the connection is lost.
        N)r   r)   r   abortrU   r   rL   r   r  r;  r   r
   )rR   rg   r   r1r2s        rA   test_abortClosesConnectionz4HTTP11ClientProtocolTests.test_abortClosesConnection  s    $%%	'))	***$$RY///$$RY///"bB8,,,	/000 	(8(8 9 9:::dV$$$dV$$$$$r@   c                    t                      }t                      }|                    |           |                    t	          t                                           g }|                                                    |j                   | 	                    |dg           | 	                    |j
        d           dS )z
        L{HTTP11ClientProtocol.abort} called after the connection is lost
        returns a C{Deferred} that fires immediately.
        Nr  )r   r)   r   r;  r   r
   r  rU   r   rL   r{   rR   rg   r   r  s       rA   test_abortAfterConnectionLostz7HTTP11ClientProtocolTests.test_abortAfterConnectionLost  s    
 $%%	'))	***(8(8 9 9:::$$V]333$(((*;<<<<<r@   c                    t                      }t                      }|                    |           |                    t	          ddt
          d                    }|                                 |                     |j                   |	                    t          t                                           t          | |t          g          S )a  
        The Deferred returned by L{HTTP11ClientProtocol.request} will fire
        with a L{ResponseFailed} failure containing a L{ConnectionAborted}
        exception, if the connection was aborted before all response headers
        have been received.
        r   r   N)r   r)   r   r   r+   rf   r  r   r  r;  r   r
   r\   r   r  s       rA   test_abortBeforeResponseBodyz6HTTP11ClientProtocolTests.test_abortBeforeResponseBody,  s     $%%	'))	***!!'&$"M"MNN	/000(8(8 9 9:::#D&3D2EFFFr@   c                     t          d          t                                                                         t	          ddt
          d                    }                    d           t                       G fddt                     fd	} fd
}|	                    |           t           t          t          g          }|	                    |          S )aS  
        When the connection is aborted after the response headers have
        been received and the L{Response} has been made available to
        application code, the response body protocol's C{connectionLost}
        method will be invoked with a L{ResponseFailed} failure containing a
        L{ConnectionAborted} exception.
        T)lenientr   r   NrE  c                   (    e Zd ZdZ fdZfdZdS )QHTTP11ClientProtocolTests.test_abortAfterResponseHeaders.<locals>.BodyDestinationzl
            A body response protocol which immediately aborts the HTTP
            connection.
            c                 0                                      dS )z<
                Abort the HTTP connection.
                N)r  r   s    rA   connectionMadez`HTTP11ClientProtocolTests.test_abortAfterResponseHeaders.<locals>.BodyDestination.connectionMadeV  s          r@   c                 2                         |           dS )z
                Make the reason for the losing of the connection available to
                the unit test via C{testResult}.
                N)r  )rR   rO   
testResults     rA   r;  z`HTTP11ClientProtocolTests.test_abortAfterResponseHeaders.<locals>.BodyDestination.connectionLost\  s    
 ""6*****r@   N)r;   r<   r=   r>   r  r;  )r   r  s   rA   BodyDestinationr  P  sQ         
! ! ! ! !+ + + + + + +r@   r   c                     |                                                                  j                                       t	          t                                           dS )z
            Connect the L{BodyDestination} response body protocol to the
            response, and then simulate connection loss after ensuring that
            the HTTP connection has been aborted.
            N)r  r   r  r;  r   r
   )r   r   r   rR   rg   s    rA   r  zMHTTP11ClientProtocolTests.test_abortAfterResponseHeaders.<locals>.deliverBodyc  s^       !2!2333OOI3444##GN,<,<$=$=>>>>>r@   c                 H                         | j        t                     d S rp   )rL  r   r.   )errorrR   s    rA   
checkErrorzLHTTP11ClientProtocolTests.test_abortAfterResponseHeaders.<locals>.checkErrorm  s!    !!%.(;;;;;r@   )r   r)   r   r   r+   rf   r   r   r   rU   r\   r   r2   )	rR   r  r  r  rV   r   r   r  rg   s	   `    @@@@rA   test_abortAfterResponseHeadersz8HTTP11ClientProtocolTests.test_abortAfterResponseHeaders<  s9    $D111	'))	***!!'&$"M"MNNUVVVZZ
	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+h 	+ 	+ 	+&	? 	? 	? 	? 	? 	? 	? 	?	< 	< 	< 	< 	< 	;''''*0)<
 
 ##J///r@   c           	          g  fd}t                      }t          |                              |                               t	          ddt
          dd                    }                    d                                g            g }|                    |j	                   |d         }t                      }t                      |_        |j                            fd	           |                    |                               d
           |j                            t                                           dg                                j        d                                j        d                                j        d                                j        d                                j        d           dS )a  
        If after a response is done the {HTTP11ClientProtocol} stays open and
        returns to QUIESCENT state, all per-request state is reset and the
        C{quiescentCallback} is called with the protocol instance.

        This is useful for implementing a persistent connection pool.

        The C{quiescentCallback} is called *before* the response-receiving
        protocol's C{connectionLost}, so that new requests triggered by end of
        first request can re-use a persistent connection.
        c                                          |                                 | j        d                               |            d S Nr  rL   r   r   r  r   r  rR   s    rA   r  zHHTTP11ClientProtocolTests.test_quiescentCallbackCalled.<locals>.callback  K    Q)))QWk222""1%%%%%r@   r   r   NTr}  s&   HTTP/1.1 200 OK
Content-length: 3

r   c                 .                         d          S )Nresponse doner   )rT  r  s    rA   r   zHHTTP11ClientProtocolTests.test_quiescentCallbackCalled.<locals>.<lambda>  s    ..?? r@   r>  r  )r   r)   r   r   r+   rf   r   rL   rU   r   r   r   r  r  r  rK   r/   r  _finishedRequest_currentRequest_transportProxyrA  )	rR   r  rg   r  r  r   bodyProtocolr   r  s	   `      @@rA   test_quiescentCallbackCalledz6HTTP11ClientProtocolTests.test_quiescentCallbackCalledv  s    	& 	& 	& 	& 	& 	& 	&
 $%%	'11	***"**FD.$4HHH
 
 	UVVV 	"---##FM222!9 ,--&.jj##//????	
 	
 	
 	\***f%%%!&&|444 	8_*EFFF 	)40002D99914888148883T:::::r@   c           	          g  fd}t                      }t          |                              |                               t	          ddt
          dd                    }                    d                                |          }                     |j	        d                                t                    d	                                |j        d
           dS )a  
        The C{quiescentCallback} passed to L{HTTP11ClientProtocol} will only be
        invoked once that protocol is in a state similar to its initial state.
        One of the aspects of this initial state is the producer-state of its
        transport; an L{HTTP11ClientProtocol} begins with a transport that is
        producing, i.e. not C{pauseProducing}'d.

        Therefore, when C{quiescentCallback} is invoked the protocol will still
        be producing.
        c                                          |                                 | j        d                               |            d S r  r	  r
  s    rA   r  z]HTTP11ClientProtocolTests.test_transportProducingWhenQuiescentAfterFullBody.<locals>.callback  r  r@   r   r   NTr  s)   HTTP/1.1 200 OK
Content-length: 3

BBBDEFERRED_CLOSErc   r   )r   r)   r   r   r+   rf   r   successResultOfrL   r{   rM   r   )rR   r  rg   r  r   r   r  s   `    @@rA   1test_transportProducingWhenQuiescentAfterFullBodyzKHTTP11ClientProtocolTests.test_transportProducingWhenQuiescentAfterFullBody  s    	& 	& 	& 	& 	& 	& 	&
 $%%	'11	***"**FD.$4HHH
 
 		
 	
 	
 ''88 	*:;;;
 	_--q111
 	0+>>>>>r@   c           	          g  fd}t                      }t          |                              |                               t	          ddt
          dd                    }|                    j                                       d            	                    t                    d                                d	                                         d
         t                     dS )z
        The quiescentCallback is called before the request C{Deferred} fires,
        in cases where the response has no body.
        c                                          |                                 | j        d                               |            d S r  r	  r
  s    rA   r  zUHTTP11ClientProtocolTests.test_quiescentCallbackCalledEmptyResponse.<locals>.callback  r  r@   r   r   NTr  &   HTTP/1.1 200 OK
Content-length: 0

r   r   rc   )r   r)   r   r   r+   rf   rU   r   r   rL   rM   r  rL  r.   )rR   r  rg   r  r   r  s   `   @@rA   )test_quiescentCallbackCalledEmptyResponsezCHTTP11ClientProtocolTests.test_quiescentCallbackCalledEmptyResponse  s   
 	& 	& 	& 	& 	& 	& 	&
 $%%	'11	***"**FD.$4HHH
 
 	##O$:;;;UVVV_--q111_Q/:::oa0(;;;;;r@   c           	      &   g }t                      }t          |j                  }|                    |           |                    t          ddt          dd                    }|                    d           g }|                    |j                   |d         }t                      }|
                    |           |j                            t                     |                     |g            |                     |j                   dS )z
        If after a response is done the {HTTP11ClientProtocol} returns a
        C{Connection: close} header in the response, the C{quiescentCallback}
        is not called and the connection is lost.
        r   r   NTr  s9   HTTP/1.1 200 OK
Content-length: 0
Connection: close

r   r   r)   r   r   r   r+   rf   r   rU   r   r  r  rK   r/   rL   r   r  rR   r  rg   r   r  r  r   r  s           rA   test_quiescentCallbackNotCalledz9HTTP11ClientProtocolTests.test_quiescentCallbackNotCalled  s    #%%	'(>??	***"**FD.$4HHH
 
 		
 	
 	
 ##FM222!9+--\***!&&|444"---	/00000r@   c           	      &   g }t                      }t          |j                  }|                    |           |                    t          ddt          dd                    }|                    d           g }|                    |j                   |d         }t                      }|
                    |           |j                            t                     |                     |g            |                     |j                   dS )z
        If the request was non-persistent (i.e. sent C{Connection: close}),
        the C{quiescentCallback} is not called and the connection is lost.
        r   r   NFr  r  r   r  r  s           rA   1test_quiescentCallbackNotCalledNonPersistentQueryzKHTTP11ClientProtocolTests.test_quiescentCallbackNotCalledNonPersistentQuery  s   
 #%%	'(>??	***"**FD.$5III
 
 	UVVV##FM222!9+--\***!&&|444"---	/00000r@   c           	          d }t          j        | t                    }t                      }t	          |          }|                    |           |                    t          ddt          dd                    }|	                    d           g }|
                    |j                   |d         }t                      }|                    |           |j                            t                      |                     d	t%          |                     |d         }	|	d
         }
|                     |
j        t*                     |                     t*                     |                     |j                   dS )zx
        If C{quiescentCallback} throws an exception, the error is logged and
        protocol is disconnected.
        c                     t                      rp   )ZeroDivisionError)r  s    rA   r  zHHTTP11ClientProtocolTests.test_quiescentCallbackThrows.<locals>.callback5  s    #%%%r@   r   r   NTr  r  r   rc   rI  )r   rJ  r   r   r)   r   r   r+   rf   r   rU   r   r   r  r  rK   r/   rK  rM   rL  r   r%  rM  r   r  )rR   r  rN  rg   r   r  r  r   r  rO  r   s              rA   test_quiescentCallbackThrowsz6HTTP11ClientProtocolTests.test_quiescentCallbackThrows/  sh   	& 	& 	& +<TCUVV#%%	'11	***"**FD.$4HHH
 
 	UVVV##FM222!9+--\***!&&|444!S--...A- ag'89990111	/00000r@   c                 N   t                      }t                      }|                    |           |                    t	          ddt
          d                    }|                                 |                     |j                   t          | |t          t          g          S )a  
        The L{Deferred} returned by L{HTTP11ClientProtocol.request} will fire
        with a L{ResponseNeverReceived} failure containing a L{CancelledError}
        exception if the request was cancelled before any response headers were
        received.
        r   r   N)r   r)   r   r   r+   rf   cancelr   disconnectedrY   r1   r   r  s       rA   test_cancelBeforeResponsez3HTTP11ClientProtocolTests.test_cancelBeforeResponseR  s     $%%	'))	***!!'&$"M"MNN	.///*&/.1A
 
 	
r@   c                 l   t                      }t                      }|                    |           |                    t	          ddt
          d                    }|                    d           |                                 |                     |j	                   t          | |t          g          S )a  
        The L{Deferred} returned by L{HTTP11ClientProtocol.request} will fire
        with a L{ResponseFailed} failure containing a L{CancelledError}
        exception if the request was cancelled before all response headers were
        received.
        r   r   Nr   )r   r)   r   r   r+   rf   r   r(  r   r)  r\   r   r  s       rA   test_cancelDuringResponsez3HTTP11ClientProtocolTests.test_cancelDuringResponsec  s     $%%	'))	***!!'&$"M"MNN4555	.///#D&>2BCCCr@   c                    t                      }t                      }|                    |           t          |          ddifdfd}|_        |                    t          ddt                              }j        	                    d           |
                                 |                     |j                   |                     d                    t          | |t          g          S )a  
        The L{Deferred} returned by L{HTTP11ClientProtocol.request} will fire
        with a L{RequestGenerationFailed} failure containing a
        L{CancelledError} exception if the request was cancelled before a
        C{bodyProducer} has finished producing.
        	cancelledFc                     dd<   d S )NTr.  r?   )rT  nonLocals    rA   r(  zJHTTP11ClientProtocolTests.assertCancelDuringBodyProduction.<locals>.cancel  s    $(H[!!!r@   c                 H    | _         t                    _        j        S rp   consumerr   r   )r3  r(  producers    rA   startProducingzRHTTP11ClientProtocolTests.assertCancelDuringBodyProduction.<locals>.startProducing  s$     (H ( 0 0H$$r@      POST   /bars   xxxxx)r   r)   r   StringProducerr5  r   r+   rf   r3  r  r(  r   r)  r^   r   )	rR   producerLengthrg   r   r5  r  r(  r0  r4  s	         @@@rA    assertCancelDuringBodyProductionz:HTTP11ClientProtocolTests.assertCancelDuringBodyProductions  s    $%%	'))	***!.11'	) 	) 	) 	) 	)	% 	% 	% 	% 	% 	%
 #1!!''7NH"U"UVV)))	.///-...,T6N;KLLLr@   c                 ,    |                      d          S )a(  
        The L{Deferred} returned by L{HTTP11ClientProtocol.request} will fire
        with a L{RequestGenerationFailed} failure containing a
        L{CancelledError} exception if the request was cancelled before a
        C{bodyProducer} with an explicit length has finished producing.
        
   )r:  rq   s    rA   test_cancelDuringBodyProductionz9HTTP11ClientProtocolTests.test_cancelDuringBodyProduction  s     44R888r@   c                 6    |                      t                    S )a'  
        The L{Deferred} returned by L{HTTP11ClientProtocol.request} will fire
        with a L{RequestGenerationFailed} failure containing a
        L{CancelledError} exception if the request was cancelled before a
        C{bodyProducer} with C{UNKNOWN_LENGTH} has finished producing.
        )r:  r   rq   s    rA   &test_cancelDuringChunkedBodyProductionz@HTTP11ClientProtocolTests.test_cancelDuringChunkedBodyProduction  s     44^DDDr@   rp   )'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?   r@   rA   r  r  <  sV        
5 5 5@ @ @      4L L L    @K K KJ J J
 
 
0  .  $0 0 0d? ? ?4  @' ' 'R6 6 6:
 
 
@  8M M M% % %*= = =G G G 80 80 80t7; 7; 7;r,? ,? ,?\< < <41 1 1>1 1 12!1 !1 !1F
 
 
"D D D M M M>9 9 9E E E E Er@   r  c                   4    e Zd ZdZdZd Zd Zd Zd Zd Z	dS )	r8  a  
    L{StringProducer} is a dummy body producer.

    @ivar stopped: A flag which indicates whether or not C{stopProducing} has
        been called.
    @ivar consumer: After C{startProducing} is called, the value of the
        C{consumer} argument to that method.
    @ivar finished: After C{startProducing} is called, a L{Deferred} which was
        returned by that method.  L{StringProducer} will never fire this
        L{Deferred}.
    Fc                     || _         d S rp   )r   )rR   r   s     rA   __init__zStringProducer.__init__  s    r@   c                 D    || _         t                      | _        | j        S rp   r2  )rR   r3  s     rA   r5  zStringProducer.startProducing  s      

}r@   c                     d| _         d S r   rx  rq   s    rA   stopProducingzStringProducer.stopProducing  r{  r@   c                     d S rp   r?   rq   s    rA   pauseProducingzStringProducer.pauseProducing      r@   c                     d S rp   r?   rq   s    rA   resumeProducingzStringProducer.resumeProducing  rH  r@   N)
r;   r<   r=   r>   ry  rB  r5  rE  rG  rJ  r?   r@   rA   r8  r8    sp        
 
 G    
        r@   r8  c                       e Zd ZdZd Zd Zd Zd Zd Zd Z	d Z
d	 Zd
 Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd ZddZd Zd Zd Zd Zd ZdS )RequestTestsz
    Tests for L{Request}.
    c                 ,    t                      | _        d S rp   )r   rg   rq   s    rA   r  zRequestTests.setUp  s    (**r@   c                     t          ddt          d                              | j                   |                     | j                                        d           dS )zk
        L{Request.writeTo} formats the request data and writes it to the given
        transport.
        r   r   Ns8   GET / HTTP/1.1
Connection: close
Host: example.com

r+   rf   rv  rg   rL   r   rq   s    rA   test_sendSimplestRequestz%RequestTests.test_sendSimplestRequest  s`    
 	nd33;;DNKKKN  ""	
 	
 	
 	
 	
r@   c                     t          ddt          dd          }|                    | j                   |                     | j                                        d           dS )zO
        A pesistent request does not send 'Connection: close' header.
        r   r   NTr  s%   GET / HTTP/1.1
Host: example.com

rO  )rR   reqs     rA   "test_sendSimplestPersistentRequestz/RequestTests.test_sendSimplestPersistentRequest  sf     fdNDTJJJDN###N  ""B	
 	
 	
 	
 	
r@   c                    t          ddgdgd          }t          dd|d                              | j                   | j                                                            d          }|                     |d	         d
           |                     |dd         ddg           |d	= |dd= |                                 |                     |g d           dS )zf
        L{Request.writeTo} formats header data and writes it to the given
        transport.
        r   r   rE   )r  rD   r      /fooNr   r      GET /foo HTTP/1.1r@   )   Connection: closes   Host: example.comr   r   )r3   r+   rv  rg   r   splitrL   sort)rR   r   liness      rA   test_sendRequestHeadersz$RequestTests.test_sendRequestHeaders  s    
 ff%5@PQQRR$//77GGG$$&&,,W55q#7888rssc3Z000!HeBCCj

VVV	
 	
 	
 	
 	
r@   c                 H   t           D ]}t          ||gddgi          }t                      }t          dd|d                              |           |                                                    d          }|                     |d         d           |                     |d	d         d
d
g           |d= |d	d= |                    d           |                    d           d	                    t          t          g          }|                     ||g           dS )z_
        Linear whitespace in request headers is replaced with a single
        space.
        rD   s   example.invalidr   rU  Nr   r   rV  rW  r@   rX  s   Host: example.invalids   : )r6   r3   r   r+   rv  r   rY  rL   remover   r7   )rR   	componentr   rg   r[  sanitizedHeaderLines         rA   -test_sanitizeLinearWhitespaceInRequestHeadersz:RequestTests.test_sanitizeLinearWhitespaceInRequestHeaders  s+   
 9 	; 	;Iy9+wAS@TUVVG'))IFGWd33;;IFFFOO%%++G44EU1X';<<<U233Z#s444a%*LL-...LL1222"'**nn-M"N"NU%8$9::::	; 	;r@   c                    t          t                    }t          ddt          |          }|                    | j                   |                     |j        d           |                     | j        j	        |           | 
                    | j        j                   |                     | j                                        d           | j                                         |j                            d           |j                            d           |j                            d           |                     | j        j	        d           |                     | j                                        d           dS )z
        L{Request.writeTo} uses chunked encoding to write data from the request
        body producer to the given transport.  It registers the request body
        producer with the transport.
        r6  r7  NsX   POST /bar HTTP/1.1
Connection: close
Transfer-Encoding: chunked
Host: example.com

s   xxxs   yyyyyyyyyyyyyyys!   3
xxx
f
yyyyyyyyyyyyyyy
0

)r8  r   r+   rf   rv  rg   assertNotIdenticalr3  r  r4  r   	streamingrL   r   clearr  r   r  rR   r4  r   s      rA   test_sendChunkedRequestBodyz(RequestTests.test_sendChunkedRequestBody  s]    ".11'7NHEE''' 14888T^4h???0111N  ""	
 	
 	
 	)))	***""4(((T^4d;;;N  ""P	
 	
 	
 	
 	
r@   c                 z    t          t                    }t          ddt          |          }|                     j                  } j                                         |j                            t                                  fd} 
                    |t                    }|                    |           |S )a  
        If L{Request} is created with a C{bodyProducer} without a known length
        and the L{Deferred} returned from its C{startProducing} method fires
        with a L{Failure}, the L{Deferred} returned by L{Request.writeTo} fires
        with that L{Failure} and the body producer is unregistered from the
        transport.  The final zero-length chunk is not written to the
        transport.
        r6  r7  c                                          j                                        d                               j        j        d            d S r  )rL   rg   r   r  r4  r  s    rA   rS   zCRequestTests.test_sendChunkedRequestBodyWithError.<locals>.cbFailed=  sH    T^1133S999  !8$?????r@   )r8  r   r+   rf   rv  rg   re  r   r  r9   rT   rU   )rR   r4  r   writeDeferredrS   rX   s   `     rA   $test_sendChunkedRequestBodyWithErrorz1RequestTests.test_sendChunkedRequestBodyWithError.  s     ".11'7NHEE77!!"4"6"6777	@ 	@ 	@ 	@ 	@ }.@AA	hr@   c                    t          d          }t          ddt          |          }|                    | j                   |                     |j        d           |                     | j        j        |           | 	                    | j        j
                   |                     | j                                        d           | j                                         |j                            d           |j                            d           |                     | j        j        d           |                     | j                                        d           dS )z
        If L{Request} is created with a C{bodyProducer} with a known length,
        that length is sent as the value for the I{Content-Length} header and
        chunked encoding is not used.
           r6  r7  NsO   POST /bar HTTP/1.1
Connection: close
Content-Length: 3
Host: example.com

r>  )r8  r+   rf   rv  rg   rc  r3  r  r4  r   rd  rL   r   re  r  r   r  rf  s      rA   test_sendRequestBodyWithLengthz+RequestTests.test_sendRequestBodyWithLengthE  s:    "!$$'7NHEE''' 14888T^4h???0111N  ""	
 	
 	
 	'''""4(((T^4d;;;--//88888r@   c                     t          |dt          d          }|                    | j                   |                     | j                                        |dz              dS )a"  
        Verify that the message generated by a L{Request} initialized with
        the given method and C{None} as the C{bodyProducer} includes
        I{Content-Length: 0} in the header.

        @param method: The HTTP method issue in the request.
        @type method: L{bytes}
        rU  NsK    /foo HTTP/1.1
Connection: close
Content-Length: 0
Host: example.com

rO  )rR   r|  r   s      rA   _sendRequestEmptyBodyWithLengthz,RequestTests._sendRequestEmptyBodyWithLengthb  sk     &'>4@@'''N  ""  	
 	
 	
 	
 	
r@   c                 0    |                      d           dS )z
        If I{PUT} L{Request} is created without a C{bodyProducer},
        I{Content-Length: 0} is included in the header and chunked
        encoding is not used.
        s   PUTNrp  rq   s    rA   test_sendPUTRequestEmptyBodyz)RequestTests.test_sendPUTRequestEmptyBodyw  s     	,,V44444r@   c                 0    |                      d           dS )z
        If I{POST} L{Request} is created without a C{bodyProducer},
        I{Content-Length: 0} is included in the header and chunked
        encoding is not used.
        r6  Nrr  rq   s    rA   test_sendPOSTRequestEmptyBodyz*RequestTests.test_sendPOSTRequestEmptyBody  s     	,,W55555r@   c                 `   t          d          }t          ddt          |          }|                    | j                  }|j                            d           |j                            d           | 	                    | j        j
        d           |                     |t                    S )a  
        If L{Request} is created with a C{bodyProducer} with a known length and
        the producer does not produce that many bytes, the L{Deferred} returned
        by L{Request.writeTo} fires with a L{Failure} wrapping a
        L{WrongBodyLength} exception.
        rm  r6  r7     abN)r8  r+   rf   rv  rg   r3  r  r   r  r  r4  rT   r'   rR   r4  r   rj  s       rA   #test_sendRequestBodyWithTooFewBytesz0RequestTests.test_sendRequestBodyWithTooFewBytes  s     "!$$'7NHEE77&&&""4(((T^4d;;;!!-AAAr@   c                 
    t          d          t          ddt                    }|                     j                  }j                            d                                j                   j                            d            	                    j                    
                     j        j        d            fd}                     |t                    }|                    |           |S )a7  
        Verify that when too many bytes have been written by a body producer
        and then the body producer's C{startProducing} L{Deferred} fires that
        the producer is unregistered from the transport and that the
        L{Deferred} returned from L{Request.writeTo} is fired with a L{Failure}
        wrapping a L{WrongBodyLength}.

        @param finisher: A callable which will be invoked with the body
            producer after too many bytes have been written to the transport.
            It should fire the startProducing Deferred somehow.
        rm  r6  r7  rw     cdNc                 P                        j                                        d           j                                                             t
          j        j        d                                            j                                        d           d S )NsQ   POST /bar HTTP/1.1
Connection: close
Content-Length: 3
Host: example.com

abs   efr@   )rL   rg   r   re  r   r    r3  r  )r   finisherr4  rR   s    rA   rS   zCRequestTests._sendRequestBodyWithTooManyBytesTest.<locals>.cbFailed  s     $$&&   N  """ k8+<+BEJJJ
 HX T^1133S99999r@   )r8  r+   rf   rv  rg   r3  r  r   ry  r   r  r4  rT   r'   rU   )rR   r}  r   rj  rS   rX   r4  s   ``    @rA   $_sendRequestBodyWithTooManyBytesTestz1RequestTests._sendRequestBodyWithTooManyBytesTest  s    "!$$'7NHEE77&&& 	)***&&& 	())) 	T^4d;;;	: 	: 	: 	: 	: 	: 	:: }o>>	hr@   c                 2    d }|                      |          S )  
        If L{Request} is created with a C{bodyProducer} with a known length and
        the producer tries to produce more than than many bytes, the
        L{Deferred} returned by L{Request.writeTo} fires with a L{Failure}
        wrapping a L{WrongBodyLength} exception.
        c                 :    | j                             d            d S rp   r   r  r4  s    rA   r}  zCRequestTests.test_sendRequestBodyWithTooManyBytes.<locals>.finisher      &&t,,,,,r@   )r~  rR   r}  s     rA   $test_sendRequestBodyWithTooManyBytesz1RequestTests.test_sendRequestBodyWithTooManyBytes  s'    	- 	- 	- 88BBBr@   c                 p     t          j         t                     fd}                     |          S )r  c                 Z   | j                             t                                 d         }                    d|           |d         }                    |j        t                                         t                    }                    t          |          d           d S )Nr   rI  rc   )	r   r  r9   r  rL  r   rM  rL   rM   )r4  rO  r   r  rN  rR   s       rA   r}  zHRequestTests.test_sendRequestBodyErrorWithTooManyBytes.<locals>.finisher  s    %%&8&:&:;;;NEMM-///m$A!!!'+=>>>++,>??FS[[!,,,,,r@   )r   rJ  r   r~  )rR   r}  rN  s   ` @rA   )test_sendRequestBodyErrorWithTooManyBytesz6RequestTests.test_sendRequestBodyErrorWithTooManyBytes  sM     +<TCUVV	- 	- 	- 	- 	- 	- 88BBBr@   c                 ~   t          j        | t                    }t          d          }t	          ddt
          |          }|                    | j                   |j        j	        }|j        
                    d           |j                            d           |                    t                                 |d         }|                     d|           |d         }|                     |j        t                     |                     t'          |                     t                              d           dS )	a  
        Though there should be no way for the internal C{finishedConsuming}
        L{Deferred} in L{Request._writeToBodyProducerContentLength} to fire a
        L{Failure} after the C{finishedProducing} L{Deferred} has fired, in
        case this does happen, the error should be logged with a message about
        how there's probably a bug in L{Request}.

        This is a whitebox test.
        rm  r6  r7  r>  Nr   rI  rc   )r   rJ  r   r8  r+   rf   rv  rg   r3  	_finishedr  r   r  r  r9   r  rL  r   rL   rM   rM  )rR   rN  r4  r   finishedConsumingrO  r   s          rA   *test_sendRequestBodyErrorWithConsumerErrorz7RequestTests.test_sendRequestBodyErrorWithConsumerError  s    +<TCUVV!!$$'7NHEE'''$-7'''""4(((!!"4"6"6777AmU+++- ag'9:::T334FGGHH!LLLLLr@   c                    t          d          }t          ddt          |          }|                    | j                  }|j                            d            ||           |                     | j        j        d           | j        	                                 | 
                    t          |j        j        d           |                     | j                                        d           |S )a  
        Verify that if the body producer fires its Deferred and then keeps
        writing to the consumer that the extra writes are ignored and the
        L{Deferred} returned by L{Request.writeTo} fires with a L{Failure}
        wrapping the most appropriate exception type.
        rm  r6  r7  rw  Nr{  r@   )r8  r+   rf   rv  rg   r3  r  r  r4  re  r   r    rL   r   )rR   r}  r4  r   rj  s        rA   -_sendRequestBodyFinishedEarlyThenTooManyBytesz:RequestTests._sendRequestBodyFinishedEarlyThenTooManyBytes	  s     "!$$'7NHEE77&&&T^4d;;;+x'8'>FFF--//555r@   c                 d    d }|                      |                     |          t                    S )a-  
        If the request body producer indicates it is done by firing the
        L{Deferred} returned from its C{startProducing} method but then goes on
        to write too many bytes, the L{Deferred} returned by {Request.writeTo}
        fires with a L{Failure} wrapping L{WrongBodyLength}.
        c                 :    | j                             d            d S rp   r  r  s    rA   r}  zPRequestTests.test_sendRequestBodyFinishedEarlyThenTooManyBytes.<locals>.finisher.	  r  r@   )rT   r  r'   r  s     rA   1test_sendRequestBodyFinishedEarlyThenTooManyBytesz>RequestTests.test_sendRequestBodyFinishedEarlyThenTooManyBytes&	  s?    	- 	- 	- !!>>xHH
 
 	
r@   c                 d    d }|                      |                     |          t                    S )a3  
        If the request body producer indicates an error by firing the
        L{Deferred} returned from its C{startProducing} method but then goes on
        to write too many bytes, the L{Deferred} returned by {Request.writeTo}
        fires with that L{Failure} and L{WrongBodyLength} is logged.
        c                 R    | j                             t                                 d S rp   )r   r  r9   r  s    rA   r}  zORequestTests.test_sendRequestBodyErroredEarlyThenTooManyBytes.<locals>.finisher>	  s&    %%&8&:&:;;;;;r@   )rT   r  r9   r  s     rA   0test_sendRequestBodyErroredEarlyThenTooManyBytesz=RequestTests.test_sendRequestBodyErroredEarlyThenTooManyBytes6	  s?    	< 	< 	< !!>>xHH
 
 	
r@   Nc                    t          t                    }t          ddt          |          }|                    | j                  }|j                            |           | j                                         | 	                    t          |j        j        d           |                     | j                                        d           |S )a  
        If the request body producer with an unknown length tries to write
        after firing the L{Deferred} returned by its C{startProducing} method,
        the C{write} call raises an exception and does not write anything to
        the underlying transport.
        r6  r7  r   r@   )r8  r   r+   rf   rv  rg   r   r  re  r   r    r3  r  rL   r   )rR   _withr4  r   rj  s        rA   0test_sendChunkedRequestBodyFinishedThenWriteMorez=RequestTests.test_sendChunkedRequestBodyFinishedThenWriteMoreF	  s     ".11'7NHEE77""5)))+x'8'>GGG--//555r@   c                     |                      t          t                                          }|                     |t                    S )a$  
        If the request body producer with an unknown length tries to write
        after firing the L{Deferred} returned by its C{startProducing} method
        with a L{Failure}, the C{write} call raises an exception and does not
        write anything to the underlying transport.
        )r  r   r9   rT   )rR   rX   s     rA   9test_sendChunkedRequestBodyFinishedWithErrorThenWriteMorezFRequestTests.test_sendChunkedRequestBodyFinishedWithErrorThenWriteMoreW	  sD     AA&(())
 
 !!!%7888r@   c                    t          d          }t          ddt          |          }|                    | j                  }|                     | j        j        |           |                     | j        j                   |j	        
                    d           |                     | j                                        d           |                     | j        j                   |j                            t#          t%                                           |                     | j        j                   |                     | j        j        d           |                     |t$                    S )z
        If the L{Deferred} returned from the C{startProducing} method of the
        L{IBodyProducer} passed to L{Request} fires with a L{Failure}, the
        L{Deferred} returned from L{Request.writeTo} fails with that
        L{Failure}.
           r6  r7  rw  sQ   POST /bar HTTP/1.1
Connection: close
Content-Length: 5
Host: example.com

abN)r8  r+   rf   rv  rg   r  r4  r   rd  r3  r  rL   r   r   r  r   r  r   r9   rT   rx  s       rA   test_sendRequestBodyWithErrorz*RequestTests.test_sendRequestBodyWithErrorc	  s@    "!$$'7NHEE77 	T^4h???0111&&&N  ""	
 	
 	
 	5666!!'*<*>*>"?"?@@@ 	5666 	T^4d;;;!!-1CDDDr@   c           	         t          ddt          i           d          }|                     t          |j        | j                   |                     | j                                        d           t          ddt          dddgi          d          }|                     t          |j        | j                   |                     | j                                        d           dS )z
        L{Request.writeTo} raises L{BadHeaders} if there is not exactly one
        I{Host} header and writes nothing to the given transport.
        r   r   Nr@   s   HostrE   s   example.org)r+   r3   r   r   rv  rg   rL   r   )rR   r   s     rA   test_hostHeaderRequiredz$RequestTests.test_hostHeaderRequired	  s    
 &$T::*got~FFF--//555D'7^^,L"MNNPT
 
 	*got~FFF--//55555r@   c                    t          d          }t          ddt          |          }|                    | j                   |                     |j                   |                                 |                     |j                   dS )zc
        L{Request.stopWriting} calls its body producer's C{stopProducing}
        method.
        rm  r   r   N)	r8  r+   rf   rv  rg   r   ry  rz  r   rf  s      rA   test_stopWritingzRequestTests.test_stopWriting	  s|    
 "!$$&$AA''')***()))))r@   c                 >   t          j        | t                    }t          d          }d }||_        t          ddt          |          }|                    | j                   |	                                 | 
                    t          |                     t                              d           |                     dt          |                     |d         }|                     d|           |d         }|                     |j        t                     dS )	z
        If the body producer's C{stopProducing} method raises an exception,
        L{Request.stopWriting} logs it and does not re-raise it.
        rm  c                       t          d          NzstopProducing is bustedrG  r?   r@   rA   brokenStopProducingzBRequestTests.test_brokenStopProducing.<locals>.brokenStopProducing	  s    $%>???r@   r   r   rc   r   rI  N)r   rJ  r   r8  rE  r+   rf   rv  rg   rz  rL   rM   rM  r9   rK  r  rL  r   )rR   rN  r4  r  r   rO  r   s          rA   test_brokenStopProducingz%RequestTests.test_brokenStopProducing	  s
   
 +<TCUVV!!$$	@ 	@ 	@ "5&$AA'''T334FGGHH!LLL!S--...AmU+++- ag'9:::::r@   rp   )r;   r<   r=   r>   r  rP  rS  r\  ra  rg  rk  rn  rp  rs  ru  ry  r~  r  r  r  r  r  r  r  r  r  r  r  r  r?   r@   rA   rL  rL    s        + + +
 
 
	
 	
 	

 
 
"; ; ;$
 
 
B  .9 9 9:
 
 
*5 5 56 6 6B B B? ? ?BC C CC C C(M M M6  &
 
 
 
 
 
    "
9 
9 
9%E %E %EN6 6 6
* 
* 
*; ; ; ; ;r@   rL  c                   D    e Zd ZdZd Zd Zd ZddZd Zd Z	d	 Z
d
 ZdS )LengthEnforcingConsumerTestsz/
    Tests for L{LengthEnforcingConsumer}.
    c                     t                      | _        t          d          | _        t	                      | _        t          | j        | j        | j                  | _        d S )Nr<  )r   r  r8  r4  r   rg   r#   enforcerrq   s    rA   r  z"LengthEnforcingConsumerTests.setUp	  sK    jj&r**(**/M4>4;
 
r@   c                 T   | j                             d           |                     | j                                        d           | j                                         | j                             d           |                     | j                                        d           dS )z
        L{LengthEnforcingConsumer.write} calls the wrapped consumer's C{write}
        method with the bytes it is passed as long as there are fewer of them
        than the C{length} attribute indicates remain to be received.
        r>  s   defN)r  r  rL   rg   r   re  rq   s    rA   
test_writez'LengthEnforcingConsumerTests.test_write	  s     	F###--//888F###--//88888r@   c                     | j                             d           |                     t          | j         j                   dS )z
        L{LengthEnforcingConsumer._noMoreWritesExpected} raises
        L{WrongBodyLength} if it is called before the indicated number of bytes
        have been written.
        s	   xxxxxxxxxN)r  r  r   r'   _noMoreWritesExpectedrq   s    rA   test_finishedEarlyz/LengthEnforcingConsumerTests.test_finishedEarly	  s;     	H%%%/4=+NOOOOOr@   Fc                 \   | j                             d           |                     | j        j                   | j                             d           |                     | j        j                   |r| j                                          |                     | j        t                    S )aN  
        If it is called with a total number of bytes exceeding the indicated
        limit passed to L{LengthEnforcingConsumer.__init__},
        L{LengthEnforcingConsumer.write} fires the L{Deferred} with a
        L{Failure} wrapping a L{WrongBodyLength} and also calls the
        C{stopProducing} method of the producer.
        
   xxxxxxxxxx   x)
r  r  r   r4  ry  r   r  rT   r  r'   )rR   _unregisterAfters     rA   test_writeTooManyz.LengthEnforcingConsumerTests.test_writeTooMany	  s     	I&&&.///D!!!-... 	2M//111!!$+???r@   c                 4   | j                             d           | j                                          |                     | j        j                   |                     t          | j         j        d           |                     | j        j                   dS )z
        If L{LengthEnforcingConsumer.write} is called after
        L{LengthEnforcingConsumer._noMoreWritesExpected}, it calls the
        producer's C{stopProducing} method and raises L{ExcessWrite}.
        r  r  N)	r  r  r  r   r4  ry  r   r    r   rq   s    rA   test_writeAfterNoMoreExpectedz:LengthEnforcingConsumerTests.test_writeAfterNoMoreExpected	  s     	I&&&++---.///+t}':DAAA-.....r@   c                 ,    |                      d          S )z
        L{LengthEnforcingConsumer._noMoreWritesExpected} does nothing (in
        particular, it does not raise any exception) if called after too many
        bytes have been passed to C{write}.
        T)r  rq   s    rA   test_finishedLatez.LengthEnforcingConsumerTests.test_finishedLate	  s     %%d+++r@   c                     | j                             d           |                     | j                                         d           dS )z
        If L{LengthEnforcingConsumer._noMoreWritesExpected} is called after
        the correct number of bytes have been written it returns L{None}.
        r  N)r  r  r  r  rq   s    rA   test_finishedz*LengthEnforcingConsumerTests.test_finished
  sD    
 	I&&&T]@@BBDIIIIIr@   c                       fd}| j         _         fd}                                 }|                    |           |S )a8  
        If L{LengthEnforcingConsumer.write} calls the producer's
        C{stopProducing} because too many bytes were written and the
        C{stopProducing} method raises an exception, the exception is logged
        and the L{LengthEnforcingConsumer} still errbacks the finished
        L{Deferred}.
        c                  `    t                                j                   t          d          r  )r8  rE  r4  r9   rq   s   rA   r  zRLengthEnforcingConsumerTests.test_stopProducingRaises.<locals>.brokenStopProducing
  s(    ((777$%>???r@   c                 ~                         t                              t                              d           d S )Nrc   )rL   rM   rM  r9   r  s    rA   
cbFinishedzILengthEnforcingConsumerTests.test_stopProducingRaises.<locals>.cbFinished
  s6    S!7!78J!K!KLLaPPPPPr@   )r4  rE  r  rU   )rR   r  r  rX   s   `   rA   test_stopProducingRaisesz5LengthEnforcingConsumerTests.test_stopProducingRaises
  su    	@ 	@ 	@ 	@ 	@ ':#	Q 	Q 	Q 	Q 	Q ""$$	j!!!r@   N)F)r;   r<   r=   r>   r  r  r  r  r  r  r  r  r?   r@   rA   r  r  	  s         
 
 

9 
9 
9P P P@ @ @ @ 
/ 
/ 
/, , ,J J J    r@   r  c                   $    e Zd ZdZd Zd Zd ZdS )RequestBodyConsumerTestsz
    Tests for L{ChunkedEncoder} which sits between an L{ITransport} and a
    request/response body producer and chunked encodes everything written to
    it.
    c           	          |                      t          t          t          t	                                                     dS )zC
        L{ChunkedEncoder} instances provide L{IConsumer}.
        N)r   r   r   r   r   rq   s    rA   test_interfacez'RequestBodyConsumerTests.test_interface)
  s4     	Y?P?P0Q0QRRSSSSSr@   c                 \   t                      }t          |          }|                    d           |                     |                                d           |                                 |                    d           |                     |                                d           dS )z}
        L{ChunkedEncoder.write} writes to the transport the chunked encoded
        form of the bytes passed to it.
        r   r  s   xxxxxxxxxxxxxxxxs   10
xxxxxxxxxxxxxxxx
N)r   r   r  rL   r   re  )rR   rg   encoders      rA   r  z#RequestBodyConsumerTests.test_write/
  s    
 $%%	 ++f**O<<<i   **,KLLLLLr@   c                    t                      }t                      }t          |          }|                    |d           |                     |j        |           |                     |j                   |                                 |                     |j        d           | 	                    |
                                d           dS )a  
        L{ChunkedEncoder.registerProducer} registers the given streaming
        producer with its transport and L{ChunkedEncoder.unregisterProducer}
        writes a zero-length chunk to its transport and unregisters the
        transport's producer.
        TNs   0

)r   r   r   registerProducerr  r4  r   rd  unregisterProducerrL   r   )rR   rg   r4  r  s       rA   test_producerRegistrationz2RequestBodyConsumerTests.test_producerRegistration<
  s     $%%	88 ++  4000Y/:::	+,,,""$$$Y/666**L99999r@   N)r;   r<   r=   r>   r  r  r  r?   r@   rA   r  r  "
  sQ         T T TM M M: : : : :r@   r  c                   <    e Zd ZdZd Zd Zd Zd Zd Zd Z	d Z
d	S )
TransportProxyProducerTestszn
    Tests for L{TransportProxyProducer} which proxies the L{IPushProducer}
    interface of a transport.
    c                 p    |                      t          t          t          d                               dS )zO
        L{TransportProxyProducer} instances provide L{IPushProducer}.
        N)r   r   r   r&   rq   s    rA   r  z*TransportProxyProducerTests.test_interfaceT
  s/     	]4J44P4PQQRRRRRr@   c                     t                      }t          |          }|                     |j        |           |                                 |                     |j        d           dS )z~
        L{TransportProxyProducer.stopProxying} drops the reference to the
        wrapped L{IPushProducer} provider.
        N)r   r&   r  r  stopProxyingrR   rg   proxys      rA   %test_stopProxyingUnreferencesProducerzATransportProxyProducerTests.test_stopProxyingUnreferencesProducerZ
  sd    
 $%%	&y11U_i888U_d33333r@   c                    t                      }|                                 t          |          }|                     |j        d           |                                 |                     |j        d           |                                 |                                 |                                 |                     |j        d           dS )z
        L{TransportProxyProducer.resumeProducing} calls the wrapped
        transport's C{resumeProducing} method unless told to stop proxying.
        r  r   N)r   rG  r&   rL   r   rJ  r  r  s      rA   test_resumeProducingz0TransportProxyProducerTests.test_resumeProducinge
  s    
 $%%	  """&y110(;;;0+>>>  """ 	0(;;;;;r@   c                    t                      }t          |          }|                     |j        d           |                                 |                     |j        d           |                                 |                                 |                                 |                     |j        d           dS )z
        L{TransportProxyProducer.pauseProducing} calls the wrapped transport's
        C{pauseProducing} method unless told to stop proxying.
        r   r  N)r   r&   rL   r   rG  rJ  r  r  s      rA   test_pauseProducingz/TransportProxyProducerTests.test_pauseProducing{
  s    
 $%%	&y110+>>>0(;;;!!### 	0+>>>>>r@   c                    t                      }t          |          }|                     |j        d           |                                 |                     |j        d           t                      }t          |          }|                                 |                                 |                     |j        d           dS )z
        L{TransportProxyProducer.stopProducing} calls the wrapped transport's
        C{stopProducing} method unless told to stop proxying.
        r   ry  N)r   r&   rL   r   rE  r  r  s      rA   test_stopProducingz.TransportProxyProducerTests.test_stopProducing
  s    
 $%%	&y110+>>>0)<<<#%%	&y110+>>>>>r@   c                    t                      }t                      }|                    |           ||_        t	          |          }|                     |j                   |                     |j        d           |	                                 |                     |j        d           | 
                    |j                   dS )zs
        L{TransportProxyProducer.loseConnection} calls the wrapped transport's
        C{loseConnection}.
        r   N)r   r   r   r   r&   r   	connectedrL   r   loseConnectionr   rR   rg   r   r  s       rA    test_loseConnectionWhileProxyingz<TransportProxyProducerTests.test_loseConnectionWhileProxying
  s    
 566	'))	***%	&y11	+,,,0+>>> 	0+>>>,-----r@   c                 L   t                      }t                      }|                    |           ||_        t	          |          }|                                 |                     |j                   |                                 |                     |j                   dS )zm
        L{TransportProxyProducer.loseConnection} does nothing when the
        proxy is not active.
        N)	r   r   r   r   r&   r  r   r  r  r  s       rA   test_loseConnectionNotProxyingz:TransportProxyProducerTests.test_loseConnectionNotProxying
  s    
 566	'))	***%	&y11	+,,, 		+,,,,,r@   N)r;   r<   r=   r>   r  r  r  r  r  r  r  r?   r@   rA   r  r  N
  s         
S S S	4 	4 	4< < <,? ? ?*? ? ?(. . .*- - - - -r@   r  c                   l    e Zd ZdZd Zd Zd Zd Zd Zd Z	d Z
d	 Zd
 Zd Zd Zd Zd Zd Zd ZdS )ResponseTestsz 
    Tests for L{Response}.
    c                     t          t                                }|                     t          t          |                     dS )z=
        L{Response} instances provide L{IResponse}.
        N)rh   r   r   r   r5   rR   r   s     rA   test_verifyInterfacez"ResponseTests.test_verifyInterface
  s9     )):):;;Y99:::::r@   c                 r   g t                      } G fddt                    } |            }t          |          }|                    |           \  }|                                 |                     |j        d           |                                 |                     |j        d           dS )z
        The L{IProtocol} provider passed to L{Response.deliverBody} has its
        C{makeConnection} method called with an L{IPushProducer} provider
        hooked up to the response as an argument.
        c                       e Zd Z fdZdS )7ResponseTests.test_makeConnection.<locals>.SomeProtocolc                 2                         |           d S rp   r   )rR   r4  	producerss     rA   r   zFResponseTests.test_makeConnection.<locals>.SomeProtocol.makeConnection
  s      *****r@   Nr;   r<   r=   r   )r  s   rA   SomeProtocolr  
  s.        + + + + + + +r@   r  r  r   N)r   r   rh   r  rG  rL   r   rJ  )rR   rg   r  r3  r   theProducerr  s         @rA   test_makeConnectionz!ResponseTests.test_makeConnection
  s     	#%%		+ 	+ 	+ 	+ 	+ 	+ 	+8 	+ 	+ 	+  <>>(33X&&&!""$$$0(;;;##%%%0+>>>>>r@   c                    g  G fddt                     } |            }t          t                                }|                    |           |                    d           |                     dg           dS )z
        The L{IProtocol} provider passed to L{Response.deliverBody} has its
        C{dataReceived} method called with bytes received as part of the
        response body.
        c                       e Zd Z fdZdS )5ResponseTests.test_dataReceived.<locals>.ListConsumerc                 2                         |           d S rp   r   rR   r   r   s     rA   r   zBResponseTests.test_dataReceived.<locals>.ListConsumer.dataReceived
      T"""""r@   Nr;   r<   r=   r   r   s   rA   ListConsumerr  
  .        # # # # # # #r@   r  r   N)r   rh   r   r  r   rL   )rR   r  r3  r   r   s       @rA   test_dataReceivedzResponseTests.test_dataReceived
  s     	# 	# 	# 	# 	# 	# 	#8 	# 	# 	#  <>>():):;;X&&&""6***)))))r@   c                    g  G fddt                     } |            }t          t                                }|                    |           |                                 d                             t                     |                     t                    d           | 	                    |j
        d           dS )z
        The L{IProtocol} provider passed to L{Response.deliverBody} has its
        C{connectionLost} method called with a L{Failure} wrapping
        L{ResponseDone} when the response's C{_bodyDataFinished} method is
        called.
        c                       e Zd Z fdZdS )7ResponseTests.test_connectionLost.<locals>.ListConsumerc                 2                         |           d S rp   r   )rR   rO   losts     rA   r;  zFResponseTests.test_connectionLost.<locals>.ListConsumer.connectionLost  s    F#####r@   N)r;   r<   r=   r;  )r  s   rA   r  r  
  s.        $ $ $ $ $ $ $r@   r  r   rc   N)r   rh   r   r  r   rK   r/   rL   rM   r  _bodyProtocol)rR   r  r3  r   r  s       @rA   test_connectionLostz!ResponseTests.test_connectionLost  s     	$ 	$ 	$ 	$ 	$ 	$ 	$8 	$ 	$ 	$  <>>():):;;X&&&""$$$Q\"""TA&&& 	X3T:::::r@   c                    g  G fddt                     } |            }t          t                                }|                    d           |                    d           |                    |           |                    d           |                     g d           |                     |j        d           dS )z
        If data is delivered to the L{Response} before a protocol is registered
        with C{deliverBody}, that data is buffered until the protocol is
        registered and then is delivered.
        c                       e Zd Z fdZdS )8ResponseTests.test_bufferEarlyData.<locals>.ListConsumerc                 2                         |           d S rp   r   r  s     rA   r   zEResponseTests.test_bufferEarlyData.<locals>.ListConsumer.dataReceived#  r  r@   Nr  r  s   rA   r  r  "  r  r@   r  r   r   r   )r   r   r   N)r   rh   r   r   r  rL   r  _bodyBuffer)rR   r  r   r   r   s       @rA   test_bufferEarlyDataz"ResponseTests.test_bufferEarlyData  s     	# 	# 	# 	# 	# 	# 	#8 	# 	# 	#  <>>():):;;""6***""6***X&&&""6*** 8 8 8999 	X1488888r@   c                     t          t                                }|                    t                                 |                     t
          |j        t                                 dS )zb
        L{Response.deliverBody} raises L{RuntimeError} if called more than
        once.
        N)rh   r   r  r   r   r   r  s     rA    test_multipleStartProducingFailsz.ResponseTests.test_multipleStartProducingFails1  sT    
 )):):;;XZZ(((,(<hjjIIIIIr@   c                     t          t                                }|                    t                                 |                                 |                     t          |j        t                                 dS )zw
        L{Response.deliverBody} raises L{RuntimeError} if called after
        L{Response._bodyDataFinished}.
        N)rh   r   r  r   r   r   r   r  s     rA   %test_startProducingAfterFinishedFailsz3ResponseTests.test_startProducingAfterFinishedFails:  sf    
 )):):;;XZZ(((""$$$,(<hjjIIIIIr@   c                     t          t                                }|                                 |                     t          |j        d           dS )z
        L{Response._bodyDataReceived} raises L{RuntimeError} if called after
        L{Response._bodyDataFinished} but before L{Response.deliverBody}.
        r   N)rh   r   r   r   r   r   r  s     rA   'test_bodyDataReceivedAfterFinishedFailsz5ResponseTests.test_bodyDataReceivedAfterFinishedFailsD  sJ    
 )):):;;""$$$,(BFKKKKKr@   c                     t          t                                }|                                 |                    t	                                 |                     t          |j        d           dS )z
        L{Response._bodyDataReceived} raises L{RuntimeError} if called after
        L{Response._bodyDataFinished} and after L{Response.deliverBody}.
        r   N)rh   r   r   r  r   r   r   r   r  s     rA   'test_bodyDataReceivedAfterDeliveryFailsz5ResponseTests.test_bodyDataReceivedAfterDeliveryFailsM  sb    
 )):):;;""$$$XZZ(((,(BFKKKKKr@   c                     t          t                                }|                                 |                     t          |j                   dS )zh
        L{Response._bodyDataFinished} raises L{RuntimeError} if called more
        than once.
        N)rh   r   r   r   r   r  s     rA   'test_bodyDataFinishedAfterFinishedFailsz5ResponseTests.test_bodyDataFinishedAfterFinishedFailsW  sH    
 )):):;;""$$$,(BCCCCCr@   c                     t          t                                }|                                 |                    t	                                 |                     t          |j                   dS )z{
        L{Response._bodyDataFinished} raises L{RuntimeError} if called after
        the body has been delivered.
        N)rh   r   r   r  r   r   r   r  s     rA   'test_bodyDataFinishedAfterDeliveryFailsz5ResponseTests.test_bodyDataFinishedAfterDeliveryFails`  s`    
 )):):;;""$$$XZZ(((,(BCCCCCr@   c                 p   g  G fddt                     }t                      }|                                  |            }t          |          }|                     |j        d           |                    |           |                     dg           |                     |j        d           dS )z
        L{Response.deliverBody} resumes the HTTP connection's transport
        after passing it to the consumer's C{makeConnection} method.
        c                       e Zd Z fdZdS )9ResponseTests.test_transportResumed.<locals>.ListConsumerc                 <                         |j                   d S rp   )r   r   )rR   rg   transportStates     rA   r   zHResponseTests.test_transportResumed.<locals>.ListConsumer.makeConnectionr  s     %%i&=>>>>>r@   Nr  )r  s   rA   r  r  q  s.        ? ? ? ? ? ? ?r@   r  r  r   N)r   r   rG  rh   rL   r   r  )rR   r  rg   r   r   r  s        @rA   test_transportResumedz#ResponseTests.test_transportResumedj  s    
 	? 	? 	? 	? 	? 	? 	?8 	? 	? 	? $%%	  """<>>(330(;;;X&&&(4440+>>>>>r@   c                 v   t                      }t          |          }|                    d           |                    d           |                                 t	                      }|                    |           |                     |j        d           |j        	                    t                     dS )z
        If the entire body is delivered to the L{Response} before the
        response's C{deliverBody} method is called, the protocol passed to
        C{deliverBody} is immediately given the body data and then
        disconnected.
        r   r   r  N)r   rh   r   r   r   r  rL   r   r  rK   r/   rR   rg   r   r   s       rA   )test_bodyDataFinishedBeforeStartProducingz7ResponseTests.test_bodyDataFinishedBeforeStartProducing~  s     $%%	(33""6***""6***""$$$'))X&&&	222""<00000r@   c                 V   t                      }t          |          }t                      }|                    |           |                     |j        d           |                    t          t                                           |j	        
                    t                     dS )a	  
        The L{Failure} passed to L{Response._bodyDataFinished} when the response
        is in the I{connected} state is passed to the C{connectionLost} method
        of the L{IProtocol} provider passed to the L{Response}'s
        C{deliverBody} method.
        	CONNECTEDN)r   rh   r   r  rL   r{   r   r   r9   r  rK   r  s       rA   #test_finishedWithErrorWhenConnectedz1ResponseTests.test_finishedWithErrorWhenConnected  s     $%%	(33'))X&&& 	+666""7+=+?+?#@#@AAA""#566666r@   c                 V   t                      }t          |          }|                     |j        d           |                    t          t                                           t                      }|                    |           |j	        
                    t                     dS )a  
        The L{Failure} passed to L{Response._bodyDataFinished} when the response
        is in the I{initial} state is passed to the C{connectionLost} method of
        the L{IProtocol} provider passed to the L{Response}'s C{deliverBody}
        method.
        INITIALN)r   rh   rL   r{   r   r   r9   r   r  r  rK   r  s       rA   !test_finishedWithErrorWhenInitialz/ResponseTests.test_finishedWithErrorWhenInitial  s     $%%	(33 	)444""7+=+?+?#@#@AAA'))X&&&""#566666r@   N)r;   r<   r=   r>   r  r  r  r  r  r  r  r
  r  r  r  r  r  r  r  r?   r@   rA   r  r  
  s        ; ; ;? ? ?,* * *&; ; ;29 9 9.J J JJ J JL L LL L LD D DD D D? ? ?(1 1 1$7 7 7&7 7 7 7 7r@   r  N)_r>   typingr   zope.interfacer   zope.interface.verifyr   twisted.internet.deferr   r   r   r	   twisted.internet.errorr
   r   twisted.internet.interfacesr   r   twisted.internet.protocolr   twisted.internet.testingr   r   r   r   twisted.loggerr   twisted.protocols.basicr   twisted.python.failurer   twisted.trial.unittestr   twisted.web._newclientr   r   r   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   twisted.web.clientr)   r*   r+   r,   r-   r.   r/   r0   r1   twisted.web.httpr2   twisted.web.http_headersr3   twisted.web.iwebr4   r5   twisted.web.test.requesthelperr6   r7   	Exceptionr9   rC   rf   rY   r\   r^   r`   rh   rj   r   r   r   r   rs  r  r  r8  rL  r  r  r  r  r?   r@   rA   <module>r3     sL          & & & & & & . . . . . . J J J J J J J J J J J J A A A A A A A A @ @ @ @ @ @ @ @ . . . . . .            . - - - - - 0 0 0 0 0 0 * * * * * * + + + + + +                                       (
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 ' & & & & & , , , , , , 5 5 5 5 5 5 5 5                  	    'N#3455% % %PT T T    L L L6 6 6 6 6( 6 6 6BSM SM SM SM SM SM SM SMl    +;X       .>   h
. h
. h
. h
. h
.H h
. h
. h
.V       0       fE fE fE fE fE fE fE fER ]               Fq; q; q; q; q;8 q; q; q;hb b b b b8 b b bJ): ): ): ): ):x ): ): ):X{- {- {- {- {-( {- {- {-|h7 h7 h7 h7 h7H h7 h7 h7 h7 h7r@   