U
    s@g-                    @   sp  d Z ddl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 ddlmZ ddlmZmZ dd	lmZmZmZ dd
lmZmZ ddlmZ ddlmZmZ ddlm Z m!Z!m"Z"m#Z# ddl$m%Z% ddl&m'Z'm(Z( ddl)m*Z* ddl+m,Z, ddl-m.Z.m/Z/m0Z0 ddl1m2Z2m3Z3 ddl4m5Z5m6Z6m7Z7 ddl8m9Z9 ddl:m;Z;m<Z< ddl=m>Z> ddl?m@Z@ ddlAmBZB ddlCmDZD ddlEmFZF ddl8mGZG ddlHmIZImJZJ ddlKmLZLmMZMmNZNmOZOmPZPmQZQmRZR ddlSmTZTmUZUmVZVmWZWmXZXmYZYmZZZ dd l[m\Z\ dd!l]m^Z^ dd"l_m`Z`maZambZbmcZcmdZdmeZe ddlHmIZImJZJ er@eZfegZhnegZfeZhzdd#lmiZi W n" ejk
rz   dZid$ZkdZlY n6X d%ZldZkdd&lmmnZnmoZo dd'lpmqZq dd(lrmsZsmtZt G d)d* d*e2ZuG d+d, d,egZvG d-d. d.eZwd/Zxd0Zyd1Zzd2Z{d3Z|d4Z}G d5d6 d6Z~G d7d8 d8egZG d9d: d:egZG d;d< d<e3ZG d=d> d>ee~ZG d?d@ d@egZG dAdB dBegZeebG dCdD dDegZG dEdF dFee~eeZG dGdH dHe~eIeZG dIdJ dJe~eJeZG dKdL dLee~eZG dMdN dNeZG dOdP dPee~ZG dQdR dRegZG dSdT dTeeZG dUdV dVeee~eZG dWdX dXe*eeZG dYdZ dZeZG d[d\ d\ee~eZG d]d^ d^e2ZG d_d` d`ee~ZG dadb dbee~eZdcdddedfdggZG dhdi diefZG djdk dke~eeehZG dldm dme~eeehZG dndo doe#ZG dpdq dqegZG drds dseZG dtdu dueZG dvdw dweIeZG dxdy dyeIeZG dzd{ d{eJeZG d|d} d}eJeZdS )~zD
Tests for L{twisted.web.client.Agent} and related new client APIs.
    N)BytesIO)TYPE_CHECKINGListOptionalTuple)SkipTestskipIfimplementer)verifyObject)TestCaseSynchronousTestCase)clienterrorhttp_headers)defertask)Failure)FakeTransportIOPump)AccumulatingProtocolEventLoggingObserverMemoryReactorClockStringTransport)!certificatesForAuthorityAndServer)	cookielib
intToBytes)proxyForInterface)Clock)ConnectionDoneConnectionLostConnectionRefusedError)ProtocolFactory)DeferredsucceedCancelledError)TCP4ClientEndpoint)IPv4AddressIPv6Address)Headers)IOpenSSLClientConnectionCreator)getDeprecationWarningString)Version)deterministicResolvingReactor)HostnameEndpoint)MethodInjectionTestsMixinURIInjectionTestsMixin)HTTP11ClientProtocolPotentialDataLossRequestNotSentRequestTransmissionFailedResponseResponseFailedResponseNeverReceived)URIBrowserLikePolicyForHTTPSFileBodyProducerHTTPConnectionPoolRequestResponseDone_HTTP11ClientFactory)SchemeNotSupported)globalLogPublisher)UNKNOWN_LENGTHIAgentIAgentEndpointFactoryIBodyProducerIPolicyForHTTPS	IResponse)sslz&SSL not present, cannot run SSL tests.zSSL present.)ClientTLSOptionsIOpenSSLTrustRoot)optionsForClientTLS)TLSMemoryBIOProtocolTLSMemoryBIOFactoryc                   @   s&   e Zd ZdZddddZdd ZdS )StubHTTPProtocolaR  
    A protocol like L{HTTP11ClientProtocol} but which does not actually know
    HTTP/1.1 and only collects requests in a list.

    @ivar requests: A C{list} of two-tuples.  Each time a request is made, a
        tuple consisting of the request and the L{Deferred} returned from the
        request method is appended to this list.
    Nreturnc                 C   s   g | _ d| _d S )N	QUIESCENT)requestsstateself rV   =/usr/lib/python3/dist-packages/twisted/web/test/test_agent.py__init__z   s    zStubHTTPProtocol.__init__c                 C   s   t  }| j||f |S )z
        Capture the given request for later inspection.

        @return: A L{Deferred} which this code will never fire.
        )r$   rR   append)rU   requestresultrV   rV   rW   rZ      s    zStubHTTPProtocol.request)__name__
__module____qualname____doc__rX   rZ   rV   rV   rV   rW   rN   q   s   rN   c                   @   s   e Zd Zdd Zdd ZdS )FileConsumerc                 C   s
   || _ d S N)
outputFile)rU   rb   rV   rV   rW   rX      s    zFileConsumer.__init__c                 C   s   | j | d S ra   )rb   write)rU   bytesrV   rV   rW   rc      s    zFileConsumer.writeN)r\   r]   r^   rX   rc   rV   rV   rV   rW   r`      s   r`   c                   @   sp   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd ZdS )FileBodyProducerTestszq
    Tests for the L{FileBodyProducer} which reads bytes from a file and writes
    them to an L{IConsumer}.
    c                 C   s   dd S )al  
        This method can be used as the C{terminationPredicateFactory} for a
        L{Cooperator}.  It returns a predicate which immediately returns
        C{False}, indicating that no more work should be done this iteration.
        This has the result of only allowing one iteration of a cooperative
        task to be run per L{Cooperator} iteration.
        c                   S   s   dS NTrV   rV   rV   rV   rW   <lambda>       z4FileBodyProducerTests._termination.<locals>.<lambda>rV   rT   rV   rV   rW   _termination   s    z"FileBodyProducerTests._terminationc                 C   s   g | _ t| j| j j| _dS )z
        Create a L{Cooperator} hooked up to an easily controlled, deterministic
        scheduler to use with L{FileBodyProducer}.
        N)
_scheduledr   Z
Cooperatorri   rY   
cooperatorrT   rV   rV   rW   setUp   s
     zFileBodyProducerTests.setUpc                 C   s   |  ttttd dS )zI
        L{FileBodyProducer} instances provide L{IBodyProducer}.
        rh   N)
assertTruer   rE   r;   r   rT   rV   rV   rW   test_interface   s     
z$FileBodyProducerTests.test_interfacec                 C   sT   G dd dt }G dd dt }t| }| t|j t| }| t|j dS )z
        If the L{FileBodyProducer} is constructed with a file-like object
        without either a C{seek} or C{tell} method, its C{length} attribute is
        set to C{UNKNOWN_LENGTH}.
        c                   @   s   e Zd Zdd ZdS )z9FileBodyProducerTests.test_unknownLength.<locals>.HasSeekc                 S   s   d S ra   rV   )rU   offsetwhencerV   rV   rW   seek   s    z>FileBodyProducerTests.test_unknownLength.<locals>.HasSeek.seekN)r\   r]   r^   rq   rV   rV   rV   rW   HasSeek   s   rr   c                   @   s   e Zd Zdd ZdS )z9FileBodyProducerTests.test_unknownLength.<locals>.HasTellc                 S   s   d S ra   rV   rT   rV   rV   rW   tell   s    z>FileBodyProducerTests.test_unknownLength.<locals>.HasTell.tellN)r\   r]   r^   rs   rV   rV   rV   rW   HasTell   s   rt   N)objectr;   assertEqualrB   length)rU   rr   rt   producerrV   rV   rW   test_unknownLength   s    

z(FileBodyProducerTests.test_unknownLengthc                 C   sH   d}t |}|d t|}| t|d |j | | d dS )z
        If the L{FileBodyProducer} is constructed with a file-like object with
        both C{seek} and C{tell} methods, its C{length} attribute is set to the
        size of the file as determined by those methods.
        s   here are some bytes   N)r   rq   r;   rv   lenrw   rs   )rU   
inputBytes	inputFilerx   rV   rV   rW   test_knownLength   s    
z&FileBodyProducerTests.test_knownLengthc                 C   s    t td}| tj|j dS )zw
        If no L{Cooperator} instance is passed to L{FileBodyProducer}, the
        global cooperator is used.
        rh   N)r;   r   rv   r   Z	cooperateZ
_cooperate)rU   rx   rV   rV   rW   test_defaultCooperator   s    z,FileBodyProducerTests.test_defaultCooperatorc                 C   s   d}d}t  }t|}tt || j|}||}tt|| d D ]}| jd  qF| 	g | j | 	||
  | 	d| | dS )z
        L{FileBodyProducer.startProducing} starts writing bytes from the input
        file to the given L{IConsumer} and returns a L{Deferred} which fires
        when they have all been written.
           hello, world      r   N)r   r`   r;   rk   startProducingranger{   rj   poprv   getvaluesuccessResultOf)rU   expectedResultreadSizeoutputconsumerrx   completeirV   rV   rW   test_startProducing   s      
z)FileBodyProducerTests.test_startProducingc                 C   sj   d}d}t |}t|| j|}tt  }|| tt|| d D ]}| jd  qF| 	|j
 dS )z
        When L{FileBodyProducer} reaches end-of-file on the input file given to
        it, the input file is closed.
           s   some friendly bytes   r   N)r   r;   rk   r`   r   r   r{   rj   r   rm   closed)rU   r   r|   r}   rx   r   r   rV   rV   rW   test_inputClosedAtEOF   s    

z+FileBodyProducerTests.test_inputClosedAtEOFc                 C   sP   G dd dt }t| | j}|tt }| jd  | |	t
 dS )z
        If a read from the input file fails while producing bytes to the
        consumer, the L{Deferred} returned by
        L{FileBodyProducer.startProducing} fires with a L{Failure} wrapping
        that exception.
        c                   @   s   e Zd Zdd ZdS )zGFileBodyProducerTests.test_failedReadWhileProducing.<locals>.BrokenFilec                 S   s   t dd S )NzSimulated bad thing)IOError)rU   countrV   rV   rW   read  s    zLFileBodyProducerTests.test_failedReadWhileProducing.<locals>.BrokenFile.readN)r\   r]   r^   r   rV   rV   rV   rW   
BrokenFile  s   r   r   N)ru   r;   rk   r   r`   r   rj   r   failureResultOftrapr   )rU   r   rx   r   rV   rV   rW   test_failedReadWhileProducing  s
    z3FileBodyProducerTests.test_failedReadWhileProducingc                 C   sv   d}d}t  }t|}t |}t|| j|}||}|  | |j | j	d  | 
d|  | | dS )a  
        L{FileBodyProducer.stopProducing} stops the underlying L{IPullProducer}
        and the cooperative task responsible for calling C{resumeProducing} and
        closes the input file but does not cause the L{Deferred} returned by
        C{startProducing} to fire.
        r   r   r   rh   N)r   r`   r;   rk   r   ZstopProducingrm   r   rj   r   rv   r   assertNoResult)rU   r   r   r   r   r}   rx   r   rV   rV   rW   test_stopProducing  s       
z(FileBodyProducerTests.test_stopProducingc                 C   s   d}d}t  }t|}tt || j|}||}| jd  | | |dd  |	  | jd  | | |dd  | g | j | 
| dS )z
        L{FileBodyProducer.pauseProducing} temporarily suspends writing bytes
        from the input file to the given L{IConsumer}.
        r   rz   r   N)r   r`   r;   rk   r   rj   r   rv   r   pauseProducingr   )rU   r   r   r   r   rx   r   rV   rV   rW   test_pauseProducing,  s"      
z)FileBodyProducerTests.test_pauseProducingc                 C   s   d}d}t  }t|}tt || j|}|| | jd  | |d| |  |	  |
  | jd  | |d|d  |  dS )z
        L{FileBodyProducer.resumeProducing} re-commences writing bytes from the
        input file to the given L{IConsumer} after it was previously paused
        with L{FileBodyProducer.pauseProducing}.
        r   rz   r   Nr   )r   r`   r;   rk   r   rj   r   rv   r   r   ZresumeProducing)rU   r   r   r   r   rx   rV   rV   rW   test_resumeProducingH  s       
z*FileBodyProducerTests.test_resumeProducingN)r\   r]   r^   r_   ri   rl   rn   ry   r~   r   r   r   r   r   r   r   rV   rV   rV   rW   re      s   
	re   	127.0.0.7::7z	127.0.0.8z	127.0.0.9z
127.0.0.10z
127.0.0.11c                   @   s8   e Zd ZdZdd ZG dd deZdd Zdd	 Zd
S )FakeReactorAndConnectMixinz
    A test mixin providing a testable C{Reactor} class and a dummy C{connect}
    method which allows instances to pretend to be endpoints.
    c                 C   sH   t  }t|tgtgtgtgtgtgdgdgdd}|j|_|j	|_	|S )af  
        Create a L{MemoryReactorClock} and give it some hostnames it can
        resolve.

        @return: a L{MemoryReactorClock}-like object with a slightly limited
            interface (only C{advance} and C{tcpClients} in addition to its
            formally-declared reactor interfaces), which can resolve a fixed
            set of domains.
        r   r   )example.comzipv6.example.comzexample.netzexample.orgfoozfoo.comr   r   )ZhostMap)
r   r.   EXAMPLE_COM_IPEXAMPLE_COM_V6_IPEXAMPLE_NET_IPEXAMPLE_ORG_IPFOO_LOCAL_IP
FOO_COM_IP
tcpClientsadvance)rU   ZmrcZdrrrV   rV   rW   createReactorh  s    

