
    Vh                       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^y;)<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y)ArbitraryExceptionze
    A unique, arbitrary exception type which L{twisted.web._newclient} knows
    nothing about.
    N__name__
__module____qualname____doc__     O/home/dcms/DCMS/lib/python3.12/site-packages/twisted/web/test/test_newclient.pyr9   r9   C   s    r@   r9   c                       e Zd ZdZy)AnotherArbitraryExceptionzI
    Similar to L{ArbitraryException} but with a different identity.
    Nr:   r?   r@   rA   rC   rC   J   s    r@   rC      host   example.comc                 \      fd} j                  ||      }|j                  |       |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 ]  \  }}|j                  |        j                  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   sl    [9 	LFDKK	3;;-yQ7	

 
r@   )assertFailureaddCallback)rR   deferredmainTyperQ   rS   ds   `  `  rA   assertWrapperExceptionTypesrY   U   s-    2 	8X.AMM(Hr@   c                 &    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Sr@   c                 &    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                 &    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                 (    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Kr@   c                       e Zd ZdZd Zy)MakeStatefulDispatcherTestsz.
    Tests for L{makeStatefulDispatcher}.
    c                     G d d      } |       }| j                  |j                         d       d|_        | j                  |j                         d       d|_        | j                  t        |j                         y)z
        A method defined with L{makeStatefulDispatcher} invokes a second
        method based on the current state of the object.
        c                   4    e Zd ZdZd Z ede      Zd Zd Zy)CMakeStatefulDispatcherTests.test_functionCalledByState.<locals>.FooAc                      y Nr?   rR   s    rA   barzGMakeStatefulDispatcherTests.test_functionCalledByState.<locals>.Foo.bar   s    r@   quuxc                      y)Nar?   rq   s    rA   _quux_AzKMakeStatefulDispatcherTests.test_functionCalledByState.<locals>.Foo._quux_A       r@   c                      y)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      s$    F )5Cr@   r|   ru   Bry   CN)rL   rr   r{   assertRaisesRuntimeError)rR   r|   statefuls      rA   test_functionCalledByStatez6MakeStatefulDispatcherTests.test_functionCalledByState   sc    	 	 5--,5r@   N)r;   r<   r=   r>   r   r?   r@   rA   rj   rj      s    6r@   rj   c                   b    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y)_HTTPParserTestszt
    Base test class for L{HTTPParser} which is responsible for the bulk of
    the task of parsing HTTP bytes.
    Nsepc                 R   g }t               }|j                  |_        |j                  t	                      | j                  |j                  t               |j                  d| j                  z          | j                  |dg       | j                  |j                  t               y)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200488;<"4!560r@   c                     i }t               }|j                  |_        |j                  t	                      |j                  d| j                  z          ||fS )Nr   )r"   __setitem__headerReceivedr   r   r   r   rR   headerr   s      rA   _headerTestSetupz!_HTTPParserTests._headerTestSetup   sP    <"("4"4 120488;<xr@   c                    | j                         \  }}|j                  d| j                  z          |j                  | j                         | j                  |ddi       | j                  |j                  t
               y)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   sk    
  002lTXX56 	dhh'(F!34.r@   c                 |   | j                         \  }}|j                  d| j                  z          |j                  d| j                  z          |j                  d| j                  z          |j                  | j                         | j                  |ddi       | j                  |j                  t
               y)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mdhh67g01i$((23dhh'(,<!=>.r@   c                    | j                         \  }}| j                  j                  g d      }|j                  d|z          |j                  d|z          |j                  | j                         | j	                  |ddd       y)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   sw    
  002@Ai%/0i%/0dhh'Ff!EFr@   c                     g | j                         \  }fd}|_        j                  | j                         | j	                  t
        g       | j	                  j                  t               y)zg
        After the last header is received, L{HTTPParser} calls
        C{allHeadersReceived}.
        c                  R     j                  j                         t        _        y rp   )r   r   r   )calledr   s   rA   allHeadersReceivedzD_HTTPParserTests.test_allHeadersCallback.<locals>.allHeadersReceived  s    MM(..)#HNr@   N)r   r   r   r   rL   r   r   r   )rR   r   r   r   r   s      @@rA   test_allHeadersCallbackz(_HTTPParserTests.test_allHeadersCallback  sd    
 002	$ '9#dhh'&*0r@   c                     | j                         \  }}|j                  | j                         | j                  |i        | j                  |j                  t
               y)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  sM    
  002dhh'$.r@   c                    t               }|j                  t                      |j                  d| j                  z          |j                  d| j                  z          |j                  d| j                  z          |j                  | j                         dddgfg}| j                  |t        |j                  j                                      y)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20488;<mdhh67mdhh67dhh'/014(8(8(I(I(K#LMr@   c                     t               }g d}|D ]'  }| j                  |j                  |      d|d       ) | j                  |j                  d      d       y)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  sh     <	
 & 	FOO226:"%	 	..w74	
r@   c                     t               }|j                  t                      |j                  t	                      | j                  t        |j                  t	                      y)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  sF    
 < 12!!&(+,(A(A68Lr@   )r;   r<   r=   r>   r   r   bytes__annotations__r   r   r   r   r   r   r   r   r   r   r?   r@   rA   r   r      sL    
  C%1 //
G1"/N
<Mr@   r   c                       e Zd ZdZdZy)$HTTPParserRFCComplaintDelimeterTestsz<
    L{_HTTPParserTests} using standard CR LF newlines.
       
Nr;   r<   r=   r>   r   r?   r@   rA   r   r   Z  s     Cr@   r   c                       e Zd ZdZdZy)'HTTPParserNonRFCComplaintDelimeterTestsz5
    L{_HTTPParserTests} using bare LF newlines.
       
Nr   r?   r@   rA   r   r   b  s     Cr@   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%y$)%HTTPClientParserTestszd
    Tests for L{HTTPClientParser} which is responsible for parsing HTTP
    response messages.
    c                 ^    t        dd      }| j                  |j                  d      d       y)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Or@   c                      t        dd      }t        |j                   fd} |d        |d        |d        |d        |d        |d       y)	zr
        L{HTTPClientParser.parseVersion} raises L{ValueError} when passed an
        unparsable version.
        Nc                 d    j                  |       }j                  |j                  |        y rp   )r   rL   data)sexcefrR   s     rA   checkParsingz@HTTPClientParserTests.test_parseBadVersion.<locals>.checkParsing  s+    ##Aq!,CSXXq)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  sX    
 $D$/!!	* 	V^$WYZ \"r@   c                 x   t        ddt        d      }t        |d      }|j                  t	                      |j                  d       | j                  |j                  j                  d       | j                  |j                  j                  d       | j                  |j                  j                  d       y)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 1245**22OD**//5**1159r@   c                 x   t        ddt        d      }t        |d      }|j                  t	                      |j                  d       | j                  |j                  j                  d       | j                  |j                  j                  d       | j                  |j                  j                  d       y)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 1212**22OD**//5**1137r@   c                 L     t        dd       fd} |d        |d       y)z
        L{HTTPClientParser.statusReceived} raises L{ParseError} if it is called
        with a status line which cannot be parsed.
        Nc                     j                  t        j                  |       }j                  |j                  |        y rp   )r   r$   r   rL   r   )r   r   r   rR   s     rA   r   zBHTTPClientParserTests.test_badResponseStatus.<locals>.checkParsing  s1    ##J0G0GKCSXXq)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                  |       |j                  |j                  _        	fd|j                  _	        |j                  |       | j                  |j                  d       | j                  |j                  t               | j                  |g        | j                  |dg       | j                  	dg       | j                  |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                  &     j                  d      S NTr   )bodyDataFinisheds   rA   <lambda>z3HTTPClientParserTests._noBodyTest.<locals>.<lambda>  s    6F6M6Md6S 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  s    #GX__="("4"4#%		* 	f%.2kk+.S+h'00+>.r"C5))D62**1115r@   c                 ~    t        ddt        d      }d}d}| j                  |||      }| j                  |ddi       y)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  sH     '4>'4!!'68<"3U!;<r@   c                 V    t        ddt        d      }d}d}| j                  |||       y)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  s0    
 &$=/&(3r@   c                 V    t        ddt        d      }d}d}| j                  |||       y)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  s0    
 &$=1&(3r@   c                    t        t        ddt        d      d       }|j                  t	                      |j                  d       |j                  d       |j                  d       | j                  |j                  t        i              | j                  |j                  j                  t        dd	gi             | j                  |j                  j                  t               y)