z(FakeReactorAndConnectMixin.createReactorc                   @   s    e Zd ZdZdd Zdd ZdS )z'FakeReactorAndConnectMixin.StubEndpointz
        Endpoint that wraps existing endpoint, substitutes StubHTTPProtocol, and
        resulting protocol instances are attached to the given test case.
        c                    sB   | _ | _dd }t|t j  _t  _ fdd j_d S )Nc                   S   s   dS )zthis function does nothingNrV   rV   rV   rV   rW   nothing  s    zAFakeReactorAndConnectMixin.StubEndpoint.__init__.<locals>.nothingc                    s    j S ra   protocol)ZaddrrT   rV   rW   rg     rh   zBFakeReactorAndConnectMixin.StubEndpoint.__init__.<locals>.<lambda>)endpointtestCaser?   reprfactoryrN   r   buildProtocol)rU   r   r   r   rV   rT   rW   rX     s    z0FakeReactorAndConnectMixin.StubEndpoint.__init__c                 C   s"   | j | j_ | j| j t| j S ra   )r   r   r   connectr   r%   )rU   ZignoredFactoryrV   rV   rW   r     s    
z/FakeReactorAndConnectMixin.StubEndpoint.connectN)r\   r]   r^   r_   rX   r   rV   rV   rV   rW   StubEndpoint  s   
r   c                    s$   t |}|j  fdd|_|S )z
        Return an Agent suitable for use in tests that wrap the Agent and want
        both a fake reactor and StubHTTPProtocol.
        c                     s     |  S ra   )r   argsZ_oldGetEndpointrU   rV   rW   rg     s    zEFakeReactorAndConnectMixin.buildAgentForWrapperTest.<locals>.<lambda>)r   Agent_getEndpoint)rU   reactoragentrV   r   rW   buildAgentForWrapperTest  s    
z3FakeReactorAndConnectMixin.buildAgentForWrapperTestc                 C   s   t  }|d || _t|S )z
        Fake implementation of an endpoint which synchronously
        succeeds with an instance of L{StubHTTPProtocol} for ease of
        testing.
        N)rN   makeConnectionr   r%   rU   r   r   rV   rV   rW   r     s    
z"FakeReactorAndConnectMixin.connectN)	r\   r]   r^   r_   r   ru   r   r   r   rV   rV   rV   rW   r   c  s
   r   c                   @   s   e Zd ZdZdd ZdS )DummyEndpointz1
    An endpoint that uses a fake transport.
    c                 C   s   | d }|t  t|S ra   r   r   r   r%   r   rV   rV   rW   r     s    
zDummyEndpoint.connectNr\   r]   r^   r_   r   rV   rV   rV   rW   r     s   r   c                   @   s   e Zd ZdZdd ZdS )BadEndpointz/
    An endpoint that shouldn't be called.
    c                 C   s   t dd S )Nz(This endpoint should not have been used.)RuntimeErrorrU   r   rV   rV   rW   r     s    zBadEndpoint.connectNr   rV   rV   rV   rW   r     s   r   c                   @   s   e Zd ZdZdd ZeZdS )DummyFactoryz/
    Create C{StubHTTPProtocol} instances.
    c                 C   s   d S ra   rV   )rU   ZquiescentCallbackZmetadatarV   rV   rW   rX     s    zDummyFactory.__init__N)r\   r]   r^   r_   rX   rN   r   rV   rV   rV   rW   r     s   r   c                   @   sp   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd ZdS )HTTPConnectionPoolTestsz4
    Tests for the L{HTTPConnectionPool} class.
    c                 C   s*   |   | _t| j| _t| j_d| j_d S NF)r   fakeReactorr<   poolr   Z_factoryretryAutomaticallyrT   rV   rV   rW   rl     s    
zHTTPConnectionPoolTests.setUpc                    s:      jji   fdd}d} j|t }||S )z{
        If there are no cached connections,
        L{HTTPConnectionPool.getConnection} returns a new connection.
        c                    s$     | t  |  jj  d S ra   )assertIsInstancerN   assertNotInr   _connectionsvaluesZconnrT   rV   rW   gotConnection  s    zMHTTPConnectionPoolTests.test_getReturnsNewIfCacheEmpty.<locals>.gotConnection/  )rv   r   r   getConnectionr   addCallback)rU   r   Z
unknownKeydrV   rT   rW   test_getReturnsNewIfCacheEmpty  s
    z6HTTPConnectionPoolTests.test_getReturnsNewIfCacheEmptyc                 C   s   t  }|t  | jd| | |jjd | || jj	d  | j
d | |jjd | || jj	d  | || jj | j
d | |jjd | || jj	d  | || jj dS )z
        If a connection is put back to the pool, a 240-sec timeout is started.

        When the timeout hits, the connection is closed and removed from the
        pool.
        http   example.comP   F   g?TN)rN   r   r   r   _putConnectionrv   	transportdisconnectingassertInr   r   r   	_timeoutsr   rU   r   rV   rV   rW   test_putStartsTimeout  s&    


z-HTTPConnectionPoolTests.test_putStartsTimeoutc                 C   s   | j }t t g}|D ]}|t  |d| q| |jd | |j }t }|t  |d| |jd }| t	|d | ||d |g | dd |D ddg | |d j
jd | ||d  j | |d |j d	S )
z
        If an idle connection is put back in the cache and the max number of
        persistent connections has been exceeded, one of the connections is
        closed and removed from the cache.
        r   r   r   c                 S   s   g | ]}|j jqS rV   )r   r   ).0prV   rV   rW   
<listcomp>*  s     zHHTTPConnectionPoolTests.test_putExceedsMaxPersistent.<locals>.<listcomp>Fr   TN)r   rN   r   r   r   rv   r   r   copyr{   r   r   rm   	cancelledr   )rU   r   
origCachedr   ZtimeoutsnewProtocolZ	newCachedrV   rV   rW   test_putExceedsMaxPersistent  s*    

z4HTTPConnectionPoolTests.test_putExceedsMaxPersistentc                    s    fdd}g }| |ddd | |ddd |ddd |ddd   jjd	 |  t jjd
 d  t jjd d dS )z
        C{maxPersistentPerHost} is enforced per C{(scheme, host, port)}:
        different keys have different max connections.
        c                    s*   t  }|t   j| ||f| |S ra   )rN   r   r   r   r   schemehostportr   rT   rV   rW   addProtocol6  s    zFHTTPConnectionPoolTests.test_maxPersistentPerHost.<locals>.addProtocolr   r   r   https     www2.example.comr   )r   r   r   r   )r   r   r   N)rY   rv   r   r   r{   )rU   r   
persistentrV   rT   rW   test_maxPersistentPerHost1  s$    
   z1HTTPConnectionPoolTests.test_maxPersistentPerHostc                    sD   t    t  jd   fdd}jdt |S )z
        Getting an address which has a cached connection returns the cached
        connection, removes it from the cache and cancels its timeout.
        r   c                    sP     |  | jjd  jd | jjd | jj	 d S )Nr      F)
assertIdenticalr   r   r   r   r   rv   r   r   r   r   r   rU   rV   rW   r   S  s     
zGHTTPConnectionPoolTests.test_getCachedConnection.<locals>.gotConnection)rN   r   r   r   r   r   r   r   )rU   r   rV   r   rW   test_getCachedConnectionI  s    
z0HTTPConnectionPoolTests.test_getCachedConnectionc                    sN   t  t  d j   fdd}j t }||S )zR
        The pool's C{_newConnection} method constructs a new connection.
        r   c                    s8    |  jj   | jj  d S ra   )assertNotIdenticalr   r   r   r   r   )newConnectionkeyr   rU   rV   rW   r   l  s    zAHTTPConnectionPoolTests.test_newConnection.<locals>.gotConnection)rN   r   r   r   r   _newConnectionr   r   )rU   r   r   rV   r   rW   test_newConnectionb  s    z*HTTPConnectionPoolTests.test_newConnectionc                 C   s   | j }d}t t g}|D ]}|t  ||| q| |j| | d|d _g }| j |t	 
|j | |d |d  | |j| g  | |ji  dS )z{
        When getting connections out of the cache, disconnected connections
        are removed and not returned.
        r   ZDISCONNECTEDr   r   N)r   rN   r   r   r   rv   r   rS   r   r   r   rY   r   r   )rU   r   r   r   r   r[   rV   rV   rW   test_getSkipsDisconnectedx  s"    
z1HTTPConnectionPoolTests.test_getSkipsDisconnectedc                 C   s   t  }| |jd t| t}d|_| jd| | dt	| |d }|d }| 
|jt | | d | d| jjd | t dS )	ze
        If a non-quiescent connection is put back in the cache, an error is
        logged.
        rQ   ZNOTQUIESCENTr   r   r   Zlog_failurez5BUG: Non-quiescent protocol added to connection pool.N)rN   rv   rS   r   ZcreateWithCleanuprA   r   r   assertEqualsr{   r   valuer   ZgetErrorMessager   r   getZflushLoggedErrors)rU   r   ZlogObserverZeventfrV   rV   rW   test_putNotQuiescent  s(    z,HTTPConnectionPoolTests.test_putNotQuiescentc                 C   s   G dd dt }t| jd}d|_g }d}||| |j |d }| |t d|_	|
| g }||| |j | |d | dS )	aI  
        When L{HTTPConnectionPool.getConnection} connects, it returns a
        C{Deferred} that fires with an instance of L{HTTP11ClientProtocol}
        that has the correct quiescent callback attached. When this callback
        is called the protocol is returned to the cache correctly, using the
        right key.
        c                   @   s   e Zd Zdd ZdS )zMHTTPConnectionPoolTests.test_getUsesQuiescentCallback.<locals>.StringEndpointc                 S   s   | d }|t  t|S ra   r   )rU   r   r   rV   rV   rW   r     s    
zUHTTPConnectionPoolTests.test_getUsesQuiescentCallback.<locals>.StringEndpoint.connectNr\   r]   r^   r   rV   rV   rV   rW   StringEndpoint  s   r  TFza keyr   rQ   N)ru   r<   r   r   r   r   rY   r   r2   Z_stateZ_quiescentCallbackr   )rU   r  r   r[   r   r   Zresult2rV   rV   rW   test_getUsesQuiescentCallback  s.     
 z5HTTPConnectionPoolTests.test_getUsesQuiescentCallbackc                    s   g   fdd}|ddd |ddd j  } D ]}|jjd q8j ji  j D ]}|jd qhj j	i  g }|