zq
        The response headers are added to the response object's C{headers}
        L{Headers} instance.
        r   r   Nc                      y rp   r?   rests    rA   r   z<HTTPClientParserTests.test_responseHeaders.<locals>.<lambda>      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.$79J
 	 1245/0g&--wr{;**22GXx<P4QRX..55~Fr@   c                    t        t        ddt        d      d       }|j                  t	                      |j                  d       |j                  d       |j                  d       |j                  d       | j                  |j                  t        i              | j                  |j                  j                  t        d	d
gi             | j                  |j                  j                  t               y)z
        The multi-line response headers are folded and added to the response
        object's C{headers} L{Headers} instance.
        r   r   Nc                      y 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.$79J
 	 124534l+g&--wr{;%%w/L'M	
 	X..55~Fr@   c                    t        t        ddt        d      d       }|j                  t	                      |j                  d       |j                  d       |j                  d       |j                  d       | j                  |j                  j                  t        i              | j                  |j                  t        d	gd
gd             | j                  |j                  j                  d       y)zv
        The connection control headers are added to the parser's C{connHeaders}
        L{Headers} instance.
        r   r   Nc                      y 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.$79J
 	 12458967g&**22GBK@  (LM	
 	**1137r@   c                    t        t        ddt        d      d       }|j                  t	                      |j                  d       |j                  d       |j                  d       | j                  |j                  j                  t        dd	gi             | j                  |j                  t        i              | j                  |j                  j                  d
       y)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                      y rp   r?   r  s    rA   r   zRHTTPClientParserTests.test_headResponseContentLengthEntityHeader.<locals>.<lambda>=  r  r@   r   r  r   r   r  r   r  r   s     rA   *test_headResponseContentLengthEntityHeaderz@HTTPClientParserTests.test_headResponseContentLengthEntityHeader7  s    
 $GT>48:K
 	 124589g&%%w0AF8/L'M	
 	--wr{;**1115r@   c                    g }t        t        ddt        d      |j                        }t	               }|j                  |       |j                  d       g }|j                  |j                  _        |j                  d       |j                  d       | j                  |j                  d       | j                  |j                  t               |j                  d       | j                  |dg       | j                  |j                  t               |j                  d	       | j                  |dd	g       | j                  |j                  t               | j                  |d
g       y)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  s+    #FD.$7
 $%		*45.2kk+78g& 	00(;.h'z*.h'(34.C5)r@   c                    g }t        t        ddt        d      |j                        }|j	                  t                      |j                  d       g }|j                  |j                  _        |j                  d       |j                  d       | j                  |j                  t               | j                  |g        | j                  |dg       | j                  |j                  j                  d       y)	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
 	 1245.2kk+67g&.r"C5)**1115r@   c                     t        t        ddt        d      d      }|j                  t	                      | j                  t        |j                  d       y)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.$$OQUV 12!!	
r@   c                    t        t        ddt        d      d      }|j                  t	                      |j                  d       | j                  |j                  j                  d       | j                  |j                  t               y)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  sr     $GFD.$$OQUV 12	
 	**1115.r@   c                     t        t        ddt        d      d      }|j                  t	                      | j                  t        |j                  d       y)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.$$OQUV 12!!F	
r@   c                    t        t        ddt        d      d      }|j                  t	                      |j                  d       | j                  |j                  j                  d       | j                  |j                  t               y)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  sp     $GFD.$$OQUV 12H	
 	**1115.r@   c                     t        t        ddt        d      d      }|j                  t	                      | j                  t        |j                  d       y)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.$$OQUV 12!!<	
r@   c                     t        t        ddt        d      d      }|j                  t	                      | j                  t        |j                  d       y)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                 R   g }t        t        ddt        d      |j                        }|j	                  t                      |j                  d       |j                  d       |j                  d       | j                  |j                  t               | j                  |dg       y)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
 	 124567;<.$=#>?r@   c                 R   g }t        t        ddt        d      |j                        }|j	                  t                      |j                  d       |j                  d       |j                  d       | j                  |j                  t               | j                  |dg       y)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(//
 	 124578;<.$=#>?r@   c                 x   g }t        t        ddt        d      |j                        }|j	                  t                      |j                  d       g }|j                  |j                  _        |j                  d       |j                  d       | j                  |g        | j                  |j                  j                  t               |j                  d       | j                  |dg       |j                  d	       | j                  |dd
g       |j                  d       | j                  |dg       y)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
 	 1245.2kk+?@g& 	r" 	X..55~F 	i(v&i(e}-
 	/0H:.r@   c                    g }t        t        ddt        d      |j                        }t	               }|j                  |       |j                  d       g }|j                  |j                  _        |j                  d       |j                  d       |j                  d       | j                  |ddg       |j                  t        d             | j                  |d	g       y)
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
 $%		*45.2kk+g&f%f%/0/L MNC5)r@   c                 T   g }t        t        ddt        d      |j                        }t	               }|j                  |       |j                  d       g }|j                  |j                  _        |j                  d       | j                  |dg       | j                  |dg       y)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
 $%		*45.2kk+	
 	x(C5)r@   c                     t               }t        t        ddt        d      d      }|j	                  |       |j
                  }|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_  si     $%	#GFD.$$OQUV	*#55(:(< =>#D*:=O<PQQr@   c                    t        j                  | t              }t               }t	        t        ddt        d      d      }|j                  |       g }|j                  j                  |j                         |j                  d       |d   }d	d}||_        |j                  d       | j                  dt        |             |d   }|d   }| j!                  |j"                  t$               | j'                  t$               y)
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#%	#GFD.$$OQUV	*""..x?UVA;	' &:"%!S-.A- agg'9:12r@   c                     t        t        ddt        d      d       }|j                  }|j	                  t                      |j                  t                      | j                  |t              S )z
        If no response at all was received and the connection is lost, the
        resulting error is L{ResponseNeverReceived}.
        r   r   Nc                      y 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  sb    
 $GT>48:J
 && 12 01!!!%:;;r@   c                 B   t        t        ddt        d      d       }|j                  }|j	                  t                      |j                  d       |j                  t                      | j                  |t              j                  | 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                      y 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:J
 && 12d# 01!!!^4@@!!>
 	
r@   c                 8   d}t        t        ddt        d      d       }|j                  t	                      |j                  |       | j                  t        |dd      du        | j                  |j                  t               | j                  t        t        |j                  j                                     d       | j                  t        t        |j                  j                                     d       | j                  |j                          y)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                      y rp   r?   rS  s    rA   r   zCHTTPClientParserTests.test_1XXResponseIsSwallowed.<locals>.<lambda>  r  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.$79I
 	 12/0 	*d;tCD0T("2"2"C"C"EFGKT("6"6"G"G"IJKQO223r@   c                    d}d}t        t        ddt        d      d       }|j                  t	                      |j                  ||z          | j                  |j                  j                  d       | j                  |j                  j                  t        i              | j                  |j                  t        dd	gi             | j                  |j                  j                  d
       y)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                      y 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   r`  following200Responser   s       rA   -test_1XXFollowedByFinalResponseOnlyEmitsFinalzCHTTPClientParserTests.test_1XXFollowedByFinalResponseOnlyEmitsFinal  s     	  Y#FD.$79I
 	 12/2FFG**//5**22GBK@--w8IF87T/UV**1137r@   c                    d}d}t        t        ddt        d      d       }|j                  t	                      |j                  ||z   |z   |z          | j                  |j                  j                  d       | j                  |j                  j                  t        i              | j                  |j                  t        dd	gi             | j                  |j                  j                  d
       y)zp
        It is acceptable for multiple 1XX responses to come through, all of
        which get ignored.
        r\  rc  r   r   Nc                      y rp   r?   rS  s    rA   r   zKHTTPClientParserTests.test_multiple1XXResponsesAreIgnored.<locals>.<lambda>  r  r@   rd   r   r  r  re  rf  s       rA   #test_multiple1XXResponsesAreIgnoredz9HTTPClientParserTests.test_multiple1XXResponsesAreIgnored  s     	  Y#FD.$79I
 	 12   ##	
 	**//5**22GBK@--w8IF87T/UV**1137r@   c                 ^   t        j                  | t              }d}t        t	        ddt
        d      d       }|j                  t                      |j                  |       | j                  dt        |             |d   }| j                  |d   d	       | j                  |d
   d       y)zF
        When a 1XX response is ignored, Twisted emits a log.
        r\  r   r   Nc                      y 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  r`  r   rO  s        rA    test_ignored1XXResponseCausesLogz6HTTPClientParserTests.test_ignored1XXResponseCausesLog  s     +<<TCUV 	 $FD.$79I
 	 12/0!S-.A%-/T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  ra  rh  rk  rp  r?   r@   rA   r   r   j  s    
P#,:8)&"H
=44G G&8(6$*>62
$/$
/ 

@"@"#/J*0*<R3:<
$44828<.r@   r   c                   (    e Zd ZdZdZdZdZd Zd Zy)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                 8    t               | _        | j                  S rp   )r   r   rR   rg   s     rA   writeTozSlowRequest.writeTo%  s     
}}r@   c                     d| _         y r   stoppedrq   s    rA   stopWritingzSlowRequest.stopWriting)  	    r@   N)	r;   r<   r=   r>   methodrx  
persistentru  ry  r?   r@   rA   rr  rr    s"    	 FGJr@   rr  c                       e Zd ZdZdZd Zy)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	   rt  s     rA   ru  zSimpleRequest.writeTo7  s    &t}r@   N)r;   r<   r=   r>   r|  ru  r?   r@   rA   r~  r~  -  s     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&y)'HTTP11ClientProtocolTestsz]
    Tests for the HTTP 1.1 client protocol implementation,
    L{HTTP11ClientProtocol}.
    c                     t               | _        t               | _        | j                  j	                  | j                         y)zR
        Create an L{HTTP11ClientProtocol} connected to a fake transport.
        N)r   rg   r)   r   r   rq   s    rA   setUpzHTTP11ClientProtocolTests.setUpB  s.     )*,.$$T^^4r@   c                     | j                   j                  t                      | j                  | j                  j                         d       y)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  s5    
 	mo.--/?r@   c                       j                   j                  t                       fd} j                   j                   j                  t	                     t
              }|j                  |       |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                 Z    j                  j                  j                         d       y Nr@   rL   rg   r   ignoredrR   s    rA   	cbNotSentz?HTTP11ClientProtocolTests.test_secondRequest.<locals>.cbNotSentZ       T^^113S9r@   )r   r   rr  rT   r~  r%   rU   rR   r  rX   s   `  rA   test_secondRequestz,HTTP11ClientProtocolTests.test_secondRequestR  sT     	km,	: t}}44]_E~V	i r@   c                       j                   j                  t        t        d                    fd} j	                   j                   j                  t                     t              }|j                  |       |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                 Z    j                  j                  j                         d       y 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%MN	: t}}44]_E~V	i r@   c                       G d d      } j                   j                   |             } fd}t         |t        g      }|j	                  |       |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y)CHTTP11ClientProtocolTests.test_failedWriteTo.<locals>.BrokenRequestFc                 (    t        t                     S rp   )r   r9   rt  s     rA   ru  zKHTTP11ClientProtocolTests.test_failedWriteTo.<locals>.BrokenRequest.writeTo{  s    .011r@   Nr;   r<   r=   r|  ru  r?   r@   rA   BrokenRequestr  x  s    J2r@   r  c                     j                  j                  j                         j                  j	                  t        t        d                   y )Nzyou asked for it)r   rg   disconnectingr   r;  r   r
   r  s    rA   rS   z>HTTP11ClientProtocolTests.test_failedWriteTo.<locals>.cbFailed  s8    OODNN889 MM((@R1S)TUr@   )r   r   r^   r9   rU   )rR   r  rX   rS   s   `   rA   test_failedWriteToz,HTTP11ClientProtocolTests.test_failedWriteTop  sP    	2 	2 MM!!-/2	V *$4F3GH	hr@   c                 z     G d d      }| j                   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y)MHTTP11ClientProtocolTests.test_synchronousWriteToError.<locals>.BrokenRequestFc                     t               rp   rG  rt  s     rA   ru  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  s7    	+ 	+ MM!!-/2,T17I6JKKr@   Nc                 D   t               }| j                  j                  |      }t        | |t        g      }| j                  |j                         | j                  j                  t        t	                            | j                  |j                         |dk(  r|j                  j                  d       |S |dk(  r^|j                  j                  t        t                            | j                  t              }| j                  t!        |      d       |S 	 |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   )rr  r   r   r`   r9   r   rx  r;  r   r   r   r  r  rC   rM  rL   rM   )rR   moder   rX   errorss        rA   *test_connectionLostDuringRequestGenerationzDHTTP11ClientProtocolTests.test_connectionLostDuringRequestGeneration  s     -MM!!'*+D!6H5IJ 	)$$W-?-A%BC 	(:%%d+  Y$$W-F-H%IJ++,EFFS[!,  r@   c                 $    | j                  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Jr@   c                 $    | j                  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Ir@   c                      t        j                   t               fd} j                  d      j	                  |      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                     j                  dt                     d   }j                  d|       j                  |d   d       j                  |d   d       y )Nrc   r   rI  rn  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  sa    a[!12NEMM-/l#/
 U7^->?r@   r  )r   rJ  r   r  rU   )rR   r  rN  s   ` @rA   Etest_errorMessageOnConnectionLostBeforeGenerationFailedDoesNotConfusez_HTTP11ClientProtocolTests.test_errorMessageOnConnectionLostBeforeGenerationFailedDoesNotConfuse  sA     +<<TCUV		@ >>yIUU
 	
r@   c                       j                   j                  t        ddt        d            } fd}|j	                  |        j                   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                  | j                  d       j                  | j                  t                      j	                  j
                  j                         j                  j                  j                  d       y )Nrd   	QUIESCENT)	rL   r   r   r3   r   rg   r  r   r   )r   rR   s    rA   	cbRequestzIHTTP11ClientProtocolTests.test_receiveSimplestResponse.<locals>.cbRequest  s_    X]]C0X--wy9OODNN889T]]0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  sU     MM!!'&$"MN	? 	