|j |g   d tt  |g   d	 tt  |d
g d
S )z
        L{HTTPConnectionPool.closeCachedConnections} closes all cached
        connections and removes them from the cache. It returns a Deferred
        that fires when they have all lost their connections.
        c                    s4   t  }|t  j| ||f|  | d S ra   )r2   r   r   r   r   rY   r   r   rU   rV   rW   r     s    zHHTTPConnectionPoolTests.test_closeCachedConnections.<locals>.addProtocolr   r   r   r   Tr   r   N)r   ZcloseCachedConnectionsrv   r   r   r   r   ZgetDelayedCallsr   r   r   rY   connectionLostr   r   )rU   r   ZdoneDeferredr   Zdcr[   rV   r	  rW   test_closeCachedConnections  s$    
z3HTTPConnectionPoolTests.test_closeCachedConnectionsc                    sX   |  | jji  t  G  fddd}| jd| }|  |  |  jt dS )z
        Cancelling the C{Deferred} returned from
        L{HTTPConnectionPool.getConnection} cancels the C{Deferred} returned
        by opening a new connection with the given endpoint.
        c                       s   e Zd Z fddZdS )zXHTTPConnectionPoolTests.test_cancelGetConnectionCancelsEndpointConnect.<locals>.Endpointc                    s    S ra   rV   r   ZconnectionResultrV   rW   r     s    z`HTTPConnectionPoolTests.test_cancelGetConnectionCancelsEndpointConnect.<locals>.Endpoint.connectNr  rV   r  rV   rW   Endpoint  s   r  i90  N)	rv   r   r   r$   r   cancelr   typer&   )rU   r  r   rV   r  rW   .test_cancelGetConnectionCancelsEndpointConnect  s    zFHTTPConnectionPoolTests.test_cancelGetConnectionCancelsEndpointConnectN)r\   r]   r^   r_   rl   r   r   r   r   r   r   r   r  r  r  r  rV   rV   rV   rW   r     s    !'#r   c                   @   s   e Zd ZdZdd ZdS )AgentTestsMixinz1
    Tests for any L{IAgent} implementation.
    c                 C   s   |  tt|   dS )z6
        The agent object provides L{IAgent}.
        N)rm   r   rC   	makeAgentrT   rV   rV   rW   rn     s    zAgentTestsMixin.test_interfaceN)r\   r]   r^   r_   rn   rV   rV   rV   rW   r    s   r  c                   @   sF   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d ej	dfddZ
dS )IntegrationTestingMixinzG
    Transport-to-Agent integration tests for both HTTP and HTTPS.
    c                 C   s   |  dtt dS )z+
        L{Agent} works over IPv4.
        r   N)integrationTestr   r(   rT   rV   rV   rW   test_integrationTestIPv4#  s    z0IntegrationTestingMixin.test_integrationTestIPv4c                 C   s   |  ddt dS )L
        L{Agent} works over IPv4 when hostname is an IPv4 address.
        s	   127.0.0.7r   N)r  r(   rT   rV   rV   rW   test_integrationTestIPv4Address*  s    z7IntegrationTestingMixin.test_integrationTestIPv4Addressc                 C   s   |  dtt dS )z+
        L{Agent} works over IPv6.
        s   ipv6.example.comN)r  r   r)   rT   rV   rV   rW   test_integrationTestIPv61  s    z0IntegrationTestingMixin.test_integrationTestIPv6c                 C   s   |  ddt dS )zL
        L{Agent} works over IPv6 when hostname is an IPv6 address.
        s   [::7]r   N)r  r)   rT   rV   rV   rW   test_integrationTestIPv6Address9  s    z7IntegrationTestingMixin.test_integrationTestIPv6Addressc                 C   s   | S ra   rV   serverrV   rV   rW   rg   A  rh   z IntegrationTestingMixin.<lambda>   httpc                    sp  |   }||}|d|d | d }	|jd \}
}}}}| |
| |d|
|}||}t|d|d}|| tj fdd	 d
 _	d
 _
| d
}t|d}|| t||||d}|  | |	  j	jd}| |d d|d  tdd |dd
 D }| |d | | |	  j	jd |  | |	}| |jdd d d
S )a  
        L{Agent} will make a TCP connection, send an HTTP request, and return a
        L{Deferred} that fires when the response has been received.

        @param hostName: The hostname to interpolate into the URL to be
            requested.
        @type hostName: L{bytes}

        @param expectedAddress: The expected address string.
        @type expectedAddress: L{bytes}

        @param addressType: The class to construct an address out of.
        @type addressType: L{type}

        @param serverWrapper: A callable that takes a protocol factory and
            returns a protocol factory; used to wrap the server / responder
            side in a TLS server.
        @type serverWrapper:
            serverWrapper(L{twisted.internet.interfaces.IProtocolFactory}) ->
            L{twisted.internet.interfaces.IProtocolFactory}

        @param createAgent: A callable that takes a reactor and produces an
            L{IAgent}; used to construct an agent with an appropriate trust
            root for TLS.
        @type createAgent: createAgent(reactor) -> L{IAgent}

        @param scheme: The scheme to test, C{http} or C{https}
        @type scheme: L{bytes}
           GET   ://   /r   ZTCPF)peerAddressc                     s   t  } |  _| S ra   )r   currentProtocol)ZapaccumulatorrV   rW   r#  k  s    z<IntegrationTestingMixin.integrationTest.<locals>.accumulatorNTs   
s
   GET / HTTPc                 S   s   g | ]}|r| d dqS )s   : r   )split)r   linerV   rV   rW   r   {  s      z;IntegrationTestingMixin.integrationTest.<locals>.<listcomp>r      HostsL   HTTP/1.1 200 OK
X-An-Header: an-value

Content-length: 12

hello world!s   x-an-headers   an-value)r   rZ   r   rv   r   r   r   r#   forProtocolr!  ZprotocolConnectionMader   flushr   datar$  rm   
startswithdictr   rc   r   r  headersgetRawHeaders)rU   hostNameexpectedAddressaddressTypeserverWrappercreateAgentr   r   r   deferredr   r   r   timeoutZbindr   ZclientProtocolZclientTransportwrapperZserverTransportZpumplinesr,  responserV   r"  rW   r  @  sL    !



  


z'IntegrationTestingMixin.integrationTestN)r\   r]   r^   r_   r  r  r  r  r   r   r  rV   rV   rV   rW   r    s   r  c                   @   s   e Zd ZdZdd ZdS )StubEndpointFactoryz=
    A stub L{IAgentEndpointFactory} for use in testing.
    c                 C   s   |j |j|jfS )z
        Testing implementation.

        @param uri: A L{URI}.

        @return: C{(scheme, host, port)} of passed in URI; violation of
            interface but useful for testing.
        @rtype: L{tuple}
        )r   r   r   rU   urirV   rV   rW   endpointForURI  s    
z"StubEndpointFactory.endpointForURIN)r\   r]   r^   r_   r;  rV   rV   rV   rW   r8    s   r8  c                   @   s  e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zd d! Zd"d# Zd$d% Zd&d' Zd(d) Zd*d+ Zee_d,d- Zd.d/ Zee_d0d1 Zd2d3 Zd4d5 Zd6d7 Z d8d9 Z!d:d; Z"d<S )=
AgentTestszA
    Tests for the new HTTP client API provided by L{Agent}.
    c                 C   s   t | jS )zE
        @return: a new L{twisted.web.client.Agent} instance
        )r   r   r   rT   rV   rV   rW   r    s    zAgentTests.makeAgentc                 C   s   |   | _|  | _dS C
        Create an L{Agent} wrapped around a fake reactor.
        Nr   r   r  r   rT   rV   rV   rW   rl     s    
zAgentTests.setUpc                 C   s@   t | j}| |jt | |jjd | |j	|jj	 dS )zV
        If no pool is passed in, the L{Agent} creates a non-persistent pool.
        FN)
r   r   r   r   _poolr<   rv   r   r   _reactorrU   r   rV   rV   rW   test_defaultPool  s    zAgentTests.test_defaultPoolc                    sR   t  j}tj j|d} fdd|_|dd   jjd d j	d dS )	z
        If C{persistent} is set to C{True} on the L{HTTPConnectionPool} (the
        default), C{Request}s are created with their C{persistent} flag set to
        C{True}.
        r   c                     s    S ra   rV   r   rT   rV   rW   rg     rh   z,AgentTests.test_persistent.<locals>.<lambda>r     http://127.0.0.1r   TN
r<   r   r   r   r   rZ   rv   r   rR   r   rU   r   r   rV   rT   rW   test_persistent  s
    
zAgentTests.test_persistentc                    sV   t  jdd}tj j|d} fdd|_|dd   jjd d j	d d	S )
a  
        If C{persistent} is set to C{False} when creating the
        L{HTTPConnectionPool}, C{Request}s are created with their
        C{persistent} flag set to C{False}.

        Elsewhere in the tests for the underlying HTTP code we ensure that
        this will result in the disconnection of the HTTP protocol once the
        request is done, so that the connection will not be returned to the
        pool.
        Fr   rD  c                     s    S ra   rV   r   rT   rV   rW   rg     rh   z/AgentTests.test_nonPersistent.<locals>.<lambda>r  rE  r   NrF  rG  rV   rT   rW   test_nonPersistent  s
    zAgentTests.test_nonPersistentc                    s   t   G  fdddtj}G  fdddt}| }|j|d}||j t }|	dd t }|j
dd	||d
 |jjd dS )z
        When a connection is made by the Agent, it uses its pool's
        C{getConnection} method to do so, with the endpoint returned by
        C{self._getEndpoint}. The key used is C{(scheme, host, port)}.
        c                       s   e Zd Z fddZdS )z:AgentTests.test_connectUsesConnectionPool.<locals>.MyAgentc                    s    |j|j|jfd  S )Nr     foor   )rv   r   r   r   )thisr:  r   rU   rV   rW   r     s    zGAgentTests.test_connectUsesConnectionPool.<locals>.MyAgent._getEndpointN)r\   r]   r^   r   rV   rN  rV   rW   MyAgent  s   rO  c                       s"   e Zd ZdZdZ fddZdS )z<AgentTests.test_connectUsesConnectionPool.<locals>.DummyPoolFc                    s*   d| _ |  |d tt S )NTrK  )	connectedrv   r   r%   rN   rM  r   ZeprN  rV   rW   r     s    zJAgentTests.test_connectUsesConnectionPool.<locals>.DummyPool.getConnectionNr\   r]   r^   rP  r   r   rV   rN  rV   rW   	DummyPool  s   rS  rD     hostrL  r     http://foo/)bodyProducerr,  TN)r   r   r   ru   r   r   r@  r   r*   ZaddRawHeaderrZ   rv   rP  )rU   rO  rS  r   r   r,  rV  rV   rN  rW   test_connectUsesConnectionPool  s     z)AgentTests.test_connectUsesConnectionPoolc                 C   s   |  | jddtS )z
        L{Agent.request} returns a L{Deferred} which fails with
        L{SchemeNotSupported} if the scheme of the URI passed to it is not
        C{'http'}.
        r  s   mailto:alice@example.com)assertFailurer   rZ   r@   rT   rV   rV   rW   test_unsupportedScheme   s    z!AgentTests.test_unsupportedSchemec                 C   sV   | j dd}| jj dd \}}}|dtt  | jd | 	|t dS )z
        The L{Deferred} returned by L{Agent.request} fires with a L{Failure} if
        the TCP connection attempt fails.
        r  rU  Nr   
   )
r   rZ   r   r   r   ZclientConnectionFailedr   r!   r   r   )rU   r[   r   r   r   rV   rV   rW   test_connectionFailed  s
    z AgentTests.test_connectionFailedc                 C   sV   d}d}| j td| d t| }| |jd | |j| | |t	 dS )zo
        L{Agent._getEndpoint} return a C{HostnameEndpoint} when passed a scheme
        of C{'http'}.
        r     s   http://   :r   N)
r   r   r9   	fromBytesr   rv   _hostStr_portr   r/   )rU   expectedHostexpectedPortr   rV   rV   rW   test_connectHTTP  s    
zAgentTests.test_connectHTTPc              	   C   s^   t d}dd|_| t}| j| W 5 Q R X | |j	j
d djt|jd dS )z|
        L{Agent._getEndpoint} when given a non-ASCII decodable URI will raise a
        L{ValueError} saying such.
        s   http://example.com:80u   ☃.comutf8r   zaThe host of the provided URI ({reprout}) contains non-ASCII octets, it should be ASCII decodable.)ZreproutN)r9   r^  encoder   assertRaises
ValueErrorr   r   rv   	exceptionr   formatr   )rU   r:  erV   rV   rW   test_nonDecodableURI'  s    
zAgentTests.test_nonDecodableURIc                    sH    fdd j _ j dd  jj \}} |jddg dS )z
        If L{None} is passed to L{Agent.request} for the C{headers} parameter,
        a L{Headers} instance is created for the request and a I{Host} header
        added to it.
        c                     s    S ra   rV   r   rT   rV   rW   rg   >  rh   z.AgentTests.test_hostProvided.<locals>.<lambda>r     http://example.com/foo?barrT  r   N	r   r   rZ   r   rR   r   rv   r,  r-  rU   reqresrV   rT   rW   test_hostProvided8  s     zAgentTests.test_hostProvidedc                    sH    fdd j _ j dd  jj \}} |jddg dS )z
        If an IPv6 address is used in the C{uri} passed to L{Agent.request},
        the computed I{Host} header needs to be bracketed.
        c                     s    S ra   rV   r   rT   rV   rW   rg   K  rh   z3AgentTests.test_hostIPv6Bracketed.<locals>.<lambda>r  s   http://[::1]/rT  s   [::1]Nrm  rn  rV   rT   rW   test_hostIPv6BracketedF  s    z!AgentTests.test_hostIPv6Bracketedc                    s^   t dgdgd} fdd j_ jdd|  jj \}} |j	
ddg d	S )
z
        If the headers passed to L{Agent.request} includes a value for the
        I{Host} header, that value takes precedence over the one which would
        otherwise be automatically provided.
           bars   quuxrL  rT  c                     s    S ra   rV   r   rT   rV   rW   rg   Y  rh   z.AgentTests.test_hostOverride.<locals>.<lambda>r  rl  rT  N)r   r*   r   r   rZ   r   rR   r   rv   r,  r-  )rU   r,  ro  rp  rV   rT   rW   test_hostOverrideR  s      zAgentTests.test_hostOverridec                    sT   t  } fdd j_ jdd|  j} t|jd  |t   dS )z
        If a I{Host} header must be added to the request, the L{Headers}
        instance passed to L{Agent.request} is not modified.
        c                     s    S ra   rV   r   rT   rV   rW   rg   g  rh   z3AgentTests.test_headersUnmodified.<locals>.<lambda>r     http://example.com/foor   N)	r   r*   r   r   rZ   r   rv   r{   rR   )rU   r,  r   rV   rT   rW   test_headersUnmodifieda  s      z!AgentTests.test_headersUnmodifiedc                 C   s   |  | jdddd dS )z
        When passed a scheme of C{'http'} and a port of C{80},
        L{Agent._computeHostValue} returns a string giving just
        the host name passed to it.
        r  r   r   Nrv   r   Z_computeHostValuerT   rV   rV   rW   test_hostValueStandardHTTPs  s    z%AgentTests.test_hostValueStandardHTTPc                 C   s   |  | jdddd dS )z
        When passed a scheme of C{'http'} and a port other than C{80},
        L{Agent._computeHostValue} returns a string giving the
        host passed to it joined together with the port number by C{":"}.
        r  r   1     example.com:54321Nrx  rT   rV   rV   rW   test_hostValueNonStandardHTTP~  s    z(AgentTests.test_hostValueNonStandardHTTPc                 C   s   |  | jdddd dS )z
        When passed a scheme of C{'https'} and a port of C{443},
        L{Agent._computeHostValue} returns a string giving just
        the host name passed to it.
           httpsr   r   Nrx  rT   rV   rV   rW   test_hostValueStandardHTTPS  s    z&AgentTests.test_hostValueStandardHTTPSc                 C   s   |  | jdddd dS )z
        When passed a scheme of C{'https'} and a port other than C{443},
        L{Agent._computeHostValue} returns a string giving the
        host passed to it joined together with the port number by C{":"}.
        r}  r   rz  r{  Nrx  rT   rV   rV   rW   test_hostValueNonStandardHTTPS  s    z)AgentTests.test_hostValueNonStandardHTTPSc                    s    fdd j _tddgi}t } j dd||  j} t|j	d |j	
 \}} |t  |jd  |jd  |jtdgd	gd
  |j| dS )a_  
        L{Agent.request} establishes a new connection to the host indicated by
        the host part of the URI passed to it and issues a request using the
        method, the path portion of the URI, the headers, and the body producer
        passed to it.  It returns a L{Deferred} which fires with an
        L{IResponse} from the server.
        c                     s    S ra   rV   r   rT   rV   rW   rg     rh   z)AgentTests.test_request.<locals>.<lambda>rL  rs  r     http://example.com:1234/foo?barr   s   /foo?bar   example.com:1234rt  N)r   r   r   r*   ru   rZ   r   rv   r{   rR   r   r   r=   methodr:  r,  r   rV  )rU   r,  bodyr   ro  rp  rV   rT   rW   test_request  s,       zAgentTests.test_requestc                 C   s<   t j| jdd}|dd | jj d }| d| dS )z~
        L{Agent} takes a C{connectTimeout} argument which is forwarded to the
        following C{connectTCP} agent.
        rz   ZconnectTimeoutr  rU  r   Nr   r   r   rZ   r   r   rv   rU   r   r4  rV   rV   rW   test_connectTimeout  s    zAgentTests.test_connectTimeoutc                 C   s<   t j| jdd}|dd | jj d }| d| dS )z}
        L{Agent} takes a C{connectTimeout} argument which is forwarded to the
        following C{connectTCP} call.
        rz   r  r     https://foo/r   Nr  r  rV   rV   rW   test_connectTimeoutHTTPS  s    z#AgentTests.test_connectTimeoutHTTPSc                 C   s<   t j| jdd}|dd | jj d }| d| dS )zz
        L{Agent} takes a C{bindAddress} argument which is forwarded to the
        following C{connectTCP} call.
        192.168.0.1ZbindAddressr  rU  r   Nr  rU   r   ZaddressrV   rV   rW   test_bindAddress  s    zAgentTests.test_bindAddressc                 C   s<   t j| jdd}|dd | jj d }| d| dS )zz
        L{Agent} takes a C{bindAddress} argument which is forwarded to the
        following C{connectSSL} call.
        r  r  r  r  r   Nr  r  rV   rV   rW   test_bindAddressSSL  s    zAgentTests.test_bindAddressSSLc                 C   s   d}|  | j}|d|}| t| jjd | jj \}}| |t	 t
jdddt
i d|}|| | |}| |jj|jj|jjf|j|j|jf dS )z
        L{Response}s returned by L{Agent.request} have a reference to the
        L{Request} that was originally issued.
           http://example.com/r  r   s   HTTPr   r         OKN)r   r   rZ   rv   r{   r   rR   r   r   r=   r   r6   Z
_constructr*   callbackr   r  absoluteURIr,  )rU   r:  r   r   ro  rp  respr7  rV   rV   rW   test_responseIncludesRequest  s,    

z'AgentTests.test_responseIncludesRequestc                 C   s^   d}|  | j}|d| | t| jjd | jj \}}| |t	 | |j
| dS )zL
        L{Request.absoluteURI} is the absolute URI of the request.
        s$   http://example.com/foo;1234?bar#fragr  r   N)r   r   rZ   rv   r{   r   rR   r   r   r=   r  )rU   r:  r   ro  rp  rV   rV   rW   test_requestAbsoluteURI  s    z"AgentTests.test_requestAbsoluteURIc                 C   s&   t ddt  d}| |jd dS )zX
        L{Request.absoluteURI} is L{None} if L{Request._parsedURI} is L{None}.
           FOOr  N)r   r=   r*   r   r  )rU   rZ   rV   rV   rW   test_requestMissingAbsoluteURI  s    z)AgentTests.test_requestMissingAbsoluteURIc                 C   s:   t  }tjjd|d}td}||}| |d dS )z|
        L{Agent.usingEndpointFactory} creates an L{Agent} that uses the given
        factory to create endpoints.
        N)ZendpointFactoryr  )r  r   r   )r8  r   r   usingEndpointFactoryr9   r^  r   rv   )rU   r   r   r:  ZreturnedEndpointrV   rV   rW   test_endpointFactory$  s     

zAgentTests.test_endpointFactoryc                 C   s<   t j| jt }|j}| |j|j|j	ft
d|j	f dS )z
        If no pool is passed in to L{Agent.usingEndpointFactory}, a default
        pool is constructed with no persistent connections.
        FN)r   r   r  r   r8  r@  rv   	__class__r   rA  r<   )rU   r   r   rV   rV   rW   test_endpointFactoryDefaultPool1  s     
z*AgentTests.test_endpointFactoryDefaultPoolc                 C   s,   t  }tj| jt |}| ||j dS )zr
        If a pool is passed in to L{Agent.usingEndpointFactory} it is used as
        the L{Agent} pool.
        N)ru   r   r   r  r   r8  assertIsr@  rG  rV   rV   rW   test_endpointFactoryPool=  s      z#AgentTests.test_endpointFactoryPoolN)#r\   r]   r^   r_   r  rl   rC  rH  rJ  rW  rY  r[  rc  rk  rq  rr  ru  rw  ry  r|  r~  r  r  r  r  skipWhenNoSSLskipr  r  r  r  r  r  r  r  rV   rV   rV   rW   r<    s@   
$ 

r<  c                   @   s   e Zd ZdZdd ZdS )AgentMethodInjectionTestsz>
    Test L{client.Agent} against HTTP method injections.
    c                 C   s*   t |  }d}|||t  d dS )v
        Attempt a request with the provided method.

        @param method: see L{MethodInjectionTestsMixin}
           http://twisted.invalidNr   r   r   rZ   r*   )rU   r  r   r:  rV   rV   rW   !attemptRequestWithMaliciousMethodR  s    z;AgentMethodInjectionTests.attemptRequestWithMaliciousMethodNr\   r]   r^   r_   r  rV   rV   rV   rW   r  I  s   r  c                   @   s   e Zd ZdZdd ZdS )AgentURIInjectionTestsz6
    Test L{client.Agent} against URI injections.
    c                 C   s*   t |  }d}|||t  d dS )zp
        Attempt a request with the provided method.

        @param uri: see L{URIInjectionTestsMixin}
        r  Nr  )rU   r:  r   r  rV   rV   rW   attemptRequestWithMaliciousURIg  s    z5AgentURIInjectionTests.attemptRequestWithMaliciousURINr\   r]   r^   r_   r  rV   rV   rV   rW   r  ^  s   r  c                       s   e Zd ZdZeZdddZdd Zdd	 Zd
d Z	dd Z
dd Zdd Zdd Z fddZde_ fddZde_ fddZ  ZS )AgentHTTPSTestsz@
    Tests for the new HTTP client API that depends on SSL.
    r   r   c                 C   s.   t |  td| d t| d S )a  
        Create an L{Agent} with an https scheme and return its endpoint
        created according to the arguments.

        @param host: The host for the endpoint.
        @type host: L{bytes}

        @param port: The port for the endpoint.
        @type port: L{int}

        @return: An endpoint of an L{Agent} constructed according to args.
        @rtype: L{SSL4ClientEndpoint}
           https://r]  r  )r   r   r   r   r9   r^  r   )rU   r   r   rV   rV   rW   makeEndpointz  s    zAgentHTTPSTests.makeEndpointc                 C   s2   ddl m} |  }| || | |jt dS )zr
        L{Agent._getEndpoint} return a L{SSL4ClientEndpoint} when passed a
        scheme of C{'https'}.
        r   )_WrapperEndpointN)twisted.internet.endpointsr  r  r   _wrappedEndpointr/   )rU   r  r   rV   rV   rW   test_endpointType  s    z!AgentHTTPSTests.test_endpointTypec                 C   s    | j dd}| |jjd dS )z@
        If a host is passed, the endpoint respects it.
        r   )r   r   N)r  rv   r  r_  )rU   r   rV   rV   rW   test_hostArgumentIsRespected  s    z,AgentHTTPSTests.test_hostArgumentIsRespectedc                 C   s$   d}| j |d}| |jj| dS )z@
        If a port is passed, the endpoint respects it.
          )r   N)r  rv   r  r`  )rU   rb  r   rV   rV   rW   test_portArgumentIsRespected  s    z,AgentHTTPSTests.test_portArgumentIsRespectedc                 C   s2   |   }|dj}| |t | |jd dS )zY
        L{Agent} wraps its connection creator creator and uses modern TLS APIs.
        Nr   )r  Z_wrapperFactoryZ_connectionCreatorr   rI   rv   Z	_hostname)rU   r   contextFactoryrV   rV   rW   test_contextFactoryType  s    z'AgentHTTPSTests.test_contextFactoryTypec                    s  d}d}G dd dt }g ttG fdddt  | ttG  fdddt }| }|  }t||}|t	d	| d
 t