i ""	
 r@   c                       j                   j                  t        ddt        d            } fd}|j	                  |        j                   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                 \    t        dddgi      }j                  | j                  |       y )Nr  r   r   )r3   rL   r   )r   r   rR   s     rA   r  zHHTTP11ClientProtocolTests.test_receiveResponseHeaders.<locals>.cbRequest  s-    66*:;<HX--x8r@   s+   HTTP/1.1 200 OK
X-Foo: bar
X-Foo: baz

r  r  s   `  rA   test_receiveResponseHeadersz5HTTP11ClientProtocolTests.test_receiveResponseHeaders  sS     MM!!'&$"MN	9 	
i ""N	
 r@   c                 ,    g t               t        j                        j                         t	               j                        }j                  d        fd}|j                  |        fd}|j                  |       |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                         j	                  j
                  d       j                  j                         j	                  g        |j                   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>*      1668J r@   )	r   r   closedDeferreddeliverBodyrL   r   r   r  rU   )r   whenFinishedr  r   quiescentResultrR   rg   s   ` @rA   
cbResponsez]HTTP11ClientProtocolTests.test_receiveResponseBeforeRequestGenerationDone.<locals>.cbResponse#  sq    $&A.6j8L1+  #X^^-TUOOI334_b1++,JKKr@   c                 b   | \  }}j                  |j                  d       j                  |j                  d       j                  |j                  d       j                  |j                  t        ddgi             j                  |d       j                  j                  d        y )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X__e4X--w6(7K/LMT9- %%d+r@   )r   r)   r   r   rr  r   r   rU   )rR   rX   r  r  r   r  r   rg   s   `   @@@@rA   /test_receiveResponseBeforeRequestGenerationDonezIHTTP11ClientProtocolTests.test_receiveResponseBeforeRequestGenerationDone  s     #%	'(>(>?	*-W%	
	L 	
j!
	, 	
m$r@   c                    t               }t               }||_        |j                  |       dt        j
                  z  }|j                  t        ddt        d            }|j                  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	')%		*,111WVT>4HI!"%	
 $D!n-=>>r@   c                      t                j                  j                        } j                  j                  d       d }|j	                  |        fd}|j	                  |       |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}_         j                         |j	                   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  s:    $&A.6j8L1+  #++,JKKr@   c                     j                   j                  d        j                  j                  t	        t                            j                  j                  j                  d       y )Nr  )r   r  r   r;  r   r9   rL   r{   )r  r   rR   s    rA   r  zuHTTP11ClientProtocolTests.test_connectionLostAfterReceivingResponseBeforeRequestGenerationDone.<locals>.cbAllResponsen  sM    %%d+MM((1C1E)FGT]]113DEr@   )rr  r   r   r   rU   )rR   rX   r  r  r   s   `   @rA   Dtest_connectionLostAfterReceivingResponseBeforeRequestGenerationDonez^HTTP11ClientProtocolTests.test_connectionLostAfterReceivingResponseBeforeRequestGenerationDoneW  sd     -MM!!'*""	
	L 	
j!	F 	
m$r@   c                 &    t               t               x}_         j                  j	                  t        ddt        d            } j                  j                  d       g }|j                  |j                          j                  |g         j                  j                  d       |d   }|j                          j                  j                  d        j                  j                  d        fd	}|j                  |       |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                  j                  d       j                  j                  t               y )Nr  )rL   r   closedReasonrK   r/   )r  r   rR   s    rA   r  zIHTTP11ClientProtocolTests.test_receiveResponseBody.<locals>.cbAllResponse  s+    X]]I6!!&&|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  s     ()19;x.--//FD.$7
 	""A	
 ##FMM2$ 	""5)!9X&""6*""6*	5 	  /r@   c                 F   | j                   j                  t        ddt        d            }| j                   j	                  d       g }|j                  |j                         |d   }t               }|j                  |       | j                   j	                  d       | j                   j	                  d       | j                  |j                  d       | j                   j                  t        t        d	                   |j                  j                  t                y)
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
 	""#AB##FMM2!9')X&""6*""6*	2$$N#EFG	
 	""#45r@   c                 X   | j                   j                  t        ddt        d            }| j                   j	                  d       g }|j                  |j                         |d   }t               }|j                  |       | j                   j	                  d       | j                   j	                  d       | j                  |j                  d       | j                   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
 	""L	
 ##FMM2!9')X&""?3""?3	2$$W-?-A%BC#$x,,-0BI/N
 	
r@   c                       j                   j                  t        ddt        d            } j                   j	                  d       t         |t        g      } fd}|j                  |       |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                         j                  | j                  d   j
                  j                  d       j                  j                  t        t        d                   y )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  s_    OODNN889A$$))+K MM((1M)NOr@   )r   r   r+   rf   r   r\   r$   rU   )rR   r  rX   rS   s   `   rA    test_parserDataReceivedExceptionz:HTTP11ClientProtocolTests.test_parserDataReceivedException  se     --//FD.$7
 	""#GH E
	P 	
hr@   c                    | j                   j                  t        ddt        d            }| j                   j                  j
                  }| j                  |j                  | j
                         | j                   j                  t        t        d                   | j                  |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
 MM))33	Y00$..A''?P0Q(RSY00$7#D/N;KLLr@   c                    t               }t               }|j                  |       g }g }|j                         j	                  |j
                         |j                         j	                  |j
                         | j                  ||fg g f       | j                  |j                         |j                  t        t                            | j                  |dg       | j                  |dg       y)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     $%	')	*$$RYY/$$RYY/"bB8,	//0 	(8 9:dV$dV$r@   c                 F   t               }t               }|j                  |       |j                  t	        t                            g }|j                         j                  |j                         | j                  |dg       | j                  |j                  d       y)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 9:$$V]]3$(*;<r@   c                 L   t               }t               }|j                  |       |j                  t	        ddt
        d            }|j                          | j                  |j                         |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N	//0(8 9:#D&3D2EFFr@   c                     t        d      t               j                         j                  t	        ddt
        d            }j                  d       t                G fddt               fd	} fd
}|j                  |       t         t        t        g      }|j                  |      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y)QHTTP11ClientProtocolTests.test_abortAfterResponseHeaders.<locals>.BodyDestinationzl
            A body response protocol which immediately aborts the HTTP
            connection.
            c                 &    j                          y)z<
                Abort the HTTP connection.
                N)r  r   s    rA   connectionMadez`HTTP11ClientProtocolTests.test_abortAfterResponseHeaders.<locals>.BodyDestination.connectionMadeV  s      r@   c                 (    j                  |       y)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  s    
!+r@   r  c                     | j                                 j                  j                         j                  t	        t                            y)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3OOI334##GN,<$=>r@   c                 F    j                  | j                  t               y 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<  s     $D1	')	*!!'&$"MNUVZ
	+h 	+&	?	< 	;''*0)<
 ##J//r@   c           	      h    g  fd}t               }t        |      j                  |       j                  t	        ddt
        dd            }j                  d        j                  g        g }|j                  |j                         |d   }t               }t               |_        |j                  j                  fd	       |j                  |       j                  d
       |j                  j                  t                 j                  dg        j                  j"                  d        j                  j$                  d        j                  j&                  d        j                  j(                  d        j                  j*                  d       y)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                  |        j                  | j                  d       j                  |        y Nr  rL   r   r   r  r   r  rR   s    rA   r  zHHTTP11ClientProtocolTests.test_quiescentCallbackCalled.<locals>.callback  5    Q)QWWk2""1%r@   r   r   NTr|  s&   HTTP/1.1 200 OK
Content-length: 3