| }|tt |jd d }	|	d}
|
t  d d }| |t | d dd ||f | j | j dS )a  
        If a custom L{WebClientConnectionCreator}-like object is passed to
        L{Agent.__init__} it will be used to determine the SSL parameters for
        HTTPS requests.  When an HTTPS request is made, the hostname and port
        number of the request URL will be passed to the connection creator's
        C{creatorForNetloc} method.  The resulting context object will be used
        to establish the SSL connection.
        s   example.orgiO  c                   @   s$   e Zd ZdZdZdd Zdd ZdS )zVAgentHTTPSTests.test_connectHTTPSCustomConnectionCreator.<locals>.JustEnoughConnectionFc                 S   s
   d| _ dS )zK
                The handshake started.  Record that fact.
                TN)handshakeStartedrT   rV   rV   rW   do_handshake  s    zcAgentHTTPSTests.test_connectHTTPSCustomConnectionCreator.<locals>.JustEnoughConnection.do_handshakec                 S   s
   d| _ dS )zL
                The connection started.  Record that fact.
                TN)connectStaterT   rV   rV   rW   set_connect_state  s    zhAgentHTTPSTests.test_connectHTTPSCustomConnectionCreator.<locals>.JustEnoughConnection.set_connect_stateN)r\   r]   r^   r  r  r  r  rV   rV   rV   rW   JustEnoughConnection  s   r  c                       s"   e Zd Zdd Z fddZdS )zSAgentHTTPSTests.test_connectHTTPSCustomConnectionCreator.<locals>.JustEnoughCreatorc                 S   s   || _ || _d S ra   )hostnamer   rU   r  r   rV   rV   rW   rX     s    z\AgentHTTPSTests.test_connectHTTPSCustomConnectionCreator.<locals>.JustEnoughCreator.__init__c                    s     || j| jf S )z
                Implement L{IOpenSSLClientConnectionCreator}.

                @param tlsProtocol: The TLS protocol.
                @type tlsProtocol: L{TLSMemoryBIOProtocol}

                @return: C{expectedConnection}
                )rY   r  r   )rU   tlsProtocolcontextArgsexpectedConnectionrV   rW   clientConnectionForTLS  s    	zjAgentHTTPSTests.test_connectHTTPSCustomConnectionCreator.<locals>.JustEnoughCreator.clientConnectionForTLSN)r\   r]   r^   rX   r  rV   r  rV   rW   JustEnoughCreator  s   r  c                       s   e Zd Z fddZdS )z_AgentHTTPSTests.test_connectHTTPSCustomConnectionCreator.<locals>.StubBrowserLikePolicyForHTTPSc                    s
    ||S )am  
                Emulate L{BrowserLikePolicyForHTTPS}.

                @param hostname: The hostname to verify.
                @type hostname: L{bytes}

                @param port: The port number.
                @type port: L{int}

                @return: a stub L{IOpenSSLClientConnectionCreator}
                @rtype: L{JustEnoughCreator}
                rV   r  r  rV   rW   creatorForNetloc  s    zpAgentHTTPSTests.test_connectHTTPSCustomConnectionCreator.<locals>.StubBrowserLikePolicyForHTTPS.creatorForNetlocNr\   r]   r^   r  rV   r  rV   rW   StubBrowserLikePolicyForHTTPS  s   r  r  r]  r   Nr   r   )ru   r
   r+   rF   r   r   r   r   r9   r^  r   r   r#   r'  r"   r   r   r   r   r   rL   rv   rm   r  r  )rU   ra  rb  r  r  ZexpectedCreatorCreatorr   r   r   Z
tlsFactoryr  ZtlsrV   )r  r  r  rW   (test_connectHTTPSCustomConnectionCreator  s0    	
z8AgentHTTPSTests.test_connectHTTPSCustomConnectionCreatorc                 C   sT   dd }|  |  |g}| t|d |\}| |d t | |d d dS )aP  
        Passing something that duck-types I{like} a L{web client context
        factory <twisted.web.client.WebClientContextFactory>} - something that
        does not provide L{IPolicyForHTTPS} - to L{Agent} emits a
        L{DeprecationWarning} even if you don't actually C{import
        WebClientContextFactory} to do it.
        c                   S   s   t tt d d S )Nz does-not-provide-IPolicyForHTTPS)r   r   r.   r   rV   rV   rV   rW   warnMe	  s    z9AgentHTTPSTests.test_deprecatedDuckPolicy.<locals>.warnMer   categorymessagez'does-not-provide-IPolicyForHTTPS' was passed as the HTTPS policy for an Agent, but it does not provide IPolicyForHTTPS.  Since Twisted 14.0, you must pass a provider of IPolicyForHTTPS.N)flushWarningsrv   r{   DeprecationWarning)rU   r  warningswarningrV   rV   rW   test_deprecatedDuckPolicy  s    z)AgentHTTPSTests.test_deprecatedDuckPolicyc                 C   s`   t tG dd dt}| }t|d}|dd}| |j |d}| |j	|
  dS )z
        L{BrowserLikePolicyForHTTPS.creatorForNetloc} returns an
        L{IOpenSSLClientConnectionCreator} provider which will add certificates
        from the given trust root.
        c                   @   s   e Zd ZdZdZdd ZdS )zGAgentHTTPSTests.test_alternateTrustRoot.<locals>.CustomOpenSSLTrustRootFNc                 S   s   d| _ || _d S rf   )calledcontext)rU   r  rV   rV   rW   _addCACertsToContext#  s    z\AgentHTTPSTests.test_alternateTrustRoot.<locals>.CustomOpenSSLTrustRoot._addCACertsToContext)r\   r]   r^   r  r  r  rV   rV   rV   rW   CustomOpenSSLTrustRoot  s   r  	trustRoots   thingyr  N)r
   rJ   ru   r:   r  rm   r  r  r  r  Zget_context)rU   r  r  ZpolicyZcreator
connectionrV   rV   rW   test_alternateTrustRoot  s    

z'AgentHTTPSTests.test_alternateTrustRootc                    s   t t|   dS )r  N)superr  r  rT   r  rV   rW   r  .  s    z/AgentHTTPSTests.test_integrationTestIPv4Addressz;service_identity does not support IP address validation yetc                    s   t t|   dS )zP
        L{Agent} works over IPv6 when the hostname is an IPv6 address.
        N)r  r  r  rT   r  rV   rW   r  8  s    z/AgentHTTPSTests.test_integrationTestIPv6Addressc                    sT   | d}t|d\ fdd} fdd}tt| j|||||dd d	S )
zC
        Wrap L{AgentTestsMixin.integrationTest} with TLS.
        s   []asciic                    s   t   d| S r   )rM   Zoptions)ZserverFactoryr  rV   rW   tlsifyI  s    z/AgentHTTPSTests.integrationTest.<locals>.tlsifyc                    sD   ddl m} ddlm} ||G  fdddt}tj| | dS )Nr   )rF   r	   c                       s   e Zd Z fddZdS )zAAgentHTTPSTests.integrationTest.<locals>.tlsagent.<locals>.Policyc                    s   t |d dS )Nr  r  )rK   decoder  	authorityrV   rW   r  P  s    
zRAgentHTTPSTests.integrationTest.<locals>.tlsagent.<locals>.Policy.creatorForNetlocNr  rV   r  rV   rW   PolicyN  s   r  )r  )twisted.web.iwebrF   Zzope.interfacer
   ru   r   r   )r   rF   r
   r  r  rV   rW   tlsagentK  s
    z1AgentHTTPSTests.integrationTest.<locals>.tlsagentr}  )r1  r2  r   N)stripr   r  r  r  r  )rU   r.  r/  r0  ZcertHostNamer  r  r  )r  r  rW   r  B  s    

	
  zAgentHTTPSTests.integrationTest)r   r   )r\   r]   r^   r_   r  r  r  r  r  r  r  r  r  r  r  r  r  __classcell__rV   rV   r  rW   r  s  s"   
	
Or  c                   @   sJ   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Ze	 e_
e_
ee_
dS )WebClientContextFactoryTestszr
    Tests for the context factory wrapper for web clients
    L{twisted.web.client.WebClientContextFactory}.
    c                 C   s&   ddl m} | tjg| _|| _dS )zU
        Get WebClientContextFactory while quashing its deprecation warning.
        r   )WebClientContextFactoryN)twisted.web.clientr  r  r  rl   warnedwebClientContextFactory)rU   r  rV   rV   rW   rl   b  s    z"WebClientContextFactoryTests.setUpc              
   C   s\   |  t| jd | j\}|  |d t |  |d t| jtddddtddd	 d
S )zx
        L{twisted.web.client.WebClientContextFactory} is deprecated.  Importing
        it displays a warning.
        r   r  r  ZTwisted   r   )Zreplacement;:N)	rv   r{   r  r  r,   r  r-   r:   replace)rU   r  rV   rV   rW   test_deprecatedk  s      z,WebClientContextFactoryTests.test_deprecatedc                 C   s   |  t|  jdd dS )zl
        If C{getContext} is called and SSL is not available, raise
        L{NotImplementedError}.
        r   r   N)rf  NotImplementedErrorr  
getContextrT   rV   rV   rW   test_missingSSL  s     z,WebClientContextFactoryTests.test_missingSSLc                 C   s$   |   dd}| |tjj dS )zT
        If SSL is present, C{getContext} returns a L{OpenSSL.SSL.Context}.
        r   r   N)r  r  r   rH   ZSSLZContext)rU   ctxrV   rV   rW   test_returnsContext  s    z0WebClientContextFactoryTests.test_returnsContextc                 C   s(   |   }|dd}| |jtj dS )zd
        The L{CertificateOptions} has C{trustRoot} set to the default trust
        roots.
        r   r   N)r  Z_getCertificateOptionsr   r  rH   ZOpenSSLDefaultPaths)rU   r  ZcertificateOptionsrV   rV   rW   -test_setsTrustRootOnContextToDefaultTrustRoot  s     zJWebClientContextFactoryTests.test_setsTrustRootOnContextToDefaultTrustRootN)r\   r]   r^   r_   rl   r  r  r  r  r  r  skipWhenSSLPresentrV   rV   rV   rW   r  \  s   	r  c                   @   sx   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd ZdS )HTTPConnectionPoolRetryTestsz
    L{client.HTTPConnectionPool}, by using
    L{client._RetryingHTTP11ClientProtocol}, supports retrying requests done
    against previously cached connections.
    c                 C   s   t d}t d|}| |dt d | |dt d | |dt d | |dt d | |dt d | |dt d | |dt d dS )	zO
        Only GET, HEAD, OPTIONS, TRACE, DELETE methods cause a retry.
        Nr  s   HEADs   OPTIONSs   TRACEs   DELETE   POSTs   MYMETHOD)r   r<   _RetryingHTTP11ClientProtocolrm   _shouldRetryr4   assertFalserU   r   r  rV   rV   rW   test_onlyRetryIdempotentMethods  sJ    
              z<HTTPConnectionPoolRetryTests.test_onlyRetryIdempotentMethodsc                 C   s   t d}t d|}| |dt d | |dtg d | |dtg d | |dt	g d | |dt
 d dS )z
        Only L{RequestNotSent}, L{RequestTransmissionFailed} and
        L{ResponseNeverReceived} exceptions cause a retry.
        Nr  )r   r<   r  rm   r  r4   r5   r8   r  r7   r!   r  rV   rV   rW   "test_onlyRetryIfNoResponseReceived  s6    
          z?HTTPConnectionPoolRetryTests.test_onlyRetryIfNoResponseReceivedc                 C   s@   t d}t d|}ttt g}| |d|d dS )z
        If a request failed due to the operation being cancelled,
        C{_shouldRetry} returns C{False} to indicate the request should not be
        retried.
        Nr  )	r   r<   r  r8   r   r   r&   r  r  )rU   r   r  rh  rV   rV   rW   !test_dontRetryIfFailedDueToCancel  s    
z>HTTPConnectionPoolRetryTests.test_dontRetryIfFailedDueToCancelc                 C   s:   t d}t d|}| |dttt gd dS )z
        If a request failed with L{ResponseNeverReceived} due to some
        arbitrary exception, C{_shouldRetry} returns C{True} to indicate the
        request should be retried.
        Nr  )r   r<   r  rm   r  r8   r   	Exceptionr  rV   rV   rW   )test_retryIfFailedDueToNonCancelException  s    
  zFHTTPConnectionPoolRetryTests.test_retryIfFailedDueToNonCancelExceptionc                    sP   t t }t   t  |d  |dt } fdd}|	|S )z
        If L{client.HTTPConnectionPool.getConnection} returns a previously
        cached connection, it will get wrapped in a
        L{client._RetryingHTTP11ClientProtocol}.
        {   c                    s     | tj | j  d S ra   )r   r   r  r   _clientProtocolr  r   rV   rW   r      s    zTHTTPConnectionPoolRetryTests.test_wrappedOnPersistentReturned.<locals>.gotConnection)
r   r<   r   rN   r   r   r   r   r   r   rU   r   r   r   rV   r   rW    test_wrappedOnPersistentReturned  s    z=HTTPConnectionPoolRetryTests.test_wrappedOnPersistentReturnedc                    s.   t d}|dt } fdd}||S )z|
        If L{client.HTTPConnectionPool.getConnection} returns a new
        connection, it will be returned as is.
        Nr  c                    s     | jt d S ra   )r   r  r2   r  rT   rV   rW   r     s    zPHTTPConnectionPoolRetryTests.test_notWrappedOnNewReturned.<locals>.gotConnection)r   r<   r   r   r   r  rV   rT   rW   test_notWrappedOnNewReturned  s    
z9HTTPConnectionPoolRetryTests.test_notWrappedOnNewReturnedc                    s   g fdd}t   tjddt  dd}|  d }t||} fdd	}||_||}td
 td j	d
 |j	d d
 
t  |fS )zP
        Fail a first request, possibly retrying depending on argument.
        c                     s   t  }  |  t| S ra   )rN   rY   r   r%   r   )	protocolsrV   rW   r     s    
z>HTTPConnectionPoolRetryTests.retryAttempt.<locals>.newProtocolr  r  TrI  r   c                    s,    | d |  |ttf S )Nr  )rv   r   r   r4   r8   )mrj  Zbp)rV  rU   willWeRetryrV   rW   r  '  s    z?HTTPConnectionPoolRetryTests.retryAttempt.<locals>._shouldRetryr   )ru   r   r=   r*   r  r  rZ   rv   r{   rR   errbackr4   )rU   r  r   rZ   r   Zretrierr  r   rV   )rV  r	  rU   r  rW   retryAttempt  s     
z)HTTPConnectionPoolRetryTests.retryAttemptc                 C   sJ   |  d\}}| t|d t }|d jd d | || j|S )z
        L{client._RetryingHTTP11ClientProtocol} retries when
        L{client._RetryingHTTP11ClientProtocol._shouldRetry} returns C{True}.
        Tr   r   r   )r  rv   r{   ru   rR   r  r   r   )rU   r   r	  r7  rV   rV   rW   "test_retryIfShouldRetryReturnsTrue9  s
    z?HTTPConnectionPoolRetryTests.test_retryIfShouldRetryReturnsTruec                 C   s*   |  d\}}| t|d | |tS )z
        L{client._RetryingHTTP11ClientProtocol} does not retry when
        L{client._RetryingHTTP11ClientProtocol._shouldRetry} returns C{False}.
        Fr   )r  rv   r{   rX  r4   rU   r   r	  rV   rV   rW   'test_dontRetryIfShouldRetryReturnsFalseF  s    zDHTTPConnectionPoolRetryTests.test_dontRetryIfShouldRetryReturnsFalsec                 C   sH   t d}t d|}| |dt d | |dt t  dS )a  
        L{_RetryingHTTP11ClientProtocol} only retries queries that don't have
        a body.

        This is an implementation restriction; if the restriction is fixed,
        this test should be removed and PUT added to list of methods that
        support retries.
        Nr  )r   r<   r  rm   r  r4   r  ru   r  rV   rV   rW   test_onlyRetryWithoutBodyQ  s    	
z6HTTPConnectionPoolRetryTests.test_onlyRetryWithoutBodyc                 C   sV   |  d\}}| t|d |d jd d tg  | t|d | |tS )z
        If a L{client._RetryingHTTP11ClientProtocol} fails more than once on
        an idempotent query before a response is received, it will not retry.
        Tr   r   r   )r  rv   r{   rR   r  r8   rX  r  rV   rV   rW   test_onlyRetryOnce`  s
    z/HTTPConnectionPoolRetryTests.test_onlyRetryOncec                    sV   t t }d|_t   t  |d  |dt	 } fdd}|
|S )z
        If L{HTTPConnectionPool.retryAutomatically} is set to C{False}, don't
        wrap connections with retrying logic.
        Fr  c                    s    |   d S ra   )r   r  r   rV   rW   r   ~  s    z[HTTPConnectionPoolRetryTests.test_dontRetryIfRetryAutomaticallyFalse.<locals>.gotConnection)r   r<   r   r   rN   r   r   r   r   r   r   r  rV   r   rW   'test_dontRetryIfRetryAutomaticallyFalsen  s    zDHTTPConnectionPoolRetryTests.test_dontRetryIfRetryAutomaticallyFalsec                    st   t t }dt  g fdd}||_t t  | |	 } fdd}|
|S )z
        L{client.HTTPConnectionPool} creates
        {client._RetryingHTTP11ClientProtocol} with a new connection factory
        method that creates a new connection using the same key and endpoint
        as the wrapped connection.
        r  c                    s     | |f d S ra   )rY   )krj  )newConnectionsrV   rW   r     s    zOHTTPConnectionPoolRetryTests.test_retryWithNewConnection.<locals>.newConnectionc                    sl    | tj | j g  |   td d d  d d   d S )Nr   r   )r   r   r  r   r  rv   r   r{   r  r   r   r  r   rU   rV   rW   r     s    zOHTTPConnectionPoolRetryTests.test_retryWithNewConnection.<locals>.gotConnection)r   r<   r   r   r   rN   r   r   r   r   r   )rU   r   r   r   r   rV   r  rW   test_retryWithNewConnection  s    z8HTTPConnectionPoolRetryTests.test_retryWithNewConnectionN)r\   r]   r^   r_   r  r  r   r  r  r  r  r  r  r  r  r  r  rV   rV   rV   rW   r    s   #r  c                   @   s   e Zd ZdZdd ZdS )CookieTestsMixinz4
    Mixin for unit tests dealing with cookies.
    c                 C   s@   t t dddt d|id}t |}||| ||fS )z/
        Add a cookie to a cookie jar.
        r  r  r  
   Set-CookieN)r   Z_FakeUrllib2Responser6   r*   Z_FakeUrllib2RequestZextract_cookies)rU   	cookieJarr:  cookiesr7  rZ   rV   rV   rW   
addCookies  s    
zCookieTestsMixin.addCookiesN)r\   r]   r^   r_   r  rV   rV   rV   rW   r    s   r  c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	CookieJarTestsz
    Tests for L{twisted.web.client._FakeUrllib2Response} and
    L{twisted.web.client._FakeUrllib2Request}'s interactions with
    C{cookielib.CookieJar} instances.
    c                 C   s"   t  }| |dddg}||fS )zL
        @return: a C{cookielib.CookieJar} with some sample cookies
        r  s(   foo=1; cow=moo; Path=/foo; Comment=hellos   bar=2; Comment=goodbye)r   	CookieJarr  )rU   r  ZreqresrV   rV   rW   makeCookieJar  s    zCookieJarTests.makeCookieJarc                 C   s   |   d }tdd |D }|d }| |jd | |jd | |jd | |jd | |jd | |dd	 |d
 }| |jd | |jd
 | |jd | |jd | |jd | 	|dd dS )z
        L{cookielib.CookieJar.extract_cookies} extracts cookie information from
        fake urllib2 response instances.
        r   c                 S   s   g | ]}|j |fqS rV   )name)r   crV   rV   rW   r     s     z6CookieJarTests.test_extractCookies.<locals>.<listcomp>r   1z/fooZhelloZcowZmoobar2/ZgoodbyeN)
r  r+  rv   versionr   r  pathZcommentZget_nonstandard_attrr   )rU   jarr  cookierV   rV   rW   test_extractCookies  s     z"CookieJarTests.test_extractCookiesc                 C   sF   |   \}\}}| |ddd || | |ddd dS )z{
        L{cookielib.CookieJar.add_cookie_header} adds a cookie header to a fake
        urllib2 request instance.
        ZCookieNzfoo=1; bar=2)r  r   Z
get_headerZadd_cookie_headerrv   )rU   r(  rZ   r7  rV   rV   rW   test_sendCookie  s    


zCookieJarTests.test_sendCookieN)r\   r]   r^   r_   r  r*  r+  rV   rV   rV   rW   r    s   r  c                   @   sV   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Ze	e_
dd Zdd Zdd ZdS )CookieAgentTestsz6
    Tests for L{twisted.web.client.CookieAgent}.
    c                 C   s   t | | jt S )zB
        @return: a new L{twisted.web.client.CookieAgent}
        )r   CookieAgentr   r   r   r  rT   rV   rV   rW   r    s    