r   c                 &    j                  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  sx    	&
 $%	'1	*"**FD.$4H
 	UV 	"-##FMM2!9 ,-&.j###//?	
 	\*f%!!&&|4 	8_*EF 	))4022D91148114833T:r@   c           	          g  fd}t               }t        |      j                  |       j                  t	        ddt
        dd            }j                  d        j                  |      } j                  |j                  d        j                  t              d	        j                  |j                  d
       y)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                  |        j                  | j                  d       j                  |        y 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	*"**FD.$4H
 		
 ''8 	*:;
 	_-q1
 	00+>r@   c           	          g  fd}t               }t        |      j                  |       j                  t	        ddt
        dd            }|j                  j                         j                  d        j                  t              d        j                  d	           j                  d
   t               y)z
        The quiescentCallback is called before the request C{Deferred} fires,
        in cases where the response has no body.
        c                     j                  |        j                  | j                  d       j                  |        y 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	*"**FD.$4H
 	##O$:$:;UV_-q1_Q/:oa0(;r@   c           	         g }t               }t        |j                        }|j                  |       |j	                  t        ddt        dd            }|j                  d       g }|j                  |j                         |d   }t               }|j                  |       |j                  j                  t               | j                  |g        | j                  |j                          y)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
 		
 ##FMM2!9+-\*!!&&|4"-	//0r@   c           	         g }t               }t        |j                        }|j                  |       |j	                  t        ddt        dd            }|j                  d       g }|j                  |j                         |d   }t               }|j                  |       |j                  j                  t               | j                  |g        | j                  |j                          y)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
 	UV##FMM2!9+-\*!!&&|4"-	//0r@   c           	         d }t        j                  | t              }t               }t	        |      }|j                  |       |j                  t        ddt        dd            }|j                  d       g }|j                  |j                         |d   }t               }|j                  |       |j                  j                  t                | j#                  d	t%        |             |d   }	|	d
   }
| j'                  |
j(                  t*               | j-                  t*               | j/                  |j0                         y)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/  s   	& +<<TCUV#%	'1	*"**FD.$4H
 	UV##FMM2!9+-\*!!&&|4!S-.A- agg'8901	//0r@   c                    t               }t               }|j                  |       |j                  t	        ddt
        d            }|j                          | j                  |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  sr     $%	')	*!!'&$"MN	../*&/.1A
 	
r@   c                 *   t               }t               }|j                  |       |j                  t	        ddt
        d            }|j                  d       |j                          | j                  |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  sy     $%	')	*!!'&$"MN45	../#D&>2BCCr@   c                    t               }t               }|j                  |       t        |      ddifdfd}|_        |j                  t        ddt                    }j                  j                  d       |j                          | j                  |j                         | 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<   y )NTr-  r?   )rT  nonLocals    rA   r'  zJHTTP11ClientProtocolTests.assertCancelDuringBodyProduction.<locals>.cancel  s    $(H[!r@   c                 J    | _         t              _        j                  S rp   consumerr   r   )r2  r'  producers    rA   startProducingzRHTTP11ClientProtocolTests.assertCancelDuringBodyProduction.<locals>.startProducing  s$     (H ( 0H$$$r@      POST   /bars   xxxxx)r   r)   r   StringProducerr4  r   r+   rf   r2  r  r'  r   r(  r^   r   )	rR   producerLengthrg   r   r4  r  r'  r/  r3  s	         @@@rA    assertCancelDuringBodyProductionz:HTTP11ClientProtocolTests.assertCancelDuringBodyProductions  s     $%	')	*!.1'	)	%
 #1!!''7NH"UV)	../-.,T6N;KLLr@   c                 $    | j                  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.
        
   )r9  rq   s    rA   test_cancelDuringBodyProductionz9HTTP11ClientProtocolTests.test_cancelDuringBodyProduction  s     44R88r@   c                 ,    | j                  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.
        )r9  r   rq   s    rA   &test_cancelDuringChunkedBodyProductionz@HTTP11ClientProtocolTests.test_cancelDuringChunkedBodyProduction  s     44^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+  r9  r<  r>  r?   r@   rA   r  r  <  s    
5@4L @KJ
0.$0d?4@'R6:
@8M%*=G 80t7;r,?\<41>12!1F
"D M>9Er@   r  c                   2    e Zd ZdZdZd Zd Zd Zd Zd Z	y)	r7  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                     || _         y rp   )r   )rR   r   s     rA   __init__zStringProducer.__init__  s	    r@   c                 F    || _         t               | _        | j                  S rp   r1  )rR   r2  s     rA   r4  zStringProducer.startProducing  s      
}}r@   c                     d| _         y r   rw  rq   s    rA   stopProducingzStringProducer.stopProducing  rz  r@   c                      y rp   r?   rq   s    rA   pauseProducingzStringProducer.pauseProducing      r@   c                      y rp   r?   rq   s    rA   resumeProducingzStringProducer.resumeProducing  rG  r@   N)
r;   r<   r=   r>   rx  rA  r4  rD  rF  rI  r?   r@   rA   r7  r7    s'    
 G
r@   r7  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y)RequestTestsz
    Tests for L{Request}.
    c                 "    t               | _        y rp   )r   rg   rq   s    rA   r  zRequestTests.setUp  s    (*r@   c                     t        ddt        d      j                  | j                         | j	                  | j                  j                         d       y)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   ru  rg   rL   r   rq   s    rA   test_sendSimplestRequestz%RequestTests.test_sendSimplestRequest  sD    
 	nd3;;DNNKNN  "	
r@   c                     t        ddt        dd      }|j                  | j                         | j	                  | j                  j                         d       y)zO
        A pesistent request does not send 'Connection: close' header.
        r   r   NTr  s%   GET / HTTP/1.1
Host: example.com

rN  )rR   reqs     rA   "test_sendSimplestPersistentRequestz/RequestTests.test_sendSimplestPersistentRequest  sG     fdNDTJDNN#NN  "B	
r@   c                 v   t        ddgdgd      }t        dd|d      j                  | j                         | j                  j	                         j                  d      }| j                  |d	   d
       | j                  |dd ddg       |d	= |dd= |j                          | j                  |g d       y)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+   ru  rg   r   splitrL   sort)rR   r   liness      rA   test_sendRequestHeadersz$RequestTests.test_sendRequestHeaders  s    
 ff%5@PQR$/77G$$&,,W5q#78rsc3Z0!HeBCj

V	
r@   c                    t         D ]  }t        |gdgd      }t               }t        dd|d      j	                  |       |j                         j                  d      }| j                  |d   d       | j                  |d	d d
d
g       |d= |d	d= |j                  d       |j                  d       | j                  |dt        z   g        y)ze
        Linear whitespace in request header values is replaced with a
        single space.
        s   example.invalidrT  r   rU  Nr   r   rV  rW  r@   rX  s   Host: example.invalids   X-Foo: )
r6   r3   r   r+   ru  r   rY  rL   remover7   )rR   	componentr   rg   r[  s        rA   -test_sanitizeLinearWhitespaceInRequestHeadersz:RequestTests.test_sanitizeLinearWhitespaceInRequestHeaders  s    
 9 
	CI)@R?STUG')IFGWd3;;IFOO%++G4EU1X';<U23Z#s4a%*LL-.LL12UZ.%@$AB
	Cr@   c                    t        t              }t        ddt        |      }|j	                  | j
                         | j                  |j                  d       | j                  | j
                  j                  |       | j                  | j
                  j                         | j                  | j
                  j                         d       | j
                  j                          |j                  j                  d       |j                  j                  d       |j                   j#                  d       | j                  | j
                  j                  d       | j                  | j
                  j                         d       y)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.
        r5  r6  NsX   POST /bar HTTP/1.1
Connection: close
Transfer-Encoding: chunked
Host: example.com

s   xxxs   yyyyyyyyyyyyyyys!   3
xxx
f
yyyyyyyyyyyyyyy
0

)r7  r   r+   rf   ru  rg   assertNotIdenticalr2  r  r3  r   	streamingrL   r   clearr  r   r  rR   r3  r   s      rA   test_sendChunkedRequestBodyz(RequestTests.test_sendChunkedRequestBody  s     ".1'7NHE' 1 148T^^44h?001NN  "	
 	)	*""4(T^^44d;NN  "P	
r@   c                 R    t        t              }t        ddt        |      }|j	                   j
                        } j
                  j                          |j                  j                  t                       fd} j                  |t              }|j                  |       |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.
        r5  r6  c                     j                  j                  j                         d       j                  j                  j                  d        y r  )rL   rg   r   r  r3  r  s    rA   rS   zCRequestTests.test_sendChunkedRequestBodyWithError.<locals>.cbFailed<  s:    T^^113S9  !8!8$?r@   )r7  r   r+   rf   ru  rg   rd  r   r  r9   rT   rU   )rR   r3  r   writeDeferredrS   rX   s   `     rA   $test_sendChunkedRequestBodyWithErrorz1RequestTests.test_sendChunkedRequestBodyWithError-  s     ".1'7NHE7!!"4"67	@ }.@A	hr@   c                    t        d      }t        ddt        |      }|j                  | j                         | j                  |j                  d       | j                  | j                  j                  |       | j                  | j                  j                         | j                  | j                  j                         d       | j                  j                          |j                  j                  d       |j                  j!                  d       | j                  | j                  j                  d       | j                  | j                  j                         d       y)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.
           r5  r6  NsO   POST /bar HTTP/1.1
Connection: close
Content-Length: 3
Host: example.com

r>  )r7  r+   rf   ru  rg   rb  r2  r  r3  r   rc  rL   r   rd  r  r   r  re  s      rA   test_sendRequestBodyWithLengthz+RequestTests.test_sendRequestBodyWithLengthD  s    "!$'7NHE' 1 148T^^44h?001NN  "	
 	'""4(T^^44d;--/8r@   c                     t        |dt        d      }|j                  | j                         | j	                  | j                  j                         |dz          y)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

rN  )rR   r{  r   s      rA   _sendRequestEmptyBodyWithLengthz,RequestTests._sendRequestEmptyBodyWithLengtha  sO     &'>4@'NN  "  	
r@   c                 &    | j                  d       y)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ro  rq   s    rA   test_sendPUTRequestEmptyBodyz)RequestTests.test_sendPUTRequestEmptyBodyv  s     	,,V4r@   c                 &    | j                  d       y)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.
        r5  Nrq  rq   s    rA   test_sendPOSTRequestEmptyBodyz*RequestTests.test_sendPOSTRequestEmptyBody~  s     	,,W5r@   c                 V   t        d      }t        ddt        |      }|j                  | j                        }|j
                  j                  d       |j                  j                  d       | j                  | j                  j                  d       | j                  |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.
        rl  r5  r6     abN)r7  r+   rf   ru  rg   r2  r  r   r  r  r3  rT   r'   rR   r3  r   ri  s       rA   #test_sendRequestBodyWithTooFewBytesz0RequestTests.test_sendRequestBodyWithTooFewBytes  s     "!$'7NHE7&""4(T^^44d;!!-AAr@   c                     t        d      t        ddt              }|j                   j                        }j
                  j                  d        j                  j                         j
                  j                  d        j                  j                          j                   j                  j                  d        fd} j                  |t              }|j                  |       |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.
        rl  r5  r6  rv     cdNc                 H   j                  j                  j                         d       j                  j                          j	                  t
        j                  j                  d               j                  j                  j                         d       y )NsQ   POST /bar HTTP/1.1
Connection: close
Content-Length: 3
Host: example.com

abs   efr@   )rL   rg   r   rd  r   r    r2  r  )r   finisherr3  rR   s    rA   rS   zCRequestTests._sendRequestBodyWithTooManyBytesTest.<locals>.cbFailed  s     $$& NN  " k8+<+<+B+BEJ
 X T^^113S9r@   )r7  r+   rf   ru  rg   r2  r  r   rx  r   r  r3  rT   r'   rU   )rR   r|  r   ri  rS   rX   r3  s   ``    @rA   $_sendRequestBodyWithTooManyBytesTestz1RequestTests._sendRequestBodyWithTooManyBytesTest  s     "!$'7NHE7& 	))*& 	(() 	T^^44d;	:: }o>	hr@   c                 *    d }| j                  |      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                   j                  d        y rp   r   r  r3  s    rA   r|  zCRequestTests.test_sendRequestBodyWithTooManyBytes.<locals>.finisher      &&t,r@   )r}  rR   r|  s     rA   $test_sendRequestBodyWithTooManyBytesz1RequestTests.test_sendRequestBodyWithTooManyBytes  s    	- 88BBr@   c                 h     t        j                   t               fd} j                  |      S )r  c                 $   | j                   j                  t                      d   }j                  d|       |d   }j	                  |j
                  t               j                  t              }j                  t        |      d       y )Nr   rI  rc   )	r   r  r9   r  rL  r   rM  rL   rM   )r3  rO  r   r  rN  rR   s       rA   r|  zHRequestTests.test_sendRequestBodyErrorWithTooManyBytes.<locals>.finisher  sv    %%&8&:;NEMM-/m$A!!!''+=>++,>?FS[!,r@   )r   rJ  r   r}  )rR   r|  rN  s   ` @rA   )test_sendRequestBodyErrorWithTooManyBytesz6RequestTests.test_sendRequestBodyErrorWithTooManyBytes  s0     +<<TCUV	- 88BBr@   c                 F   t        j                  | t              }t        d      }t	        ddt
        |      }|j                  | j                         |j                  j                  }|j                  j                  d       |j                  j                  d       |j                  t                      |d   }| j                  d|       |d   }| j!                  |j"                  t               | j%                  t'        | j)                  t                    d       y)	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.
        rl  r5  r6  r>  Nr   rI  rc   )r   rJ  r   r7  r+   rf   ru  rg   r2  	_finishedr  r   r  r  r9   r  rL  r   rL   rM   rM  )rR   rN  r3  r   finishedConsumingrO  r   s          rA   *test_sendRequestBodyErrorWithConsumerErrorz7RequestTests.test_sendRequestBodyErrorWithConsumerError  s     +<<TCUV!!$'7NHE'$--77'""4(!!"4"67AmU+- agg'9:T334FGH!Lr@   c                    t        d      }t        ddt        |      }|j                  | j                        }|j
                  j                  d        ||       | j                  | j                  j                  d       | j                  j                          | j                  t        |j
                  j                  d       | j                  | j                  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.
        rl  r5  r6  rv  Nrz  r@   )r7  r+   rf   ru  rg   r2  r  r  r3  rd  r   r    rL   r   )rR   r|  r3  r   ri  s        rA   -_sendRequestBodyFinishedEarlyThenTooManyBytesz:RequestTests._sendRequestBodyFinishedEarlyThenTooManyBytes	  s     "!$'7NHE7&T^^44d;+x'8'8'>'>F--/5r@   c                 R    d }| j                  | j                  |      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                   j                  d        y 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
 	
r@   c                 R    d }| j                  | j                  |      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                 J    | j                   j                  t                      y 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_sendRequestBodyErroredEarlyThenTooManyBytes5	  s-    	< !!>>xH
 	