zCookieAgentTests.makeAgentc                 C   s   |   | _d S ra   )r   r   rT   rV   rV   rW   rl     s    zCookieAgentTests.setUpc              	      s   t   t g  j}t| }|dd} fdd}|	| j
j \}}|jdd tddd	td
dgid}|| |S )a  
        L{CookieAgent.request} does not insert any C{'Cookie'} header into the
        L{Request} object if there is no cookie in the cookie jar for the URI
        being requested. Cookies are extracted from the response and stored in
        the cookie jar.
        r  r  c                    s@   t  }t|d |d jd |d jd d S )Nr   r   r   r"  )listrv   r{   r   r  )Zignoredr  r  rU   rV   rW   _checkCookie   s    zACookieAgentTests.test_emptyCookieJarRequest.<locals>._checkCookie   cookieNr  r  r  r     foo=1)r   r  rv   r.  r   r   r   r-  rZ   r   r   rR   r   r   r,  r-  r6   r*   r  )rU   r   cookieAgentr   r0  ro  rp  r  rV   r/  rW   test_emptyCookieJarRequest  s*     

z+CookieAgentTests.test_emptyCookieJarRequestc                 C   s   d}d}t  }| |||g | tt|d | | j}t	||}|
d| | jj \}}| |jd|g dS )z
        L{CookieAgent.request} inserts a C{'Cookie'} header into the L{Request}
        object when there is a cookie matching the request URI in the cookie
        jar.
        r  r2  r   r  r1  Nr   r  r  rv   r{   r.  r   r   r   r-  rZ   r   rR   r   r,  r-  rU   r:  r)  r  r   r3  ro  rp  rV   rV   rW   test_requestWithCookie6  s    z'CookieAgentTests.test_requestWithCookiec                 C   s   d}d}t  }| |||g | tt|d | | j}t	||}|
d| | jj \}}| |jddg dS )z~
        L{CookieAgent} is able to handle secure cookies, ie cookies which
        should only be handled over https.
        s    https://example.com:1234/foo?bar   foo=1;securer   r  r1  r2  Nr5  r6  rV   rV   rW   test_secureCookieK  s    z"CookieAgentTests.test_secureCookiec                 C   s   d}d}t  }| |||g | tt|d | | j}t	||}|
d| | jj \}}| d|jd dS )zs
        If a cookie is setup as secure, it won't be sent with the request if
        it's not over HTTPS.
        rl  r8  r   r  Nr1  )r   r  r  rv   r{   r.  r   r   r   r-  rZ   r   rR   r   r   r,  r-  r6  rV   rV   rW   %test_secureCookieOnInsecureConnectiona  s    z6CookieAgentTests.test_secureCookieOnInsecureConnectionc                 C   s   d}d}t  }| |||g | tt|d | | j}t	||}|
d| | jj \}}| |jddg dS )zz
        L{CookieAgent} supports cookies which enforces the port number they
        need to be transferred upon.
        r     foo=1;port=1234r   r  r1  r2  Nr5  r6  rV   rV   rW   test_portCookieu  s    z CookieAgentTests.test_portCookiec                 C   s8   d}d}t  }| |||g | tt|d dS )z
        When creating a cookie with a port directive, it won't be added to the
        L{cookie.CookieJar} if the URI is on a different port.
        s   http://example.com:4567/foo?barr;  r   N)r   r  r  rv   r{   r.  )rU   r:  r)  r  rV   rV   rW   test_portCookieOnWrongPort  s
    z+CookieAgentTests.test_portCookieOnWrongPortN)r\   r]   r^   r_   r  rl   r4  r7  r9  r  r  r:  r<  r=  rV   rV   rV   rW   r,    s   	%r,  c                   @   s   e Zd ZdZdS )Decoder1K
    A test decoder to be used by L{client.ContentDecoderAgent} tests.
    Nr\   r]   r^   r_   rV   rV   rV   rW   r>    s   r>  c                   @   s   e Zd ZdZdS )Decoder2r?  Nr@  rV   rV   rV   rW   rA    s   rA  c                   @   sH   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dd Z
dS )ContentDecoderAgentTestsz2
    Tests for L{client.ContentDecoderAgent}.
    c                 C   s   t | jg S )zJ
        @return: a new L{twisted.web.client.ContentDecoderAgent}
        )r   ContentDecoderAgentr   rT   rV   rV   rW   r    s    z"ContentDecoderAgentTests.makeAgentc                 C   s   |   | _| | j| _dS r=  )r   r   r   r   rT   rV   rV   rW   rl     s    
zContentDecoderAgentTests.setUpc                 C   sf   t | jdtfdtfg}|dd | j}| t|j	d |j	
 \}}| |jddg dS )	z
        L{client.ContentDecoderAgent} sets the I{Accept-Encoding} header to the
        names of the available decoder objects.
           decoder1   decoder2r  rv  r      accept-encoding   decoder1,decoder2N)r   rC  r   r>  rA  rZ   r   rv   r{   rR   r   r,  r-  )rU   r   r   ro  rp  rV   rV   rW   test_acceptHeaders  s     z+ContentDecoderAgentTests.test_acceptHeadersc                 C   s   t dgdgd}t| jdtfdtfg}|jdd|d | j}| 	t
|jd	 |j \}}| 	tt|j d
ddgfddgfddgfg dS )z
        If there are existing I{Accept-Encoding} fields,
        L{client.ContentDecoderAgent} creates a new field for the decoders it
        knows about.
        rs     fizz)rL  rF  rD  rE  r  rv  r,  r   s   Accept-EncodingrG     Foor&  r   N)r   r*   r   rC  r   r>  rA  rZ   r   rv   r{   rR   r   r.  sortedr,  getAllRawHeaders)rU   r,  r   r   ro  rp  rV   rV   rW   test_existingHeaders  s$     
z-ContentDecoderAgentTests.test_existingHeadersc                 C   sb   t | jdtfdtfg}|dd}| jj \}}t	dddt
 d}|| || j|S )	z
        If the response is not encoded despited the request I{Accept-Encoding}
        headers, L{client.ContentDecoderAgent} simply forwards the response.
        rD  rE  r  rv  r  r  r  N)r   rC  r   r>  rA  rZ   r   rR   r   r6   r   r*   r  r   r   )rU   r   r3  ro  rp  r7  rV   rV   rW   test_plainEncodingResponse  s     
z3ContentDecoderAgentTests.test_plainEncodingResponsec                 C   sr   t | jdtfdtfg}|dd}| jj \}}t	
dgdgd}tdd	d
|d}|| || j|S )zz
        If an encoding unknown to the L{client.ContentDecoderAgent} is found,
        the response is unchanged.
        rD  rE  r  rv  rs  rI  rL     content-encodingr  r  r  N)r   rC  r   r>  rA  rZ   r   rR   r   r   r*   r6   r  r   r   )rU   r   r3  ro  rp  r,  r7  rV   rV   rW   test_unsupportedEncoding  s     
z1ContentDecoderAgentTests.test_unsupportedEncodingc                    s|   t jdtfdtfg}|dd}jj \}}t	
dgdgd}tdd	d
|d |   fdd}||S )z
        When L{client.ContentDecoderAgent} encounters a decoder it doesn't know
        about, it stops decoding even if another encoding is known afterwards.
        rD  rE  r  rv  rs  s   decoder1,fizz,decoder2rP  r  r  r  Nc                    s2     |  | t dg| jd d S )Ns   decoder1,fizzrQ  )r   r   rA  rv   r,  r-  r[   r7  rU   rV   rW   check	  s
    
z<ContentDecoderAgentTests.test_unknownEncoding.<locals>.check)r   rC  r   r>  rA  rZ   r   rR   r   r   r*   r6   r  r   )rU   r   r3  ro  rp  r,  rU  rV   rT  rW   test_unknownEncoding	  s     
z-ContentDecoderAgentTests.test_unknownEncodingN)r\   r]   r^   r_   r  rl   rH  rN  rO  rR  rV  rV   rV   rV   rW   rB    s   rB  c                   @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )SimpleAgentProtocola
  
    A L{Protocol} to be used with an L{client.Agent} to receive data.

    @ivar finished: L{Deferred} firing when C{connectionLost} is called.

    @ivar made: L{Deferred} firing when C{connectionMade} is called.

    @ivar received: C{list} of received data.
    c                 C   s   t  | _t  | _g | _d S ra   )r$   madefinishedreceivedrT   rV   rV   rW   rX   -	  s    zSimpleAgentProtocol.__init__c                 C   s   | j d  d S ra   )rX  r  rT   rV   rV   rW   connectionMade3	  s    z"SimpleAgentProtocol.connectionMadec                 C   s   | j d  d S ra   )rY  r  )rU   reasonrV   rV   rW   r
  7	  s    z"SimpleAgentProtocol.connectionLostc                 C   s   | j | d S ra   )rZ  rY   rU   r)  rV   rV   rW   dataReceived;	  s    z SimpleAgentProtocol.dataReceivedN)r\   r]   r^   r_   rX   r[  r
  r^  rV   rV   rV   rW   rW  "	  s
   
rW  c                   @   s4   e Zd Zdd Zdd Zdd Zdd Zd	d
 ZdS ) ContentDecoderAgentWithGzipTestsc                 C   s0   |   | _| | j}t|dtjfg| _dS )r>     gzipN)r   r   r   r   rC  ZGzipDecoderr   rB  rV   rV   rW   rl   C	  s    
 
z&ContentDecoderAgentWithGzipTests.setUpc                    s   j dd}jj \}}tdgdgd}t }tddd||d	_	|
 td
tjdtj }|d|d |    fdd}|| |S )z
        If the response has a C{gzip} I{Content-Encoding} header,
        L{GzipDecoder} wraps the response to return uncompressed data to the
        user.
        r  rv  rs  r`  rP  r  r  r     r      s   xxxxxxs   yyyyc                    s    |  | jd | jd | jd t| j ddgfg | jt	 
tt| d  d d   dd     t }| | |jdg t|j|jgS )	Nr  r  r  rK  rs  unknownrz   s
   xxxxxxyyyy)r   rv   r&  codephraser.  r,  rM  rw   rB   rf  AttributeErrorgetattr_bodyDataReceived_bodyDataFinishedrW  deliverBodyrZ  r   gatherResultsrX  rY  r[   r   r)  r7  rU   rV   rW   checkResponseb	  s     

zQContentDecoderAgentWithGzipTests.test_gzipEncodingResponse.<locals>.checkResponse)r   rZ   r   rR   r   r   r*   r   r6   rw   r  zlibZcompressobjZDEFLATEDZ	MAX_WBITScompressr(  r   )rU   r3  ro  rp  r,  r   Z
compressorrn  rV   rm  rW   test_gzipEncodingResponseM	  s     

z:ContentDecoderAgentWithGzipTests.test_gzipEncodingResponsec                    s   j dd}jj \}}tdgdgd}t }tddd||d	_	|
 d
  fdd}|| |tj fdd}||S )z
        If the data received by the L{GzipDecoder} isn't valid gzip-compressed
        data, the call to C{deliverBody} fails with a C{zlib.error}.
        r  rv  rs  r`  rP  r  r  r  ra  s   not gzipped contentc                    s      | t  d S ra   )rh  rj  r"   rS  )r)  r7  rV   rW   rn  	  s    
zJContentDecoderAgentWithGzipTests.test_brokenContent.<locals>.checkResponsec                    s$   | j d tj  | jt d S )Nr   reasonsr   ro  r   r   r7  r6   r   rT   rV   rW   checkFailure	  s    zIContentDecoderAgentWithGzipTests.test_brokenContent.<locals>.checkFailure)r   rZ   r   rR   r   r   r*   r   r6   rw   r  r   rX  r   r7   )rU   r3  ro  rp  r,  r   rn  ru  rV   rm  rW   test_brokenContent{	  s    

z3ContentDecoderAgentWithGzipTests.test_brokenContentc           	         s   G dd dt }tj}|t_ttd| jdd}jj	 \}}t
ddgi}t }tddd	|| |   fd
d}|| |S )z
        When the connection with the server is lost, the gzip protocol calls
        C{flush} on the zlib decompressor object to get uncompressed data which
        may have been buffered.
        c                   @   s$   e Zd Zdd Zdd Zdd ZdS )zFContentDecoderAgentWithGzipTests.test_flushData.<locals>.decompressobjc                 S   s   d S ra   rV   rU   ZwbitsrV   rV   rW   rX   	  s    zOContentDecoderAgentWithGzipTests.test_flushData.<locals>.decompressobj.__init__c                 S   s   dS N   xrV   r]  rV   rV   rW   
decompress	  s    zQContentDecoderAgentWithGzipTests.test_flushData.<locals>.decompressobj.decompressc                 S   s   dS )N   yrV   rT   rV   rV   rW   r(  	  s    zLContentDecoderAgentWithGzipTests.test_flushData.<locals>.decompressobj.flushNr\   r]   r^   rX   rz  r(  rV   rV   rV   rW   decompressobj	  s   r}  r  rv  rQ  r`  r  r  r  c                    sF     d    t }| | |jddg t|j|j	gS Ns   datary  r{  
rh  ri  rW  rj  rv   rZ  r   rk  rX  rY  rl  rT  rV   rW   rn  	  s    

zFContentDecoderAgentWithGzipTests.test_flushData.<locals>.checkResponse)ru   ro  r}  
addCleanupsetattrr   rZ   r   rR   r   r   r*   r   r6   r  r   )	rU   r}  oldDecompressObjr3  ro  rp  r,  r   rn  rV   rT  rW   test_flushData	  s    


z/ContentDecoderAgentWithGzipTests.test_flushDatac           
         s   G dd dt }tj}|t_ttd| jdd}jj	 \}}t
ddgi}t }tddd	|| |   fd
d}|| |tj fdd}	||	S )z
        If the C{flush} call in C{connectionLost} fails, the C{zlib.error}
        exception is caught and turned into a L{ResponseFailed}.
        c                   @   s$   e Zd Zdd Zdd Zdd ZdS )zGContentDecoderAgentWithGzipTests.test_flushError.<locals>.decompressobjc                 S   s   d S ra   rV   rw  rV   rV   rW   rX   	  s    zPContentDecoderAgentWithGzipTests.test_flushError.<locals>.decompressobj.__init__c                 S   s   dS rx  rV   r]  rV   rV   rW   rz  	  s    zRContentDecoderAgentWithGzipTests.test_flushError.<locals>.decompressobj.decompressc                 S   s   t  d S ra   )ro  r   rT   rV   rV   rW   r(  	  s    zMContentDecoderAgentWithGzipTests.test_flushError.<locals>.decompressobj.flushNr|  rV   rV   rV   rW   r}  	  s   r}  r  rv  rQ  r`  r  r  r  c                    sF     d    t }| | |jddg t|j|j	gS r~  r  rl  rT  rV   rW   rn  	  s    