r@   Nc                    t        t              }t        ddt        |      }|j	                  | j
                        }|j                  j                  |       | j
                  j                          | j                  t        |j                  j                  d       | j                  | j
                  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.
        r5  r6  r   r@   )r7  r   r+   rf   ru  rg   r   r  rd  r   r    r2  r  rL   r   )rR   _withr3  r   ri  s        rA   0test_sendChunkedRequestBodyFinishedThenWriteMorez=RequestTests.test_sendChunkedRequestBodyFinishedThenWriteMoreE	  s     ".1'7NHE7""5)+x'8'8'>'>G--/5r@   c                 r    | j                  t        t                           }| j                  |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_sendChunkedRequestBodyFinishedWithErrorThenWriteMoreV	  s6     AA&()
 !!!%788r@   c                    t        d      }t        ddt        |      }|j                  | j                        }| j                  | j                  j                  |       | j                  | j                  j                         |j                  j                  d       | j                  | j                  j                         d       | j                  | j                  j                         |j                  j!                  t#        t%                            | j                  | j                  j                         | j                  | j                  j                  d       | j'                  |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}.
           r5  r6  rv  sQ   POST /bar HTTP/1.1
Connection: close
Content-Length: 5
Host: example.com

abN)r7  r+   rf   ru  rg   r  r3  r   rc  r2  r  rL   r   r   r  r   r  r   r9   rT   rw  s       rA   test_sendRequestBodyWithErrorz*RequestTests.test_sendRequestBodyWithErrorb	  s    "!$'7NHE7 	T^^44h?001&NN  "	
 	556!!'*<*>"?@ 	556 	T^^44d;!!-1CDDr@   c           	         t        ddt        i       d      }| j                  t        |j                  | j
                         | j                  | j
                  j                         d       t        ddt        dddgi      d      }| j                  t        |j                  | j
                         | j                  | j
                  j                         d       y)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   ru  rg   rL   r   )rR   r   s     rA   test_hostHeaderRequiredz$RequestTests.test_hostHeaderRequired	  s    
 &$T:*goot~~F--/5D'7^^,L"MNPT
 	*goot~~F--/5r@   c                     t        d      }t        ddt        |      }|j                  | j                         | j                  |j                         |j                          | j                  |j                         y)zc
        L{Request.stopWriting} calls its body producer's C{stopProducing}
        method.
        rl  r   r   N)	r7  r+   rf   ru  rg   r   rx  ry  r   re  s      rA   test_stopWritingzRequestTests.test_stopWriting	  s`    
 "!$&$A'))*(()r@   c                    t        j                  | t              }t        d      }d }||_        t        ddt        |      }|j                  | j                         |j                          | j                  t        | j                  t                    d       | j                  dt        |             |d   }| j                  d|       |d   }| j!                  |j"                  t               y)	z
        If the body producer's C{stopProducing} method raises an exception,
        L{Request.stopWriting} logs it and does not re-raise it.
        rl  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   r7  rD  r+   rf   ru  rg   ry  rL   rM   rM  r9   rK  r  rL  r   )rR   rN  r3  r  r   rO  r   s          rA   test_brokenStopProducingz%RequestTests.test_brokenStopProducing	  s    
 +<<TCUV!!$	@ "5&$A'T334FGH!L!S-.AmU+- agg'9:r@   rp   )r;   r<   r=   r>   r  rO  rR  r\  r`  rf  rj  rm  ro  rr  rt  rx  r}  r  r  r  r  r  r  r  r  r  r  r  r  r?   r@   rA   rK  rK    s    +
	

"C"
B.9:
*56B?BCC(M6&
 
 "
9%EN6
*;r@   rK  c                   B    e Zd ZdZd Zd Zd ZddZd Zd Z	d Z
d	 Zy
)LengthEnforcingConsumerTestsz/
    Tests for L{LengthEnforcingConsumer}.
    c                     t               | _        t        d      | _        t	               | _        t        | j                  | j
                  | j                        | _        y )Nr;  )r   r  r7  r3  r   rg   r#   enforcerrq   s    rA   r  z"LengthEnforcingConsumerTests.setUp	  s@    j&r*(*/MM4>>4;;
r@   c                 L   | j                   j                  d       | j                  | j                  j	                         d       | j                  j                          | j                   j                  d       | j                  | j                  j	                         d       y)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   rd  rq   s    rA   
test_writez'LengthEnforcingConsumerTests.test_write	  sr     	F#--/8F#--/8r@   c                     | j                   j                  d       | j                  t        | j                   j                         y)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	  s0     	H%/4==+N+NOr@   c                 z   | j                   j                  d       | j                  | j                  j                         | j                   j                  d       | j                  | j                  j                         |r| j                   j                          | 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   r3  rx  r   r  rT   r  r'   )rR   _unregisterAfters     rA   test_writeTooManyz.LengthEnforcingConsumerTests.test_writeTooMany	  s     	I&../D!--.MM//1!!$++??r@   c                 X   | j                   j                  d       | j                   j                          | j                  | j                  j
                         | j                  t        | j                   j                  d       | j                  | j                  j
                         y)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   r3  rx  r   r    r   rq   s    rA   test_writeAfterNoMoreExpectedz:LengthEnforcingConsumerTests.test_writeAfterNoMoreExpected	  sp     	I&++-../+t}}':':DA--.r@   c                 $    | j                  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                   j                  d       | j                  | j                   j                         d       y)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
  s3    
 	I&T]]@@BDIr@   c                       fd}| j                   _         fd} j                         }|j                  |       |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                  X    t         j                   j                         t        d      r  )r7  rD  r3  r9   rq   s   rA   r  zRLengthEnforcingConsumerTests.test_stopProducingRaises.<locals>.brokenStopProducing
  s!    ((7$%>??r@   c                 b    j                  t        j                  t                    d       y )Nrc   )rL   rM   rM  r9   r  s    rA   