zGContentDecoderAgentWithGzipTests.test_flushError.<locals>.checkResponsec                    s$   | j d tj  | jt d S )Nr   rr  rt  rT   rV   rW   ru  	  s    zFContentDecoderAgentWithGzipTests.test_flushError.<locals>.checkFailure)ru   ro  r}  r  r  r   rZ   r   rR   r   r   r*   r   r6   r  r   rX  r   r7   )
rU   r}  r  r3  ro  rp  r,  r   rn  ru  rV   rT  rW   test_flushError	  s    


z0ContentDecoderAgentWithGzipTests.test_flushErrorN)r\   r]   r^   rl   rq  rv  r  r  rV   rV   rV   rW   r_  @	  s
   
.!.r_  c                   @   s8   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d ZdS )ProxyAgentTestsz)
    Tests for L{client.ProxyAgent}.
    c                 C   s   t t| jdd| jS )zA
        @return: a new L{twisted.web.client.ProxyAgent}
        z	127.0.0.1r\  )r   
ProxyAgentr'   r   rT   rV   rV   rW   r  
  s    zProxyAgentTests.makeAgentc                 C   s@   |   | _tt| jdd| j| _| jj}| || | j_d S )Nr#  .  )r   r   r   r  r'   r   Z_proxyEndpointr   )rU   ZoldEndpointrV   rV   rW   rl   
  s    
 zProxyAgentTests.setUpc           	      C   s   t ddgi}t }| jdd|| | jj dd \}}}| |d | |d | 	|j
tj | j}| t|jd	 |j \}}| 	|t | |jd | |jd | |jt dgd
gd | |j| dS )z
        L{client.ProxyAgent} issues an HTTP request against the proxy, with the
        full URI as path, when C{request} is called.
        rL  rs  r  r  Nr   r#  r  r   r  rt  )r   r*   ru   r   rZ   r   r   r   rv   r   Z_wrappedFactoryr   r?   r   r{   rR   r=   r  r:  r,  r   rV  )	rU   r,  r  r   r   r   r   ro  rp  rV   rV   rW   test_proxyRequest
  s6       z!ProxyAgentTests.test_proxyRequestc                 C   s   |  | jjjd dS )zJ
        C{ProxyAgent} connections are not persistent by default.
        FN)rv   r   r@  r   rT   rV   rV   rW   rJ  5
  s    z"ProxyAgentTests.test_nonPersistentc                    sb   t   G  fdddt}| }tj j|d}||j |dd |jj	d dS )z
        When a connection is made by the C{ProxyAgent}, it uses its pool's
        C{getConnection} method to do so, with the endpoint it was constructed
        with and a key of C{("http-proxy", endpoint)}.
        c                       s"   e Zd ZdZdZ fddZdS )zAProxyAgentTests.test_connectUsesConnectionPool.<locals>.DummyPoolFc                    s.   d| _ |  |d f tt S )NTz
http-proxy)rP  r   rv   r   r%   rN   rQ  rN  rV   rW   r   F
  s    zOProxyAgentTests.test_connectUsesConnectionPool.<locals>.DummyPool.getConnectionNrR  rV   rN  rV   rW   rS  C
  s   rS  rD  r  rU  TN)
r   ru   r   r  r   r   r@  rZ   rv   rP  )rU   rS  r   r   rV   rN  rW   rW  <
  s    z.ProxyAgentTests.test_connectUsesConnectionPoolN)	r\   r]   r^   r_   r  rl   r  rJ  rW  rV   rV   rV   rW   r  	  s   	"r     authorizationr1     cookie2   proxy-authorizations   www-authenticatec                   @   s  e Zd ZU dZeed< eed< eed< dd Zd5e	e
e
e
ee ed	d
dZdd Zdd Zdd Zdd Zd6ee
ddddZddddZddddZddddZdd  Zd!d" Zd#d$ Zd%d& Zd'd( Zd)d* Zd+d, Zd-d. Zd/d0 Z d1d2 Z!d3d4 Z"dS )7_RedirectAgentTestsMixinz^
    Test cases mixin for L{RedirectAgentTests} and
    L{BrowserLikeRedirectAgentTests}.
    r   r   r   c                 C   s|   | j dd}| jj \}}t }tddd|d}|| | 	dt
| jj | |}| || | |jd dS )zz
        L{client.RedirectAgent} behaves like L{client.Agent} if the response
        doesn't contain a redirect.
        r  rv  r  r  r  Nr   )r   rZ   r   rR   r   r   r*   r6   r  rv   r{   r   r   previousResponse)rU   r3  ro  rp  r,  r7  r[   rV   rV   rW   test_noRedirectj
  s    

z(_RedirectAgentTestsMixin.test_noRedirectFN)rd  crossSchemecrossDomain	crossPortrequestHeadersrP   c                 C   s  d}t dk	rdnd}|dkr dnd}| jjd|d | d	 |d
 | jj dd \}	}
| t|	 | ||
 | jj	 \}}|}|}|}|rt dkrt
d|dkrdnd}|dkrdnd}d}|rd}d}|rdn|}|d | | d }td|gi}td|d|d}|| | jj	 \}}| d|j | d|j | jj dd \}	}
| |rntnt|	 | ||
 |S )z
        When getting a redirect, L{client.RedirectAgent} follows the URL
        specified in the L{Location} header field and make a new request.

        @param code: HTTP status code.
        r   Nr}  r  r   r   r  r  s   /foorJ  r   z;Cross-scheme redirects can't be tested without TLS support.rh   i   s   :8443   example.net   /bar   locationr  r  )rH   r   rZ   r   r   r   rv   r   r   rR   r   r   r*   r6   r  r  r:  r   )rU   rd  r  r  r  r  ZstartDomainZstartSchemeZ	startPortr   r   ro  rp  ZtargetSchemeZtargetDomainZ
targetPortZ
portSyntaxZlocationValuer,  r7  req2res2rV   rV   rW   _testRedirectDefault}
  sL      
z-_RedirectAgentTestsMixin._testRedirectDefaultc                 C   s   |  d dS )zO
        L{client.RedirectAgent} follows redirects on status code 301.
        -  Nr  rT   rV   rV   rW   test_redirect301
  s    z)_RedirectAgentTestsMixin.test_redirect301c                 C   s   | j ddd dS )zI
        L{client.RedirectAgent} follows cross-scheme redirects.
        r  Tr  Nr  rT   rV   rV   rW   test_redirect301Scheme
  s    z/_RedirectAgentTestsMixin.test_redirect301Schemec                 C   s   |  d dS )zO
        L{client.RedirectAgent} follows redirects on status code 302.
        .  Nr  rT   rV   rV   rW   test_redirect302
  s    z)_RedirectAgentTestsMixin.test_redirect302c                 C   s   |  d dS )zO
        L{client.RedirectAgent} follows redirects on status code 307.
        3  Nr  rT   rV   rV   rW   test_redirect307
  s    z)_RedirectAgentTestsMixin.test_redirect307r   )expectedHostHeadercrossKwargsrP   c                 K   s   dgdgdgdgdgdgd}dd	gi}t ||}| jd
|d}t tddd}||j}| |ddgi|| | jd|dt ||i}	||	j}
| |
d|gi|t | dS )zv
        L{client.RedirectAgent} scrubs sensitive headers when redirecting
        between differing origins.
        s   sensitive-authnzs   sensitive-cookie-datas   sensitive-cookie2-datas   sensitive-proxy-auths   sensitive-authns   sensitive-custom)r  r1  r  r  s   wWw-auThentiCates   x-custom-sensitives   x-random-headers   x-random-valuer  )r  )r,  rP   c                 S   s   dd |   D S )Nc                 S   s   i | ]\}}|  |qS rV   )lower)r   r  vrV   rV   rW   
<dictcomp>
  s      zW_RedirectAgentTestsMixin._sensitiveHeadersTest.<locals>.normHeaders.<locals>.<dictcomp>)rM  rJ  rV   rV   rW   normHeaders
  s    zC_RedirectAgentTestsMixin._sensitiveHeadersTest.<locals>.normHeadersrT  r   r  N)r  )r*   r  r+  r,  r  )rU   r  r  ZsensitiveHeaderValuesZotherHeaderValuesZ
allHeadersZ
redirectedr  ZsameOriginHeadersZredirectedElsewhereZotherOriginHeadersrV   rV   rW   _sensitiveHeadersTest
  sH    

  

 
z._RedirectAgentTestsMixin._sensitiveHeadersTestrO   c                 C   s   | j ddd dS )zv
        L{client.RedirectAgent} scrubs sensitive headers when redirecting
        between differing domains.
        Tr  )r  r  Nr  rT   rV   rV   rW   test_crossDomainHeaders  s    z0_RedirectAgentTestsMixin.test_crossDomainHeadersc                 C   s   | j ddd dS )zt
        L{client.RedirectAgent} scrubs sensitive headers when redirecting
        between differing ports.
        Ts   example.com:8443)r  r  Nr  rT   rV   rV   rW   test_crossPortHeaders  s     z._RedirectAgentTestsMixin.test_crossPortHeadersc                 C   s   | j dd dS )zv
        L{client.RedirectAgent} scrubs sensitive headers when redirecting
        between differing schemes.
        Tr  Nr  rT   rV   rV   rW   test_crossSchemeHeaders  s    z0_RedirectAgentTestsMixin.test_crossSchemeHeadersc           	      C   sx   | j |d | jj \}}tddgi}td|d|d}|| | jj \}}| 	d|j
 | 	d|j dS )	z
        L{client.RedirectAgent} changes the method to I{GET} when getting
        a redirect on a non-I{GET} request.

        @param code: HTTP status code.

        @param method: HTTP request method.
        rv  r     http://example.com/barr  r  Nr  r  )r   rZ   r   rR   r   r   r*   r6   r  rv   r  r:  )	rU   rd  r  ro  rp  r,  r7  r  r  rV   rV   rW   _testRedirectToGet  s    	
z+_RedirectAgentTestsMixin._testRedirectToGetc                 C   s   |  dd dS )z
        L{client.RedirectAgent} changes the method to I{GET} when getting a 303
        redirect on a I{POST} request.
        i/  r  Nr  rT   rV   rV   rW   test_redirect3035  s    z)_RedirectAgentTestsMixin.test_redirect303c                 C   s   | j dd}| jj \}}t }tddd|d}|| | 	|t
j}|jjd tj | d|jjd jj | d|jjj dS )z
        If no L{Location} header field is found when getting a redirect,
        L{client.RedirectAgent} fails with a L{ResponseFailed} error wrapping a
        L{error.RedirectWithNoLocation} exception.
        r  rv  r  r  r  Nr   )r   rZ   r   rR   r   r   r*   r6   r  r   r   r7   r  rs  r   r   ZRedirectWithNoLocationrv   r:  r7  rd  )rU   r3  ro  rp  r,  r7  failrV   rV   rW   test_noLocationField=  s    
z-_RedirectAgentTestsMixin.test_noLocationFieldc           	      C   s   | j |d}| jj \}}t }td|d|d}|| | 	|t
j}|jjd tj | d|jjd jj | ||jjj dS )a  
        When getting a redirect on an unsupported request method,
        L{client.RedirectAgent} fails with a L{ResponseFailed} error wrapping
        a L{error.PageRedirect} exception.

        @param code: HTTP status code.

        @param method: HTTP request method.
        rv  r  r  Nr   )r   rZ   r   rR   r   r   r*   r6   r  r   r   r7   r  rs  r   r   ZPageRedirectrv   locationr7  rd  )	rU   rd  r  r3  ro  rp  r,  r7  r  rV   rV   rW   _testPageRedirectFailureR  s    

z1_RedirectAgentTestsMixin._testPageRedirectFailurec                 C   s   |  dd dS )z
        When getting a 307 redirect on a I{POST} request,
        L{client.RedirectAgent} fails with a L{ResponseFailed} error wrapping
        a L{error.PageRedirect} exception.
        r  r  Nr  rT   rV   rV   rW   test_307OnPostk  s    z'_RedirectAgentTestsMixin.test_307OnPostc                 C   s   |  | j}t|d}|dd}| jj \}}t	ddgi}t
ddd|d	}|| | jj \}}	t
ddd|d	}
|	|
 | |tj}|jjd
 tj | d|jjd
 jj | d|jjj d	S )z
        If the limit of redirects specified to L{client.RedirectAgent} is
        reached, the deferred fires with L{ResponseFailed} error wrapping
        a L{InfiniteRedirection} exception.
        r   r  rv  r  r  r  r  r  Nr   )r   r   r   RedirectAgentrZ   r   rR   r   r   r*   r6   r  r   r7   r  rs  r   r   ZInfiniteRedirectionrv   r  r7  rd  )rU   r   redirectAgentr3  ro  rp  r,  r7  r  r  Z	response2r  rV   rV   rW   test_redirectLimitt  s$    

z+_RedirectAgentTestsMixin.test_redirectLimitc           
      C   sx   | j d| | jj \}}td|gi}tddd|d}|| | jj \}}	| 	d|j
 | 	||j dS )a1  
        When L{client.RedirectAgent} encounters a relative redirect I{URI}, it
        is resolved against the request I{URI} before following the redirect.

        @param uri: Request URI.

        @param location: I{Location} header redirect URI.

        @param finalURI: Expected final URI.
        r  r  r  r  r  N)r   rZ   r   rR   r   r   r*   r6   r  rv   r  r  )
rU   r:  r  ZfinalURIro  rp  r,  r7  r  r  rV   rV   rW   _testRedirectURI  s    
z)_RedirectAgentTestsMixin._testRedirectURIc                 C   s.   |  ddd |  ddd |  ddd dS )	z
        L{client.RedirectAgent} resolves and follows relative I{URI}s in
        redirects, preserving query strings.
           http://example.com/foo/bars   bazs   http://example.com/foo/bazs   /bazs   http://example.com/baz   /baz?as   http://example.com/baz?aNr  rT   rV   rV   rW   test_relativeURI  s       z)_RedirectAgentTestsMixin.test_relativeURIc                 C   s    |  ddd |  ddd dS )a  
        L{client.RedirectAgent} resolves and follows relative I{URI}s in
        redirects, preserving fragments in way that complies with the HTTP 1.1
        bis draft.

        @see: U{https://tools.ietf.org/html/draft-ietf-httpbis-p2-semantics-22#section-7.1.2}
        s   http://example.com/foo/bar#fragr  s   http://example.com/baz?a#fragr  s   /baz?a#frag2s   http://example.com/baz?a#frag2Nr  rT   rV   rV   rW   !test_relativeURIPreserveFragments  s      z:_RedirectAgentTestsMixin.test_relativeURIPreserveFragmentsc                 C   s    |  ddd |  ddd dS )z
        L{client.RedirectAgent} resolves and follows scheme relative I{URI}s in
        redirects, replacing the hostname and port when required.
        r  s   //foo.com/bazs   http://foo.com/bazs   //foo.com:81/bazs   http://foo.com:81/bazNr  rT   rV   rV   rW   test_relativeURISchemeRelative  s      z7_RedirectAgentTestsMixin.test_relativeURISchemeRelativec                 C   s   |  | j}t|}|dd}| jj \}}t	ddgi}t
ddd|d}|| | jj \}}	t
dd	d|d}
|	|
 | |}| |j| | |jd dS )
z
        L{Response.response} references the previous L{Response} from
        a redirect, or L{None} if there was no previous response.
        r  rv  r  r  r  r  r  Nr  )r   r   r   r  rZ   r   rR   r   r   r*   r6   r  r   r   r  )rU   r   r  r3  ZredirectReqZredirectResr,  ZredirectResponsero  rp  r7  ZfinalResponserV   rV   rW   test_responseHistory  s    



z-_RedirectAgentTestsMixin.test_responseHistory)FFFN)r   )#r\   r]   r^   r_   rC   __annotations__r   rN   r  intboolr   r*   r=   r  r  r  r  r  rd   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  rV   rV   rV   rW   r  `
  sR   
    ?	  -		r  c                   @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )RedirectAgentTestsz,
    Tests for L{client.RedirectAgent}.
    c                 C   s   t j| | jdgdS )zD
        @return: a new L{twisted.web.client.RedirectAgent}
        s   X-Custom-sensitiveZsensitiveHeaderNames)r   r  r   r   rT   rV   rV   rW   r    s    
zRedirectAgentTests.makeAgentc                 C   s   |   | _|  | _d S ra   r?  rT   rV   rV   rW   rl     s    
zRedirectAgentTests.setUpc                 C   s   |  dd dS )z
        When getting a 301 redirect on a I{POST} request,
        L{client.RedirectAgent} fails with a L{ResponseFailed} error wrapping
        a L{error.PageRedirect} exception.
        r  r  Nr  rT   rV   rV   rW   test_301OnPost  s    z!RedirectAgentTests.test_301OnPostc                 C   s   |  dd dS )z
        When getting a 302 redirect on a I{POST} request,
        L{client.RedirectAgent} fails with a L{ResponseFailed} error wrapping
        a L{error.PageRedirect} exception.
        r  r  Nr  rT   rV   rV   rW   test_302OnPost  s    z!RedirectAgentTests.test_302OnPostN)r\   r]   r^   r_   r  rl   r  r  rV   rV   rV   rW   r    s
   
	r  c                   @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )BrowserLikeRedirectAgentTestsz7
    Tests for L{client.BrowserLikeRedirectAgent}.
    c                 C   s   t j| | jdgdS )zO
        @return: a new L{twisted.web.client.BrowserLikeRedirectAgent}
        s   x-Custom-sensitiver  )r   ZBrowserLikeRedirectAgentr   r   rT   rV   rV   rW   r  )  s    
z'BrowserLikeRedirectAgentTests.makeAgentc                 C   s   |   | _|  | _d S ra   r?  rT   rV   rV   rW   rl   3  s    
z#BrowserLikeRedirectAgentTests.setUpc                 C   s   |  dd dS )
        L{client.BrowserLikeRedirectAgent} changes the method to I{GET} when
        getting a 302 redirect on a I{POST} request.
        r  r  Nr  rT   rV   rV   rW   test_redirectToGet3018  s    z3BrowserLikeRedirectAgentTests.test_redirectToGet301c                 C   s   |  dd dS )r  r  r  Nr  rT   rV   rV   rW   test_redirectToGet302@  s    z3BrowserLikeRedirectAgentTests.test_redirectToGet302N)r\   r]   r^   r_   r  rl   r  r  rV   rV   rV   rW   r     s
   
r  c                   @   s   e Zd ZdZdZdd ZdS )AbortableStringTransportzK
    A version of L{StringTransport} that supports C{abortConnection}.
    Fc                 C   s   d| _ |   dS )z
        A testable version of the C{ITCPTransport.abortConnection} method.

        Since this is a special case of closing the connection,
        C{loseConnection} is also called.
        TN)abortingZloseConnectionrT   rV   rV   rW   abortConnectionQ  s    z(AbortableStringTransport.abortConnectionN)r\   r]   r^   r_   r  r  rV   rV   rV   rW   r  I  s   r  c                   @   s.   e Zd ZdZdZdZdefddZdd ZdS )	DummyResponsea  
    Fake L{IResponse} for testing readBody that captures the protocol passed to
    deliverBody and uses it to make a connection with a transport.

    @ivar protocol: After C{deliverBody} is called, the protocol it was called
        with.

    @ivar transport: An instance created by calling C{transportFactory} which
        is used by L{DummyResponse.protocol} to make a connection.
    r  r  Nc                 C   s    |dkrt  }|| _| | _dS )z
        @param headers: The headers for this response.  If L{None}, an empty
            L{Headers} instance will be used.
        @type headers: L{Headers}

        @param transportFactory: A callable used to construct the transport.
        N)r*   r,  r   )rU   r,  transportFactoryrV   rV   rW   rX   l  s    zDummyResponse.__init__c                 C   s   || _ | j | j dS )zt
        Record the given protocol and use it to make a connection with
        L{DummyResponse.transport}.
        Nr   r   r   r   rV   rV   rW   rj  z  s    zDummyResponse.deliverBody)	r\   r]   r^   r_   rd  re  r  rX   rj  rV   rV   rV   rW   r  ]  s
   r  c                   @   s   e Zd ZdZdd ZdS )AlreadyCompletedDummyResponsezE
    A dummy response that has already had its transport closed.
    c                 C   s    || _ | j | j d| j _dS )zA
        Make the connection, then remove the transport.
        Nr  r   rV   rV   rW   rj    s    z)AlreadyCompletedDummyResponse.deliverBodyN)r\   r]   r^   r_   rj  rV   rV   rV   rW   r    s   r  c                   @   s@   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dS )ReadBodyTestsz&
    Tests for L{client.readBody}
    c                 C   sP   t  }t|}|jd |jd |jtt  | | 	|d dS )z
        L{client.readBody} returns a L{Deferred} which fires with the complete
        body of the L{IResponse} provider passed to it.
           first   second   firstsecondN)
r  r   readBodyr   r^  r
  r   r>   rv   r   )rU   r7  r   rV   rV   rW   test_success  s    
zReadBodyTests.test_successc                 C   s8   t  }t|}|  | |tj | |jj	 dS )z
        When cancelling the L{Deferred} returned by L{client.readBody}, the
        connection to the server will be aborted.
        N)
r  r   r  r  r   r   r&   rm   r   r  )rU   r7  r3  rV   rV   rW   test_cancel  s
    
zReadBodyTests.test_cancelc                 C   s|   t  }t|}|jd |jd |jtt  | |}|	tj
 | |jj|jj|jjddddd dS )a  
        If the full body of the L{IResponse} passed to L{client.readBody} is
        not definitely received, the L{Deferred} returned by L{client.readBody}
        fires with a L{Failure} wrapping L{client.PartialDownloadError} with
        the content that was received.
        r  r  )statusr  r  s   200r  r  N)r  r   r  r   r^  r
  r   r3   r   r   ZPartialDownloadErrorrv   r  r  r  r7  )rU   r7  r   ZfailurerV   rV   rW   test_withPotentialDataLoss  s"    

z(ReadBodyTests.test_withPotentialDataLossc                 C   sX   t  }t|}|jd |jttd | |}|	t | 
|jjd dS )z
        If there is an exception other than L{client.PotentialDataLoss} while
        L{client.readBody} is collecting the response body, the L{Deferred}
        returned by {client.readBody} fires with that exception.
        r  mystery problem)r  N)r  r   r  r   r^  r
  r   r    r   r   rv   r  r   )rU   r7  r   r\  rV   rV   rW   test_otherErrors  s    



zReadBodyTests.test_otherErrorsc                    sD   t td d j_| tdt fdd}|  | |t	j
 dS )z
        Calling L{client.readBody} with a transport that does not implement
        L{twisted.internet.interfaces.ITCPTransport} produces a deprecation
        warning, but no exception when cancelling.
        )r  NzLUsing readBody with a transport that does not have an abortConnection methodc                      s
   t  S ra   )r   r  rV   r7  rV   rW   rg     rh   z8ReadBodyTests.test_deprecatedTransport.<locals>.<lambda>)r  r   r   r  ZassertWarnsr  __file__r  r   r   r&   )rU   r   rV   r  rW   test_deprecatedTransport  s    

z&ReadBodyTests.test_deprecatedTransportc                 C   s,   t  }t| |  }| t|d dS )z
        Calling L{client.readBody} with a response that has already had its
        transport closed (eg. for a very small request) will not trigger a
        deprecation warning.
        r   N)r  r   r  r  rv   r{   )rU   r7  r  rV   rV   rW   !test_deprecatedTransportNoWarning  s    
z/ReadBodyTests.test_deprecatedTransportNoWarningN)
r\   r]   r^   r_   r  r  r  r  r  r  rV   rV   rV   rW   r    s   r  c                   @   s   e Zd ZdZdd ZdS )RequestMethodInjectionTestsz@
    Test L{client.Request} against HTTP method injections.
    c                 C   s   t j|dt dd dS )r  r  Nr  r:  r,  rV  r   r=   r   r*   )rU   r  rV   rV   rW   r     s    z=RequestMethodInjectionTests.attemptRequestWithMaliciousMethodNr  rV   rV   rV   rW   r    s   r  c                   @   s   e Zd ZdZdd ZdS )"RequestWriteToMethodInjectionTestsH
    Test L{client.Request.writeTo} against HTTP method injections.
    c                 C   s8   t ddgi}tjdd|dd}||_|t  dS )r  r&     twisted.invalidr  r  Nr  )r   r*   r   r=   r  writeTor   )rU   r  r,  ro  rV   rV   rW   r    s    zDRequestWriteToMethodInjectionTests.attemptRequestWithMaliciousMethodNr  rV   rV   rV   rW   r    s   r  c                   @   s   e Zd ZdZdd ZdS )RequestURIInjectionTestsz=
    Test L{client.Request} against HTTP URI injections.
    c                 C   s   t jd|t dd dS )zp
        Attempt a request with the provided URI.

        @param method: see L{URIInjectionTestsMixin}
        r  Nr  r  r9  rV   rV   rW   r  1  s    z7RequestURIInjectionTests.attemptRequestWithMaliciousURINr  rV   rV   rV   rW   r  )  s   r  c                   @   s   e Zd ZdZdd ZdS )RequestWriteToURIInjectionTestsr  c                 C   s8   t ddgi}tjdd|dd}||_|t  dS )zs
        Attempt a request with the provided method.

        @param method: see L{URIInjectionTestsMixin}
        r&  r  r  r  Nr  )r   r*   r   r=   r:  r  r   )rU   r:  r,  ro  rV   rV   rW   r  H  s    z>RequestWriteToURIInjectionTests.attemptRequestWithMaliciousURINr  rV   rV   rV   rW   r  @  s   r  )r_   ro  ior   typingr   r   r   r   Zunittestr   r   Zzope.interface.declarationsr
   Zzope.interface.verifyr   Ztwisted.trial.unittestr   r   Ztwisted.webr   r   r   Ztwisted.internetr   r   Ztwisted.python.failurer   Ztwisted.test.iosimr   r   Ztwisted.test.proto_helpersr   r   r   r   Ztwisted.test.test_sslverifyr   Ztwisted.python.compatr   r   Ztwisted.python.componentsr   Ztwisted.internet.taskr   Ztwisted.internet.errorr   r    r!   Ztwisted.internet.protocolr"   r#   Ztwisted.internet.deferr$   r%   r&   r  r'   Ztwisted.internet.addressr(   r)   Ztwisted.web.http_headersr*   Ztwisted.internet.interfacesr+   Ztwisted.python.deprecater,   Zincrementalr-   Z$twisted.internet.test.test_endpointsr.   r/   Z!twisted.web.test.injectionhelpersr0   r1   Ztwisted.web._newclientr2   r3   r4   r5   r6   r7   r8   r  r9   r:   r;   r<   r=   r>   r?   Ztwisted.web.errorr@   Ztwisted.loggerrA   r  rB   rC   rD   rE   rF   rG   ZtestMixinClassru   ZruntimeTestCaserH   ImportErrorr  r  Ztwisted.internet._sslverifyrI   rJ   Ztwisted.internet.sslrK   Ztwisted.protocols.tlsrL   rM   rN   r`   re   r   r   r   r   r   r   r   r   r   r   r   r  r  r8  r<  r  r  r  r  r  r  r  r,  r>  rA  rB  rW  r_  r  ZSENSITIVE_HEADERSr  r  r  r  r  r  r  r  r  r  r  rV   rV   rV   rW   <module>   s4  $	$
 

 HP	  Am   .

 jH  
> } ?Z	   
+
)'f