cbFinishedzILengthEnforcingConsumerTests.test_stopProducingRaises.<locals>.cbFinished
  s$    S!7!78J!KLaPr@   )r3  rD  r  rU   )rR   r  r  rX   s   `   rA   test_stopProducingRaisesz5LengthEnforcingConsumerTests.test_stopProducingRaises

  s>    	@ ':#	Q ""$	j!r@   N)F)r;   r<   r=   r>   r  r  r  r  r  r  r  r  r?   r@   rA   r  r  	  s2    

9P@ 
/,Jr@   r  c                   "    e Zd ZdZd Zd Zd Zy)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           	      d    | j                  t        t        t        t	                                  y)zC
        L{ChunkedEncoder} instances provide L{IConsumer}.
        N)r   r   r   r   r   rq   s    rA   test_interfacez'RequestBodyConsumerTests.test_interface(
  s     	Y?P0QRSr@   c                    t               }t        |      }|j                  d       | j                  |j	                         d       |j                          |j                  d       | j                  |j	                         d       y)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   rd  )rR   rg   encoders      rA   r  z#RequestBodyConsumerTests.test_write.
  sg    
 $%	 +f*O<i *,KLr@   c                 l   t               }t               }t        |      }|j                  |d       | j	                  |j
                  |       | j                  |j                         |j                          | j	                  |j
                  d       | j                  |j                         d       y)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  r3  r   rc  unregisterProducerrL   r   )rR   rg   r3  r  s       rA   test_producerRegistrationz2RequestBodyConsumerTests.test_producerRegistration;
  s     $%	8 +  40Y//:	++,""$Y//6*L9r@   N)r;   r<   r=   r>   r  r  r  r?   r@   rA   r  r  !
  s    TM:r@   r  c                   :    e Zd ZdZd Zd Zd Zd Zd Zd Z	d Z
y	)
TransportProxyProducerTestszn
    Tests for L{TransportProxyProducer} which proxies the L{IPushProducer}
    interface of a transport.
    c                 T    | j                  t        t        t        d                   y)zO
        L{TransportProxyProducer} instances provide L{IPushProducer}.
        N)r   r   r   r&   rq   s    rA   r  z*TransportProxyProducerTests.test_interfaceS
  s     	]4J44PQRr@   c                     t               }t        |      }| j                  |j                  |       |j	                          | j                  |j                  d       y)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_stopProxyingUnreferencesProducerY
  sJ    
 $%	&y1U__i8U__d3r@   c                 v   t               }|j                          t        |      }| j                  |j                  d       |j                          | j                  |j                  d       |j                          |j                          |j                          | j                  |j                  d       y)z
        L{TransportProxyProducer.resumeProducing} calls the wrapped
        transport's C{resumeProducing} method unless told to stop proxying.
        r  r   N)r   rF  r&   rL   r   rI  r  r  s      rA   test_resumeProducingz0TransportProxyProducerTests.test_resumeProducingd
  s    
 $%	  "&y100(;00+>  " 	00(;r@   c                 V   t               }t        |      }| j                  |j                  d       |j	                          | j                  |j                  d       |j                          |j                          |j	                          | j                  |j                  d       y)z
        L{TransportProxyProducer.pauseProducing} calls the wrapped transport's
        C{pauseProducing} method unless told to stop proxying.
        r   r  N)r   r&   rL   r   rF  rI  r  r  s      rA   test_pauseProducingz/TransportProxyProducerTests.test_pauseProducingz
  s    
 $%	&y100+>00(;!!# 	00+>r@   c                 `   t               }t        |      }| j                  |j                  d       |j	                          | j                  |j                  d       t               }t        |      }|j                          |j	                          | j                  |j                  d       y)z
        L{TransportProxyProducer.stopProducing} calls the wrapped transport's
        C{stopProducing} method unless told to stop proxying.
        r   rx  N)r   r&   rL   r   rD  r  r  s      rA   test_stopProducingz.TransportProxyProducerTests.test_stopProducing
  s    
 $%	&y100+>00)<#%	&y100+>r@   c                 n   t               }t               }|j                  |       ||_        t	        |      }| j                  |j                         | j                  |j                  d       |j                          | j                  |j                  d       | j                  |j                         y)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	')	*%	&y1	++,00+> 	00+>,,-r@   c                    t               }t               }|j                  |       ||_        t	        |      }|j                          | j                  |j                         |j                          | j                  |j                         y)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
  sr    
 56	')	*%	&y1	++, 		++,r@   N)r;   r<   r=   r>   r  r  r  r  r  r  r  r?   r@   rA   r  r  M
  s+    
S	4<,?*?(.*-r@   r  c                   j    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y)ResponseTestsz 
    Tests for L{Response}.
    c                 h    t        t                     }| j                  t        t        |             y)z=
        L{Response} instances provide L{IResponse}.
        N)rh   r   r   r   r5   rR   r   s     rA   test_verifyInterfacez"ResponseTests.test_verifyInterface
  s$     )):;Y9:r@   c                 >   g t               } G fddt              } |       }t        |      }|j                  |       \  }|j	                          | j                  |j                  d       |j                          | j                  |j                  d       y)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y)7ResponseTests.test_makeConnection.<locals>.SomeProtocolc                 (    j                  |       y rp   r   )rR   r3  	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  rF  rL   r   rI  )rR   rg   r  r2  r   theProducerr  s         @rA   test_makeConnectionz!ResponseTests.test_makeConnection
  s     	#%		+8 	+  >(3X&!""$00(;##%00+>r@   c                     g  G fddt               } |       }t        t                     }|j                  |       |j	                  d       | j                  dg       y)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y)5ResponseTests.test_dataReceived.<locals>.ListConsumerc                 (    j                  |       y 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  r2  r   r   s       @rA   test_dataReceivedzResponseTests.test_dataReceived
  sZ     	#8 	#  >():;X&""6*)r@   c                 @   g  G fddt               } |       }t        t                     }|j                  |       |j	                          d   j                  t               | j                  t              d       | j                  |j                  d       y)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y)7ResponseTests.test_connectionLost.<locals>.ListConsumerc                 (    j                  |       y 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  r2  r   r  s       @rA   test_connectionLostz!ResponseTests.test_connectionLost   s     	$8 	$  >():;X&""$Q\"TA& 	X33T:r@   c                 H   g  G fddt               } |       }t        t                     }|j                  d       |j                  d       |j	                  |       |j                  d       | j                  g d       | j                  |j                  d       y)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y)8ResponseTests.test_bufferEarlyData.<locals>.ListConsumerc                 (    j                  |       y 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9 	X1148r@   c                     t        t                     }|j                  t                      | j	                  t
        |j                  t                      y)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_multipleStartProducingFails0  s;    
 )):;XZ(,(<(<hjIr@   c                     t        t                     }|j                  t                      |j	                          | j                  t        |j                  t                      y)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_startProducingAfterFinishedFails9  sG    
 )):;XZ(""$,(<(<hjIr@   c                     t        t                     }|j                          | j                  t        |j
                  d       y)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_bodyDataReceivedAfterFinishedFailsC  s5    
 )):;""$,(B(BFKr@   c                     t        t                     }|j                          |j                  t	                      | j                  t        |j                  d       y)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_bodyDataReceivedAfterDeliveryFailsL  sE    
 )):;""$XZ(,(B(BFKr@   c                     t        t                     }|j                          | j                  t        |j                         y)zh
        L{Response._bodyDataFinished} raises L{RuntimeError} if called more
        than once.
        N)rh   r   r   r   r   r  s     rA   'test_bodyDataFinishedAfterFinishedFailsz5ResponseTests.test_bodyDataFinishedAfterFinishedFailsV  s3    
 )):;""$,(B(BCr@   c                     t        t                     }|j                          |j                  t	                      | j                  t        |j                         y)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_  sC    
 )):;""$XZ(,(B(BCr@   c                 <   g  G fddt               }t               }|j                           |       }t        |      }| j	                  |j
                  d       |j                  |       | j	                  dg       | j	                  |j
                  d       y)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y)9ResponseTests.test_transportResumed.<locals>.ListConsumerc                 <    j                  |j                         y rp   )r   r   )rR   rg   transportStates     rA   r   zHResponseTests.test_transportResumed.<locals>.ListConsumer.makeConnectionq  s    %%i&=&=>r@   Nr  )r  s   rA   r  r  p  s    ?r@   r  r  r   N)r   r   rF  rh   rL   r   r  )rR   r  rg   r   r   r  s        @rA   test_transportResumedz#ResponseTests.test_transportResumedi  s    
 	?8 	? $%	  ">(300(;X&(400+>r@   c                 >   t               }t        |      }|j                  d       |j                  d       |j                          t	               }|j                  |       | j                  |j                  d       |j                  j                  t               y)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""6*""6*""$')X&	2""<0r@   c                    t               }t        |      }t               }|j                  |       | j	                  |j
                  d       |j                  t        t                            |j                  j                  t               y)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  sn     $%	(3')X& 	+6""7+=+?#@A""#56r@   c                    t               }t        |      }| j                  |j                  d       |j	                  t        t                            t               }|j                  |       |j                  j                  t               y)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  sn     $%	(3 	)4""7+=+?#@A')X&""#5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  
  sX    ;?,*&;29.JJLLDD?(1$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   rr  r~  r  r7  rK  r  r  r  r  r?   r@   rA   <module>r2     s    & . J J A @ .  . 0 * +    (
 
 
 ' , 5 	  'N#345%PTL6( 6BSM SMl+;X .> h
.H h
.V 0 fE fER ]     Fp;8 p;fb8 bJ):x ):X{-( {-|h7H h7r@   