code
stringlengths
26
870k
docstring
stringlengths
1
65.6k
func_name
stringlengths
1
194
language
stringclasses
1 value
repo
stringlengths
8
68
path
stringlengths
5
182
url
stringlengths
46
251
license
stringclasses
4 values
def test_unnecessaryWindowUpdateForStream(self): """ When a WindowUpdate frame is received for a stream but no data is currently waiting, that stream is not marked as unblocked and the priority tree continues to assert that no stream can progress. """ f = FrameFactory() transport = StringTransport() conn = H2Connection() conn.requestFactory = DummyHTTPHandlerProxy # Send a request that implies a body is coming. Twisted doesn't send a # response until the entire request is received, so it won't queue any # data yet. Then, fire off a WINDOW_UPDATE frame. frames = [] frames.append( f.buildHeadersFrame(headers=self.postRequestHeaders, streamID=1) ) frames.append(f.buildWindowUpdateFrame(streamID=1, increment=5)) data = f.clientConnectionPreface() data += b''.join(f.serialize() for f in frames) conn.makeConnection(transport) conn.dataReceived(data) self.assertAllStreamsBlocked(conn)
When a WindowUpdate frame is received for a stream but no data is currently waiting, that stream is not marked as unblocked and the priority tree continues to assert that no stream can progress.
test_unnecessaryWindowUpdateForStream
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_windowUpdateAfterTerminate(self): """ When a WindowUpdate frame is received for a stream that has been aborted it is ignored. """ f = FrameFactory() b = StringTransport() a = H2Connection() a.requestFactory = DummyHTTPHandlerProxy # Send the request. frames = buildRequestFrames( self.postRequestHeaders, self.postRequestData, f ) requestBytes = f.clientConnectionPreface() requestBytes += b''.join(f.serialize() for f in frames) a.makeConnection(b) # one byte at a time, to stress the implementation. for byte in iterbytes(requestBytes): a.dataReceived(byte) # Abort the connection. a.streams[1].abortConnection() # Send a WindowUpdate windowUpdateFrame = f.buildWindowUpdateFrame(streamID=1, increment=5) a.dataReceived(windowUpdateFrame.serialize()) # Give the sending loop a chance to catch up! frames = framesFromBytes(b.value()) # Check that the stream is terminated. self.assertTrue( isinstance(frames[-1], hyperframe.frame.RstStreamFrame) )
When a WindowUpdate frame is received for a stream that has been aborted it is ignored.
test_windowUpdateAfterTerminate
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_windowUpdateAfterComplete(self): """ When a WindowUpdate frame is received for a stream that has been completed it is ignored. """ f = FrameFactory() b = StringTransport() a = H2Connection() a.requestFactory = DummyHTTPHandlerProxy # Send the request. frames = buildRequestFrames( self.postRequestHeaders, self.postRequestData, f ) requestBytes = f.clientConnectionPreface() requestBytes += b''.join(f.serialize() for f in frames) a.makeConnection(b) # one byte at a time, to stress the implementation. for byte in iterbytes(requestBytes): a.dataReceived(byte) def update_window(*args): # Send a WindowUpdate windowUpdateFrame = f.buildWindowUpdateFrame( streamID=1, increment=5 ) a.dataReceived(windowUpdateFrame.serialize()) def validate(*args): # Give the sending loop a chance to catch up! frames = framesFromBytes(b.value()) # Check that the stream is ended neatly. self.assertIn('END_STREAM', frames[-1].flags) d = a._streamCleanupCallbacks[1].addCallback(update_window) return d.addCallback(validate)
When a WindowUpdate frame is received for a stream that has been completed it is ignored.
test_windowUpdateAfterComplete
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_dataAndRstStream(self): """ When a DATA frame is received at the same time as RST_STREAM, Twisted does not send WINDOW_UPDATE frames for the stream. """ frameFactory = FrameFactory() transport = StringTransport() a = H2Connection() a.requestFactory = DummyHTTPHandlerProxy # Send the request, but instead of the last frame send a RST_STREAM # frame instead. This needs to be very long to actually force the # WINDOW_UPDATE frames out. frameData = [b'\x00' * (2**14)] * 4 bodyLength = "{}".format(sum(len(data) for data in frameData)) headers = ( self.postRequestHeaders[:-1] + [('content-length', bodyLength)] ) frames = buildRequestFrames( headers=headers, data=frameData, frameFactory=frameFactory ) del frames[-1] frames.append( frameFactory.buildRstStreamFrame( streamID=1, errorCode=h2.errors.ErrorCodes.INTERNAL_ERROR ) ) requestBytes = frameFactory.clientConnectionPreface() requestBytes += b''.join(f.serialize() for f in frames) a.makeConnection(transport) # Feed all the bytes at once. This is important: if they arrive slowly, # Twisted doesn't have any problems. a.dataReceived(requestBytes) # Check the frames we got. We expect a WINDOW_UPDATE frame only for the # connection, because Twisted knew the stream was going to be reset. frames = framesFromBytes(transport.value()) # Check that the only WINDOW_UPDATE frame came for the connection. windowUpdateFrameIDs = [ f.stream_id for f in frames if isinstance(f, hyperframe.frame.WindowUpdateFrame) ] self.assertEqual([0], windowUpdateFrameIDs) # While we're here: we shouldn't have received HEADERS or DATA for this # either. headersFrames = [ f for f in frames if isinstance(f, hyperframe.frame.HeadersFrame) ] dataFrames = [ f for f in frames if isinstance(f, hyperframe.frame.DataFrame) ] self.assertFalse(headersFrames) self.assertFalse(dataFrames)
When a DATA frame is received at the same time as RST_STREAM, Twisted does not send WINDOW_UPDATE frames for the stream.
test_dataAndRstStream
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_registerProducerWithTransport(self): """ L{H2Connection} can be registered with the transport as a producer. """ b = StringTransport() a = H2Connection() a.requestFactory = DummyHTTPHandlerProxy b.registerProducer(a, True) self.assertTrue(b.producer is a)
L{H2Connection} can be registered with the transport as a producer.
test_registerProducerWithTransport
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_pausingProducerPreventsDataSend(self): """ L{H2Connection} can be paused by its consumer. When paused it stops sending data to the transport. """ f = FrameFactory() b = StringTransport() a = H2Connection() a.requestFactory = DummyHTTPHandlerProxy # Send the request. frames = buildRequestFrames(self.getRequestHeaders, [], f) requestBytes = f.clientConnectionPreface() requestBytes += b''.join(f.serialize() for f in frames) a.makeConnection(b) b.registerProducer(a, True) # one byte at a time, to stress the implementation. for byte in iterbytes(requestBytes): a.dataReceived(byte) # The headers will be sent immediately, but the body will be waiting # until the reactor gets to spin. Before it does we'll pause # production. a.pauseProducing() # Now we want to build up a whole chain of Deferreds. We want to # 1. deferLater for a moment to let the sending loop run, which should # block. # 2. After that deferred fires, we want to validate that no data has # been sent yet. # 3. Then we want to resume the production. # 4. Then, we want to wait for the stream completion deferred. # 5. Validate that the data is correct. cleanupCallback = a._streamCleanupCallbacks[1] def validateNotSent(*args): frames = framesFromBytes(b.value()) self.assertEqual(len(frames), 2) self.assertFalse( isinstance(frames[-1], hyperframe.frame.DataFrame) ) a.resumeProducing() # Resume producing is a no-op, so let's call it a bunch more times. a.resumeProducing() a.resumeProducing() a.resumeProducing() a.resumeProducing() return cleanupCallback def validateComplete(*args): frames = framesFromBytes(b.value()) # Check that the stream is correctly terminated. self.assertEqual(len(frames), 4) self.assertTrue('END_STREAM' in frames[-1].flags) d = task.deferLater(reactor, 0.01, validateNotSent) d.addCallback(validateComplete) return d
L{H2Connection} can be paused by its consumer. When paused it stops sending data to the transport.
test_pausingProducerPreventsDataSend
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_stopProducing(self): """ L{H2Connection} can be stopped by its producer. That causes it to lose its transport. """ f = FrameFactory() b = StringTransport() a = H2Connection() a.requestFactory = DummyHTTPHandlerProxy # Send the request. frames = buildRequestFrames(self.getRequestHeaders, [], f) requestBytes = f.clientConnectionPreface() requestBytes += b''.join(f.serialize() for f in frames) a.makeConnection(b) b.registerProducer(a, True) # one byte at a time, to stress the implementation. for byte in iterbytes(requestBytes): a.dataReceived(byte) # The headers will be sent immediately, but the body will be waiting # until the reactor gets to spin. Before it does we'll stop production. a.stopProducing() frames = framesFromBytes(b.value()) self.assertEqual(len(frames), 2) self.assertFalse( isinstance(frames[-1], hyperframe.frame.DataFrame) ) self.assertFalse(a._stillProducing)
L{H2Connection} can be stopped by its producer. That causes it to lose its transport.
test_stopProducing
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_passthroughHostAndPeer(self): """ A L{H2Stream} object correctly passes through host and peer information from its L{H2Connection}. """ hostAddress = IPv4Address("TCP", "17.52.24.8", 443) peerAddress = IPv4Address("TCP", "17.188.0.12", 32008) frameFactory = FrameFactory() transport = StringTransport( hostAddress=hostAddress, peerAddress=peerAddress ) connection = H2Connection() connection.requestFactory = DummyHTTPHandlerProxy connection.makeConnection(transport) frames = buildRequestFrames(self.getRequestHeaders, [], frameFactory) requestBytes = frameFactory.clientConnectionPreface() requestBytes += b''.join(frame.serialize() for frame in frames) for byte in iterbytes(requestBytes): connection.dataReceived(byte) # The stream is present. Go grab the stream object. stream = connection.streams[1] self.assertEqual(stream.getHost(), hostAddress) self.assertEqual(stream.getPeer(), peerAddress) # Allow the stream to finish up and check the result. cleanupCallback = connection._streamCleanupCallbacks[1] def validate(*args): self.assertEqual(stream.getHost(), hostAddress) self.assertEqual(stream.getPeer(), peerAddress) return cleanupCallback.addCallback(validate)
A L{H2Stream} object correctly passes through host and peer information from its L{H2Connection}.
test_passthroughHostAndPeer
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_initiallySchedulesOneDataCall(self): """ When a H2Connection is established it schedules one call to be run as soon as the reactor has time. """ reactor = task.Clock() a = H2Connection(reactor) calls = reactor.getDelayedCalls() self.assertEqual(len(calls), 1) call = calls[0] # Validate that the call is scheduled for right now, but hasn't run, # and that it's correct. self.assertTrue(call.active()) self.assertEqual(call.time, 0) self.assertEqual(call.func, a._sendPrioritisedData) self.assertEqual(call.args, ()) self.assertEqual(call.kw, {})
When a H2Connection is established it schedules one call to be run as soon as the reactor has time.
test_initiallySchedulesOneDataCall
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def patch_TimeoutMixin_clock(self, connection, reactor): """ Unfortunately, TimeoutMixin does not allow passing an explicit reactor to test timeouts. For that reason, we need to monkeypatch the method set up by the TimeoutMixin. @param connection: The HTTP/2 connection object to patch. @type connection: L{H2Connection} @param reactor: The reactor whose callLater method we want. @type reactor: An object implementing L{twisted.internet.interfaces.IReactorTime} """ connection.callLater = reactor.callLater
Unfortunately, TimeoutMixin does not allow passing an explicit reactor to test timeouts. For that reason, we need to monkeypatch the method set up by the TimeoutMixin. @param connection: The HTTP/2 connection object to patch. @type connection: L{H2Connection} @param reactor: The reactor whose callLater method we want. @type reactor: An object implementing L{twisted.internet.interfaces.IReactorTime}
patch_TimeoutMixin_clock
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def initiateH2Connection(self, initialData, requestFactory): """ Performs test setup by building a HTTP/2 connection object, a transport to back it, a reactor to run in, and sending in some initial data as needed. @param initialData: The initial HTTP/2 data to be fed into the connection after setup. @type initialData: L{bytes} @param requestFactory: The L{Request} factory to use with the connection. """ reactor = task.Clock() conn = H2Connection(reactor) conn.timeOut = 100 self.patch_TimeoutMixin_clock(conn, reactor) transport = StringTransport() conn.requestFactory = _makeRequestProxyFactory(requestFactory) conn.makeConnection(transport) # one byte at a time, to stress the implementation. for byte in iterbytes(initialData): conn.dataReceived(byte) return (reactor, conn, transport)
Performs test setup by building a HTTP/2 connection object, a transport to back it, a reactor to run in, and sending in some initial data as needed. @param initialData: The initial HTTP/2 data to be fed into the connection after setup. @type initialData: L{bytes} @param requestFactory: The L{Request} factory to use with the connection.
initiateH2Connection
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def assertTimedOut(self, data, frameCount, errorCode, lastStreamID): """ Confirm that the data that was sent matches what we expect from a timeout: namely, that it ends with a GOAWAY frame carrying an appropriate error code and last stream ID. """ frames = framesFromBytes(data) self.assertEqual(len(frames), frameCount) self.assertTrue( isinstance(frames[-1], hyperframe.frame.GoAwayFrame) ) self.assertEqual(frames[-1].error_code, errorCode) self.assertEqual(frames[-1].last_stream_id, lastStreamID)
Confirm that the data that was sent matches what we expect from a timeout: namely, that it ends with a GOAWAY frame carrying an appropriate error code and last stream ID.
assertTimedOut
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def prepareAbortTest(self, abortTimeout=_DEFAULT): """ Does the common setup for tests that want to test the aborting functionality of the HTTP/2 stack. @param abortTimeout: The value to use for the abortTimeout. Defaults to whatever is set on L{H2Connection.abortTimeout}. @type abortTimeout: L{int} or L{None} @return: A tuple of the reactor being used for the connection, the connection itself, and the transport. """ if abortTimeout is self._DEFAULT: abortTimeout = H2Connection.abortTimeout frameFactory = FrameFactory() initialData = frameFactory.clientConnectionPreface() reactor, conn, transport = self.initiateH2Connection( initialData, requestFactory=DummyHTTPHandler, ) conn.abortTimeout = abortTimeout # Advance the clock. reactor.advance(100) self.assertTimedOut( transport.value(), frameCount=2, errorCode=h2.errors.ErrorCodes.NO_ERROR, lastStreamID=0 ) self.assertTrue(transport.disconnecting) self.assertFalse(transport.disconnected) return reactor, conn, transport
Does the common setup for tests that want to test the aborting functionality of the HTTP/2 stack. @param abortTimeout: The value to use for the abortTimeout. Defaults to whatever is set on L{H2Connection.abortTimeout}. @type abortTimeout: L{int} or L{None} @return: A tuple of the reactor being used for the connection, the connection itself, and the transport.
prepareAbortTest
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_timeoutAfterInactivity(self): """ When a L{H2Connection} does not receive any data for more than the time out interval, it closes the connection cleanly. """ frameFactory = FrameFactory() initialData = frameFactory.clientConnectionPreface() reactor, conn, transport = self.initiateH2Connection( initialData, requestFactory=DummyHTTPHandler, ) # Save the response preamble. preamble = transport.value() # Advance the clock. reactor.advance(99) # Everything is fine, no extra data got sent. self.assertEqual(preamble, transport.value()) self.assertFalse(transport.disconnecting) # Advance the clock. reactor.advance(2) self.assertTimedOut( transport.value(), frameCount=2, errorCode=h2.errors.ErrorCodes.NO_ERROR, lastStreamID=0 ) self.assertTrue(transport.disconnecting)
When a L{H2Connection} does not receive any data for more than the time out interval, it closes the connection cleanly.
test_timeoutAfterInactivity
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_timeoutResetByRequestData(self): """ When a L{H2Connection} receives data, the timeout is reset. """ # Don't send any initial data, we'll send the preamble manually. frameFactory = FrameFactory() initialData = b'' reactor, conn, transport = self.initiateH2Connection( initialData, requestFactory=DummyHTTPHandler, ) # Send one byte of the preamble every 99 'seconds'. for byte in iterbytes(frameFactory.clientConnectionPreface()): conn.dataReceived(byte) # Advance the clock. reactor.advance(99) # Everything is fine. self.assertFalse(transport.disconnecting) # Advance the clock. reactor.advance(2) self.assertTimedOut( transport.value(), frameCount=2, errorCode=h2.errors.ErrorCodes.NO_ERROR, lastStreamID=0 ) self.assertTrue(transport.disconnecting)
When a L{H2Connection} receives data, the timeout is reset.
test_timeoutResetByRequestData
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_timeoutResetByResponseData(self): """ When a L{H2Connection} sends data, the timeout is reset. """ # Don't send any initial data, we'll send the preamble manually. frameFactory = FrameFactory() initialData = b'' requests = [] frames = buildRequestFrames(self.getRequestHeaders, [], frameFactory) initialData = frameFactory.clientConnectionPreface() initialData += b''.join(f.serialize() for f in frames) def saveRequest(stream, queued): req = DelayedHTTPHandler(stream, queued=queued) requests.append(req) return req reactor, conn, transport = self.initiateH2Connection( initialData, requestFactory=saveRequest, ) conn.dataReceived(frameFactory.clientConnectionPreface()) # Advance the clock. reactor.advance(99) self.assertEquals(len(requests), 1) for x in range(10): # It doesn't time out as it's being written... requests[0].write(b'some bytes') reactor.advance(99) self.assertFalse(transport.disconnecting) # but the timer is still running, and it times out when it idles. reactor.advance(2) self.assertTimedOut( transport.value(), frameCount=13, errorCode=h2.errors.ErrorCodes.PROTOCOL_ERROR, lastStreamID=1 )
When a L{H2Connection} sends data, the timeout is reset.
test_timeoutResetByResponseData
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_timeoutWithProtocolErrorIfStreamsOpen(self): """ When a L{H2Connection} times out with active streams, the error code returned is L{h2.errors.ErrorCodes.PROTOCOL_ERROR}. """ frameFactory = FrameFactory() frames = buildRequestFrames(self.getRequestHeaders, [], frameFactory) initialData = frameFactory.clientConnectionPreface() initialData += b''.join(f.serialize() for f in frames) reactor, conn, transport = self.initiateH2Connection( initialData, requestFactory=DummyProducerHandler, ) # Advance the clock to time out the request. reactor.advance(101) self.assertTimedOut( transport.value(), frameCount=2, errorCode=h2.errors.ErrorCodes.PROTOCOL_ERROR, lastStreamID=1 ) self.assertTrue(transport.disconnecting)
When a L{H2Connection} times out with active streams, the error code returned is L{h2.errors.ErrorCodes.PROTOCOL_ERROR}.
test_timeoutWithProtocolErrorIfStreamsOpen
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_noTimeoutIfConnectionLost(self): """ When a L{H2Connection} loses its connection it cancels its timeout. """ frameFactory = FrameFactory() frames = buildRequestFrames(self.getRequestHeaders, [], frameFactory) initialData = frameFactory.clientConnectionPreface() initialData += b''.join(f.serialize() for f in frames) reactor, conn, transport = self.initiateH2Connection( initialData, requestFactory=DummyProducerHandler, ) sentData = transport.value() oldCallCount = len(reactor.getDelayedCalls()) # Now lose the connection. conn.connectionLost("reason") # There should be one fewer call than there was. currentCallCount = len(reactor.getDelayedCalls()) self.assertEqual(oldCallCount - 1, currentCallCount) # Advancing the clock should do nothing. reactor.advance(101) self.assertEqual(transport.value(), sentData)
When a L{H2Connection} loses its connection it cancels its timeout.
test_noTimeoutIfConnectionLost
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_timeoutEventuallyForcesConnectionClosed(self): """ When a L{H2Connection} has timed the connection out, and the transport doesn't get torn down within 15 seconds, it gets forcibly closed. """ reactor, conn, transport = self.prepareAbortTest() # Advance the clock to see that we abort the connection. reactor.advance(14) self.assertTrue(transport.disconnecting) self.assertFalse(transport.disconnected) reactor.advance(1) self.assertTrue(transport.disconnecting) self.assertTrue(transport.disconnected)
When a L{H2Connection} has timed the connection out, and the transport doesn't get torn down within 15 seconds, it gets forcibly closed.
test_timeoutEventuallyForcesConnectionClosed
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_losingConnectionCancelsTheAbort(self): """ When a L{H2Connection} has timed the connection out, getting C{connectionLost} called on it cancels the forcible connection close. """ reactor, conn, transport = self.prepareAbortTest() # Advance the clock, but right before the end fire connectionLost. reactor.advance(14) conn.connectionLost(None) # Check that the transport isn't forcibly closed. reactor.advance(1) self.assertTrue(transport.disconnecting) self.assertFalse(transport.disconnected)
When a L{H2Connection} has timed the connection out, getting C{connectionLost} called on it cancels the forcible connection close.
test_losingConnectionCancelsTheAbort
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_losingConnectionWithNoAbortTimeOut(self): """ When a L{H2Connection} has timed the connection out but the C{abortTimeout} is set to L{None}, the connection is never aborted. """ reactor, conn, transport = self.prepareAbortTest(abortTimeout=None) # Advance the clock an arbitrarily long way, and confirm it never # aborts. reactor.advance(2**32) self.assertTrue(transport.disconnecting) self.assertFalse(transport.disconnected)
When a L{H2Connection} has timed the connection out but the C{abortTimeout} is set to L{None}, the connection is never aborted.
test_losingConnectionWithNoAbortTimeOut
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_connectionLostAfterForceClose(self): """ If a timed out transport doesn't close after 15 seconds, the L{HTTPChannel} will forcibly close it. """ reactor, conn, transport = self.prepareAbortTest() # Force the follow-on forced closure. reactor.advance(15) self.assertTrue(transport.disconnecting) self.assertTrue(transport.disconnected) # Now call connectionLost on the protocol. This is done by some # transports, including TCP and TLS. We don't have anything we can # assert on here: this just must not explode. conn.connectionLost(error.ConnectionDone)
If a timed out transport doesn't close after 15 seconds, the L{HTTPChannel} will forcibly close it.
test_connectionLostAfterForceClose
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def makeRequest(self, method=b'GET', clientAddress=None): """ Create a request object to be passed to L{basic.BasicCredentialFactory.decode} along with a response value. Override this in a subclass. """ raise NotImplementedError("%r did not implement makeRequest" % ( self.__class__,))
Create a request object to be passed to L{basic.BasicCredentialFactory.decode} along with a response value. Override this in a subclass.
makeRequest
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
MIT
def test_interface(self): """ L{BasicCredentialFactory} implements L{ICredentialFactory}. """ self.assertTrue( verifyObject(ICredentialFactory, self.credentialFactory))
L{BasicCredentialFactory} implements L{ICredentialFactory}.
test_interface
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
MIT
def test_usernamePassword(self): """ L{basic.BasicCredentialFactory.decode} turns a base64-encoded response into a L{UsernamePassword} object with a password which reflects the one which was encoded in the response. """ response = b64encode(b''.join([self.username, b':', self.password])) creds = self.credentialFactory.decode(response, self.request) self.assertTrue(IUsernamePassword.providedBy(creds)) self.assertTrue(creds.checkPassword(self.password)) self.assertFalse(creds.checkPassword(self.password + b'wrong'))
L{basic.BasicCredentialFactory.decode} turns a base64-encoded response into a L{UsernamePassword} object with a password which reflects the one which was encoded in the response.
test_usernamePassword
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
MIT
def test_incorrectPadding(self): """ L{basic.BasicCredentialFactory.decode} decodes a base64-encoded response with incorrect padding. """ response = b64encode(b''.join([self.username, b':', self.password])) response = response.strip(b'=') creds = self.credentialFactory.decode(response, self.request) self.assertTrue(verifyObject(IUsernamePassword, creds)) self.assertTrue(creds.checkPassword(self.password))
L{basic.BasicCredentialFactory.decode} decodes a base64-encoded response with incorrect padding.
test_incorrectPadding
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
MIT
def test_invalidEncoding(self): """ L{basic.BasicCredentialFactory.decode} raises L{LoginFailed} if passed a response which is not base64-encoded. """ response = b'x' # one byte cannot be valid base64 text self.assertRaises( error.LoginFailed, self.credentialFactory.decode, response, self.makeRequest())
L{basic.BasicCredentialFactory.decode} raises L{LoginFailed} if passed a response which is not base64-encoded.
test_invalidEncoding
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
MIT
def test_invalidCredentials(self): """ L{basic.BasicCredentialFactory.decode} raises L{LoginFailed} when passed a response which is not valid base64-encoded text. """ response = b64encode(b'123abc+/') self.assertRaises( error.LoginFailed, self.credentialFactory.decode, response, self.makeRequest())
L{basic.BasicCredentialFactory.decode} raises L{LoginFailed} when passed a response which is not valid base64-encoded text.
test_invalidCredentials
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
MIT
def makeRequest(self, method=b'GET', clientAddress=None): """ Create a L{DummyRequest} (change me to create a L{twisted.web.http.Request} instead). """ if clientAddress is None: clientAddress = IPv4Address("TCP", "localhost", 1234) request = DummyRequest(b'/') request.method = method request.client = clientAddress return request
Create a L{DummyRequest} (change me to create a L{twisted.web.http.Request} instead).
makeRequest
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
MIT
def test_decode(self): """ L{digest.DigestCredentialFactory.decode} calls the C{decode} method on L{twisted.cred.digest.DigestCredentialFactory} with the HTTP method and host of the request. """ host = b'169.254.0.1' method = b'GET' done = [False] response = object() def check(_response, _method, _host): self.assertEqual(response, _response) self.assertEqual(method, _method) self.assertEqual(host, _host) done[0] = True self.patch(self.credentialFactory.digest, 'decode', check) req = self.makeRequest(method, IPv4Address('TCP', host, 81)) self.credentialFactory.decode(response, req) self.assertTrue(done[0])
L{digest.DigestCredentialFactory.decode} calls the C{decode} method on L{twisted.cred.digest.DigestCredentialFactory} with the HTTP method and host of the request.
test_decode
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
MIT
def test_interface(self): """ L{DigestCredentialFactory} implements L{ICredentialFactory}. """ self.assertTrue( verifyObject(ICredentialFactory, self.credentialFactory))
L{DigestCredentialFactory} implements L{ICredentialFactory}.
test_interface
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
MIT
def test_getChallenge(self): """ The challenge issued by L{DigestCredentialFactory.getChallenge} must include C{'qop'}, C{'realm'}, C{'algorithm'}, C{'nonce'}, and C{'opaque'} keys. The values for the C{'realm'} and C{'algorithm'} keys must match the values supplied to the factory's initializer. None of the values may have newlines in them. """ challenge = self.credentialFactory.getChallenge(self.request) self.assertEqual(challenge['qop'], b'auth') self.assertEqual(challenge['realm'], b'test realm') self.assertEqual(challenge['algorithm'], b'md5') self.assertIn('nonce', challenge) self.assertIn('opaque', challenge) for v in challenge.values(): self.assertNotIn(b'\n', v)
The challenge issued by L{DigestCredentialFactory.getChallenge} must include C{'qop'}, C{'realm'}, C{'algorithm'}, C{'nonce'}, and C{'opaque'} keys. The values for the C{'realm'} and C{'algorithm'} keys must match the values supplied to the factory's initializer. None of the values may have newlines in them.
test_getChallenge
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
MIT
def test_getChallengeWithoutClientIP(self): """ L{DigestCredentialFactory.getChallenge} can issue a challenge even if the L{Request} it is passed returns L{None} from C{getClientIP}. """ request = self.makeRequest(b'GET', None) challenge = self.credentialFactory.getChallenge(request) self.assertEqual(challenge['qop'], b'auth') self.assertEqual(challenge['realm'], b'test realm') self.assertEqual(challenge['algorithm'], b'md5') self.assertIn('nonce', challenge) self.assertIn('opaque', challenge)
L{DigestCredentialFactory.getChallenge} can issue a challenge even if the L{Request} it is passed returns L{None} from C{getClientIP}.
test_getChallengeWithoutClientIP
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
MIT
def test_getChildWithDefault(self): """ An L{UnauthorizedResource} is every child of itself. """ resource = UnauthorizedResource([]) self.assertIdentical( resource.getChildWithDefault("foo", None), resource) self.assertIdentical( resource.getChildWithDefault("bar", None), resource)
An L{UnauthorizedResource} is every child of itself.
test_getChildWithDefault
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
MIT
def _unauthorizedRenderTest(self, request): """ Render L{UnauthorizedResource} for the given request object and verify that the response code is I{Unauthorized} and that a I{WWW-Authenticate} header is set in the response containing a challenge. """ resource = UnauthorizedResource([ BasicCredentialFactory('example.com')]) request.render(resource) self.assertEqual(request.responseCode, 401) self.assertEqual( request.responseHeaders.getRawHeaders(b'www-authenticate'), [b'basic realm="example.com"'])
Render L{UnauthorizedResource} for the given request object and verify that the response code is I{Unauthorized} and that a I{WWW-Authenticate} header is set in the response containing a challenge.
_unauthorizedRenderTest
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
MIT
def test_render(self): """ L{UnauthorizedResource} renders with a 401 response code and a I{WWW-Authenticate} header and puts a simple unauthorized message into the response body. """ request = self.makeRequest() self._unauthorizedRenderTest(request) self.assertEqual(b'Unauthorized', b''.join(request.written))
L{UnauthorizedResource} renders with a 401 response code and a I{WWW-Authenticate} header and puts a simple unauthorized message into the response body.
test_render
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
MIT
def test_renderHEAD(self): """ The rendering behavior of L{UnauthorizedResource} for a I{HEAD} request is like its handling of a I{GET} request, but no response body is written. """ request = self.makeRequest(method=b'HEAD') self._unauthorizedRenderTest(request) self.assertEqual(b'', b''.join(request.written))
The rendering behavior of L{UnauthorizedResource} for a I{HEAD} request is like its handling of a I{GET} request, but no response body is written.
test_renderHEAD
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
MIT
def test_renderQuotesRealm(self): """ The realm value included in the I{WWW-Authenticate} header set in the response when L{UnauthorizedResounrce} is rendered has quotes and backslashes escaped. """ resource = UnauthorizedResource([ BasicCredentialFactory('example\\"foo')]) request = self.makeRequest() request.render(resource) self.assertEqual( request.responseHeaders.getRawHeaders(b'www-authenticate'), [b'basic realm="example\\\\\\"foo"'])
The realm value included in the I{WWW-Authenticate} header set in the response when L{UnauthorizedResounrce} is rendered has quotes and backslashes escaped.
test_renderQuotesRealm
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
MIT
def test_renderQuotesDigest(self): """ The digest value included in the I{WWW-Authenticate} header set in the response when L{UnauthorizedResource} is rendered has quotes and backslashes escaped. """ resource = UnauthorizedResource([ digest.DigestCredentialFactory(b'md5', b'example\\"foo')]) request = self.makeRequest() request.render(resource) authHeader = request.responseHeaders.getRawHeaders( b'www-authenticate' )[0] self.assertIn(b'realm="example\\\\\\"foo"', authHeader) self.assertIn(b'hm="md5', authHeader)
The digest value included in the I{WWW-Authenticate} header set in the response when L{UnauthorizedResource} is rendered has quotes and backslashes escaped.
test_renderQuotesDigest
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
MIT
def setUp(self): """ Create a realm, portal, and L{HTTPAuthSessionWrapper} to use in the tests. """ self.username = b'foo bar' self.password = b'bar baz' self.avatarContent = b"contents of the avatar resource itself" self.childName = b"foo-child" self.childContent = b"contents of the foo child of the avatar" self.checker = InMemoryUsernamePasswordDatabaseDontUse() self.checker.addUser(self.username, self.password) self.avatar = Data(self.avatarContent, 'text/plain') self.avatar.putChild( self.childName, Data(self.childContent, 'text/plain')) self.avatars = {self.username: self.avatar} self.realm = Realm(self.avatars.get) self.portal = portal.Portal(self.realm, [self.checker]) self.credentialFactories = [] self.wrapper = HTTPAuthSessionWrapper( self.portal, self.credentialFactories)
Create a realm, portal, and L{HTTPAuthSessionWrapper} to use in the tests.
setUp
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
MIT
def _authorizedBasicLogin(self, request): """ Add an I{basic authorization} header to the given request and then dispatch it, starting from C{self.wrapper} and returning the resulting L{IResource}. """ authorization = b64encode(self.username + b':' + self.password) request.requestHeaders.addRawHeader(b'authorization', b'Basic ' + authorization) return getChildForRequest(self.wrapper, request)
Add an I{basic authorization} header to the given request and then dispatch it, starting from C{self.wrapper} and returning the resulting L{IResource}.
_authorizedBasicLogin
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
MIT
def test_getChildWithDefault(self): """ Resource traversal which encounters an L{HTTPAuthSessionWrapper} results in an L{UnauthorizedResource} instance when the request does not have the required I{Authorization} headers. """ request = self.makeRequest([self.childName]) child = getChildForRequest(self.wrapper, request) d = request.notifyFinish() def cbFinished(result): self.assertEqual(request.responseCode, 401) d.addCallback(cbFinished) request.render(child) return d
Resource traversal which encounters an L{HTTPAuthSessionWrapper} results in an L{UnauthorizedResource} instance when the request does not have the required I{Authorization} headers.
test_getChildWithDefault
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
MIT
def _invalidAuthorizationTest(self, response): """ Create a request with the given value as the value of an I{Authorization} header and perform resource traversal with it, starting at C{self.wrapper}. Assert that the result is a 401 response code. Return a L{Deferred} which fires when this is all done. """ self.credentialFactories.append(BasicCredentialFactory('example.com')) request = self.makeRequest([self.childName]) request.requestHeaders.addRawHeader(b'authorization', response) child = getChildForRequest(self.wrapper, request) d = request.notifyFinish() def cbFinished(result): self.assertEqual(request.responseCode, 401) d.addCallback(cbFinished) request.render(child) return d
Create a request with the given value as the value of an I{Authorization} header and perform resource traversal with it, starting at C{self.wrapper}. Assert that the result is a 401 response code. Return a L{Deferred} which fires when this is all done.
_invalidAuthorizationTest
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
MIT
def test_getChildWithDefaultUnauthorizedUser(self): """ Resource traversal which enouncters an L{HTTPAuthSessionWrapper} results in an L{UnauthorizedResource} when the request has an I{Authorization} header with a user which does not exist. """ return self._invalidAuthorizationTest( b'Basic ' + b64encode(b'foo:bar'))
Resource traversal which enouncters an L{HTTPAuthSessionWrapper} results in an L{UnauthorizedResource} when the request has an I{Authorization} header with a user which does not exist.
test_getChildWithDefaultUnauthorizedUser
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
MIT
def test_getChildWithDefaultUnauthorizedPassword(self): """ Resource traversal which enouncters an L{HTTPAuthSessionWrapper} results in an L{UnauthorizedResource} when the request has an I{Authorization} header with a user which exists and the wrong password. """ return self._invalidAuthorizationTest( b'Basic ' + b64encode(self.username + b':bar'))
Resource traversal which enouncters an L{HTTPAuthSessionWrapper} results in an L{UnauthorizedResource} when the request has an I{Authorization} header with a user which exists and the wrong password.
test_getChildWithDefaultUnauthorizedPassword
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
MIT
def test_getChildWithDefaultUnrecognizedScheme(self): """ Resource traversal which enouncters an L{HTTPAuthSessionWrapper} results in an L{UnauthorizedResource} when the request has an I{Authorization} header with an unrecognized scheme. """ return self._invalidAuthorizationTest(b'Quux foo bar baz')
Resource traversal which enouncters an L{HTTPAuthSessionWrapper} results in an L{UnauthorizedResource} when the request has an I{Authorization} header with an unrecognized scheme.
test_getChildWithDefaultUnrecognizedScheme
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
MIT
def test_getChildWithDefaultAuthorized(self): """ Resource traversal which encounters an L{HTTPAuthSessionWrapper} results in an L{IResource} which renders the L{IResource} avatar retrieved from the portal when the request has a valid I{Authorization} header. """ self.credentialFactories.append(BasicCredentialFactory('example.com')) request = self.makeRequest([self.childName]) child = self._authorizedBasicLogin(request) d = request.notifyFinish() def cbFinished(ignored): self.assertEqual(request.written, [self.childContent]) d.addCallback(cbFinished) request.render(child) return d
Resource traversal which encounters an L{HTTPAuthSessionWrapper} results in an L{IResource} which renders the L{IResource} avatar retrieved from the portal when the request has a valid I{Authorization} header.
test_getChildWithDefaultAuthorized
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
MIT
def test_renderAuthorized(self): """ Resource traversal which terminates at an L{HTTPAuthSessionWrapper} and includes correct authentication headers results in the L{IResource} avatar (not one of its children) retrieved from the portal being rendered. """ self.credentialFactories.append(BasicCredentialFactory('example.com')) # Request it exactly, not any of its children. request = self.makeRequest([]) child = self._authorizedBasicLogin(request) d = request.notifyFinish() def cbFinished(ignored): self.assertEqual(request.written, [self.avatarContent]) d.addCallback(cbFinished) request.render(child) return d
Resource traversal which terminates at an L{HTTPAuthSessionWrapper} and includes correct authentication headers results in the L{IResource} avatar (not one of its children) retrieved from the portal being rendered.
test_renderAuthorized
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
MIT
def test_getChallengeCalledWithRequest(self): """ When L{HTTPAuthSessionWrapper} finds an L{ICredentialFactory} to issue a challenge, it calls the C{getChallenge} method with the request as an argument. """ @implementer(ICredentialFactory) class DumbCredentialFactory(object): scheme = b'dumb' def __init__(self): self.requests = [] def getChallenge(self, request): self.requests.append(request) return {} factory = DumbCredentialFactory() self.credentialFactories.append(factory) request = self.makeRequest([self.childName]) child = getChildForRequest(self.wrapper, request) d = request.notifyFinish() def cbFinished(ignored): self.assertEqual(factory.requests, [request]) d.addCallback(cbFinished) request.render(child) return d
When L{HTTPAuthSessionWrapper} finds an L{ICredentialFactory} to issue a challenge, it calls the C{getChallenge} method with the request as an argument.
test_getChallengeCalledWithRequest
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
MIT
def _logoutTest(self): """ Issue a request for an authentication-protected resource using valid credentials and then return the C{DummyRequest} instance which was used. This is a helper for tests about the behavior of the logout callback. """ self.credentialFactories.append(BasicCredentialFactory('example.com')) class SlowerResource(Resource): def render(self, request): return NOT_DONE_YET self.avatar.putChild(self.childName, SlowerResource()) request = self.makeRequest([self.childName]) child = self._authorizedBasicLogin(request) request.render(child) self.assertEqual(self.realm.loggedOut, 0) return request
Issue a request for an authentication-protected resource using valid credentials and then return the C{DummyRequest} instance which was used. This is a helper for tests about the behavior of the logout callback.
_logoutTest
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
MIT
def test_logout(self): """ The realm's logout callback is invoked after the resource is rendered. """ request = self._logoutTest() request.finish() self.assertEqual(self.realm.loggedOut, 1)
The realm's logout callback is invoked after the resource is rendered.
test_logout
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
MIT
def test_logoutOnError(self): """ The realm's logout callback is also invoked if there is an error generating the response (for example, if the client disconnects early). """ request = self._logoutTest() request.processingFailed( Failure(ConnectionDone("Simulated disconnect"))) self.assertEqual(self.realm.loggedOut, 1)
The realm's logout callback is also invoked if there is an error generating the response (for example, if the client disconnects early).
test_logoutOnError
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
MIT
def test_decodeRaises(self): """ Resource traversal which enouncters an L{HTTPAuthSessionWrapper} results in an L{UnauthorizedResource} when the request has a I{Basic Authorization} header which cannot be decoded using base64. """ self.credentialFactories.append(BasicCredentialFactory('example.com')) request = self.makeRequest([self.childName]) request.requestHeaders.addRawHeader(b'authorization', b'Basic decode should fail') child = getChildForRequest(self.wrapper, request) self.assertIsInstance(child, UnauthorizedResource)
Resource traversal which enouncters an L{HTTPAuthSessionWrapper} results in an L{UnauthorizedResource} when the request has a I{Basic Authorization} header which cannot be decoded using base64.
test_decodeRaises
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
MIT
def test_selectParseResponse(self): """ L{HTTPAuthSessionWrapper._selectParseHeader} returns a two-tuple giving the L{ICredentialFactory} to use to parse the header and a string containing the portion of the header which remains to be parsed. """ basicAuthorization = b'Basic abcdef123456' self.assertEqual( self.wrapper._selectParseHeader(basicAuthorization), (None, None)) factory = BasicCredentialFactory('example.com') self.credentialFactories.append(factory) self.assertEqual( self.wrapper._selectParseHeader(basicAuthorization), (factory, b'abcdef123456'))
L{HTTPAuthSessionWrapper._selectParseHeader} returns a two-tuple giving the L{ICredentialFactory} to use to parse the header and a string containing the portion of the header which remains to be parsed.
test_selectParseResponse
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
MIT
def test_unexpectedDecodeError(self): """ Any unexpected exception raised by the credential factory's C{decode} method results in a 500 response code and causes the exception to be logged. """ logObserver = EventLoggingObserver.createWithCleanup( self, globalLogPublisher ) class UnexpectedException(Exception): pass class BadFactory(object): scheme = b'bad' def getChallenge(self, client): return {} def decode(self, response, request): raise UnexpectedException() self.credentialFactories.append(BadFactory()) request = self.makeRequest([self.childName]) request.requestHeaders.addRawHeader(b'authorization', b'Bad abc') child = getChildForRequest(self.wrapper, request) request.render(child) self.assertEqual(request.responseCode, 500) self.assertEquals(1, len(logObserver)) self.assertIsInstance( logObserver[0]["log_failure"].value, UnexpectedException ) self.assertEqual(len(self.flushLoggedErrors(UnexpectedException)), 1)
Any unexpected exception raised by the credential factory's C{decode} method results in a 500 response code and causes the exception to be logged.
test_unexpectedDecodeError
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
MIT
def test_unexpectedLoginError(self): """ Any unexpected failure from L{Portal.login} results in a 500 response code and causes the failure to be logged. """ logObserver = EventLoggingObserver.createWithCleanup( self, globalLogPublisher ) class UnexpectedException(Exception): pass class BrokenChecker(object): credentialInterfaces = (IUsernamePassword,) def requestAvatarId(self, credentials): raise UnexpectedException() self.portal.registerChecker(BrokenChecker()) self.credentialFactories.append(BasicCredentialFactory('example.com')) request = self.makeRequest([self.childName]) child = self._authorizedBasicLogin(request) request.render(child) self.assertEqual(request.responseCode, 500) self.assertEquals(1, len(logObserver)) self.assertIsInstance( logObserver[0]["log_failure"].value, UnexpectedException ) self.assertEqual(len(self.flushLoggedErrors(UnexpectedException)), 1)
Any unexpected failure from L{Portal.login} results in a 500 response code and causes the failure to be logged.
test_unexpectedLoginError
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
MIT
def test_anonymousAccess(self): """ Anonymous requests are allowed if a L{Portal} has an anonymous checker registered. """ unprotectedContents = b"contents of the unprotected child resource" self.avatars[ANONYMOUS] = Resource() self.avatars[ANONYMOUS].putChild( self.childName, Data(unprotectedContents, 'text/plain')) self.portal.registerChecker(AllowAnonymousAccess()) self.credentialFactories.append(BasicCredentialFactory('example.com')) request = self.makeRequest([self.childName]) child = getChildForRequest(self.wrapper, request) d = request.notifyFinish() def cbFinished(ignored): self.assertEqual(request.written, [unprotectedContents]) d.addCallback(cbFinished) request.render(child) return d
Anonymous requests are allowed if a L{Portal} has an anonymous checker registered.
test_anonymousAccess
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_httpauth.py
MIT
def test_getNodeText(self): """ L{getNodeText} returns the concatenation of all the text data at or beneath the node passed to it. """ node = self.dom.parseString('<foo><bar>baz</bar><bar>quux</bar></foo>') self.assertEqual(domhelpers.getNodeText(node), "bazquux")
L{getNodeText} returns the concatenation of all the text data at or beneath the node passed to it.
test_getNodeText
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_domhelpers.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_domhelpers.py
MIT
def test_gatherTextNodesDropsWhitespace(self): """ Microdom discards whitespace-only text nodes, so L{gatherTextNodes} returns only the text from nodes which had non-whitespace characters. """ doc4_xml = '''<html> <head> </head> <body> stuff </body> </html> ''' doc4 = self.dom.parseString(doc4_xml) actual = domhelpers.gatherTextNodes(doc4) expected = '\n stuff\n ' self.assertEqual(actual, expected) actual = domhelpers.gatherTextNodes(doc4.documentElement) self.assertEqual(actual, expected)
Microdom discards whitespace-only text nodes, so L{gatherTextNodes} returns only the text from nodes which had non-whitespace characters.
test_gatherTextNodesDropsWhitespace
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_domhelpers.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_domhelpers.py
MIT
def test_textEntitiesNotDecoded(self): """ Microdom does not decode entities in text nodes. """ doc5_xml = '<x>Souffl&amp;</x>' doc5 = self.dom.parseString(doc5_xml) actual = domhelpers.gatherTextNodes(doc5) expected = 'Souffl&amp;' self.assertEqual(actual, expected) actual = domhelpers.gatherTextNodes(doc5.documentElement) self.assertEqual(actual, expected)
Microdom does not decode entities in text nodes.
test_textEntitiesNotDecoded
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_domhelpers.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_domhelpers.py
MIT
def test_textEntitiesDecoded(self): """ Minidom does decode entities in text nodes. """ doc5_xml = '<x>Souffl&amp;</x>' doc5 = self.dom.parseString(doc5_xml) actual = domhelpers.gatherTextNodes(doc5) expected = 'Souffl&' self.assertEqual(actual, expected) actual = domhelpers.gatherTextNodes(doc5.documentElement) self.assertEqual(actual, expected)
Minidom does decode entities in text nodes.
test_textEntitiesDecoded
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_domhelpers.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_domhelpers.py
MIT
def test_getNodeUnicodeText(self): """ L{domhelpers.getNodeText} returns a C{unicode} string when text nodes are represented in the DOM with unicode, whether or not there are non-ASCII characters present. """ node = self.dom.parseString("<foo>bar</foo>") text = domhelpers.getNodeText(node) self.assertEqual(text, u"bar") self.assertIsInstance(text, unicode) node = self.dom.parseString(u"<foo>\N{SNOWMAN}</foo>".encode('utf-8')) text = domhelpers.getNodeText(node) self.assertEqual(text, u"\N{SNOWMAN}") self.assertIsInstance(text, unicode)
L{domhelpers.getNodeText} returns a C{unicode} string when text nodes are represented in the DOM with unicode, whether or not there are non-ASCII characters present.
test_getNodeUnicodeText
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_domhelpers.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_domhelpers.py
MIT
def test_noMessageValidStatus(self): """ If no C{message} argument is passed to the L{Error} constructor and the C{code} argument is a valid HTTP status code, C{code} is mapped to a descriptive string to which C{message} is assigned. """ e = error.Error(b"200") self.assertEqual(e.message, b"OK")
If no C{message} argument is passed to the L{Error} constructor and the C{code} argument is a valid HTTP status code, C{code} is mapped to a descriptive string to which C{message} is assigned.
test_noMessageValidStatus
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
MIT
def test_noMessageInvalidStatus(self): """ If no C{message} argument is passed to the L{Error} constructor and C{code} isn't a valid HTTP status code, C{message} stays L{None}. """ e = error.Error(b"InvalidCode") self.assertEqual(e.message, None)
If no C{message} argument is passed to the L{Error} constructor and C{code} isn't a valid HTTP status code, C{message} stays L{None}.
test_noMessageInvalidStatus
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
MIT
def test_messageExists(self): """ If a C{message} argument is passed to the L{Error} constructor, the C{message} isn't affected by the value of C{status}. """ e = error.Error(b"200", b"My own message") self.assertEqual(e.message, b"My own message")
If a C{message} argument is passed to the L{Error} constructor, the C{message} isn't affected by the value of C{status}.
test_messageExists
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
MIT
def test_str(self): """ C{str()} on an L{Error} returns the code and message it was instantiated with. """ # Bytestring status e = error.Error(b"200", b"OK") self.assertEqual(str(e), "200 OK") # int status e = error.Error(200, b"OK") self.assertEqual(str(e), "200 OK")
C{str()} on an L{Error} returns the code and message it was instantiated with.
test_str
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
MIT
def test_noMessageValidStatus(self): """ If no C{message} argument is passed to the L{PageRedirect} constructor and the C{code} argument is a valid HTTP status code, C{code} is mapped to a descriptive string to which C{message} is assigned. """ e = error.PageRedirect(b"200", location=b"/foo") self.assertEqual(e.message, b"OK to /foo")
If no C{message} argument is passed to the L{PageRedirect} constructor and the C{code} argument is a valid HTTP status code, C{code} is mapped to a descriptive string to which C{message} is assigned.
test_noMessageValidStatus
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
MIT
def test_noMessageValidStatusNoLocation(self): """ If no C{message} argument is passed to the L{PageRedirect} constructor and C{location} is also empty and the C{code} argument is a valid HTTP status code, C{code} is mapped to a descriptive string to which C{message} is assigned without trying to include an empty location. """ e = error.PageRedirect(b"200") self.assertEqual(e.message, b"OK")
If no C{message} argument is passed to the L{PageRedirect} constructor and C{location} is also empty and the C{code} argument is a valid HTTP status code, C{code} is mapped to a descriptive string to which C{message} is assigned without trying to include an empty location.
test_noMessageValidStatusNoLocation
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
MIT
def test_noMessageInvalidStatusLocationExists(self): """ If no C{message} argument is passed to the L{PageRedirect} constructor and C{code} isn't a valid HTTP status code, C{message} stays L{None}. """ e = error.PageRedirect(b"InvalidCode", location=b"/foo") self.assertEqual(e.message, None)
If no C{message} argument is passed to the L{PageRedirect} constructor and C{code} isn't a valid HTTP status code, C{message} stays L{None}.
test_noMessageInvalidStatusLocationExists
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
MIT
def test_messageExistsLocationExists(self): """ If a C{message} argument is passed to the L{PageRedirect} constructor, the C{message} isn't affected by the value of C{status}. """ e = error.PageRedirect(b"200", b"My own message", location=b"/foo") self.assertEqual(e.message, b"My own message to /foo")
If a C{message} argument is passed to the L{PageRedirect} constructor, the C{message} isn't affected by the value of C{status}.
test_messageExistsLocationExists
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
MIT
def test_messageExistsNoLocation(self): """ If a C{message} argument is passed to the L{PageRedirect} constructor and no location is provided, C{message} doesn't try to include the empty location. """ e = error.PageRedirect(b"200", b"My own message") self.assertEqual(e.message, b"My own message")
If a C{message} argument is passed to the L{PageRedirect} constructor and no location is provided, C{message} doesn't try to include the empty location.
test_messageExistsNoLocation
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
MIT
def test_noMessageValidStatus(self): """ If no C{message} argument is passed to the L{InfiniteRedirection} constructor and the C{code} argument is a valid HTTP status code, C{code} is mapped to a descriptive string to which C{message} is assigned. """ e = error.InfiniteRedirection(b"200", location=b"/foo") self.assertEqual(e.message, b"OK to /foo")
If no C{message} argument is passed to the L{InfiniteRedirection} constructor and the C{code} argument is a valid HTTP status code, C{code} is mapped to a descriptive string to which C{message} is assigned.
test_noMessageValidStatus
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
MIT
def test_noMessageValidStatusNoLocation(self): """ If no C{message} argument is passed to the L{InfiniteRedirection} constructor and C{location} is also empty and the C{code} argument is a valid HTTP status code, C{code} is mapped to a descriptive string to which C{message} is assigned without trying to include an empty location. """ e = error.InfiniteRedirection(b"200") self.assertEqual(e.message, b"OK")
If no C{message} argument is passed to the L{InfiniteRedirection} constructor and C{location} is also empty and the C{code} argument is a valid HTTP status code, C{code} is mapped to a descriptive string to which C{message} is assigned without trying to include an empty location.
test_noMessageValidStatusNoLocation
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
MIT
def test_noMessageInvalidStatusLocationExists(self): """ If no C{message} argument is passed to the L{InfiniteRedirection} constructor and C{code} isn't a valid HTTP status code, C{message} stays L{None}. """ e = error.InfiniteRedirection(b"InvalidCode", location=b"/foo") self.assertEqual(e.message, None)
If no C{message} argument is passed to the L{InfiniteRedirection} constructor and C{code} isn't a valid HTTP status code, C{message} stays L{None}.
test_noMessageInvalidStatusLocationExists
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
MIT
def test_messageExistsLocationExists(self): """ If a C{message} argument is passed to the L{InfiniteRedirection} constructor, the C{message} isn't affected by the value of C{status}. """ e = error.InfiniteRedirection(b"200", b"My own message", location=b"/foo") self.assertEqual(e.message, b"My own message to /foo")
If a C{message} argument is passed to the L{InfiniteRedirection} constructor, the C{message} isn't affected by the value of C{status}.
test_messageExistsLocationExists
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
MIT
def test_messageExistsNoLocation(self): """ If a C{message} argument is passed to the L{InfiniteRedirection} constructor and no location is provided, C{message} doesn't try to include the empty location. """ e = error.InfiniteRedirection(b"200", b"My own message") self.assertEqual(e.message, b"My own message")
If a C{message} argument is passed to the L{InfiniteRedirection} constructor and no location is provided, C{message} doesn't try to include the empty location.
test_messageExistsNoLocation
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
MIT
def test_validMessage(self): """ When C{code}, C{message}, and C{uri} are passed to the L{RedirectWithNoLocation} constructor, the C{message} and C{uri} attributes are set, respectively. """ e = error.RedirectWithNoLocation(b"302", b"REDIRECT", b"https://example.com") self.assertEqual(e.message, b"REDIRECT to https://example.com") self.assertEqual(e.uri, b"https://example.com")
When C{code}, C{message}, and C{uri} are passed to the L{RedirectWithNoLocation} constructor, the C{message} and C{uri} attributes are set, respectively.
test_validMessage
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
MIT
def test_constructor(self): """ Given C{element} and C{renderName} arguments, the L{MissingRenderMethod} constructor assigns the values to the corresponding attributes. """ elt = object() e = error.MissingRenderMethod(elt, 'renderThing') self.assertIs(e.element, elt) self.assertIs(e.renderName, 'renderThing')
Given C{element} and C{renderName} arguments, the L{MissingRenderMethod} constructor assigns the values to the corresponding attributes.
test_constructor
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
MIT
def test_repr(self): """ A L{MissingRenderMethod} is represented using a custom string containing the element's representation and the method name. """ elt = object() e = error.MissingRenderMethod(elt, 'renderThing') self.assertEqual( repr(e), ("'MissingRenderMethod': " "%r had no render method named 'renderThing'") % elt)
A L{MissingRenderMethod} is represented using a custom string containing the element's representation and the method name.
test_repr
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
MIT
def test_constructor(self): """ Given an C{element} argument, the L{MissingTemplateLoader} constructor assigns the value to the corresponding attribute. """ elt = object() e = error.MissingTemplateLoader(elt) self.assertIs(e.element, elt)
Given an C{element} argument, the L{MissingTemplateLoader} constructor assigns the value to the corresponding attribute.
test_constructor
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
MIT
def test_repr(self): """ A L{MissingTemplateLoader} is represented using a custom string containing the element's representation and the method name. """ elt = object() e = error.MissingTemplateLoader(elt) self.assertEqual( repr(e), "'MissingTemplateLoader': %r had no loader" % elt)
A L{MissingTemplateLoader} is represented using a custom string containing the element's representation and the method name.
test_repr
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
MIT
def test_constructor(self): """ Given C{exception}, C{roots}, and C{traceback} arguments, the L{FlattenerError} constructor assigns the roots to the C{_roots} attribute. """ e = self.makeFlattenerError(roots=['a', 'b']) self.assertEqual(e._roots, ['a', 'b'])
Given C{exception}, C{roots}, and C{traceback} arguments, the L{FlattenerError} constructor assigns the roots to the C{_roots} attribute.
test_constructor
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
MIT
def test_str(self): """ The string form of a L{FlattenerError} is identical to its representation. """ e = self.makeFlattenerError() self.assertEqual(str(e), repr(e))
The string form of a L{FlattenerError} is identical to its representation.
test_str
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
MIT
def test_reprWithRootsAndWithTraceback(self): """ The representation of a L{FlattenerError} initialized with roots and a traceback contains a formatted representation of those roots (using C{_formatRoot}) and a formatted traceback. """ e = self.makeFlattenerError(['a', 'b']) e._formatRoot = self.fakeFormatRoot self.assertTrue( re.match('Exception while flattening:\n' ' R\(a\)\n' ' R\(b\)\n' ' File "[^"]*", line [0-9]*, in makeFlattenerError\n' ' raise RuntimeError\("oh noes"\)\n' 'RuntimeError: oh noes\n$', repr(e), re.M | re.S), repr(e))
The representation of a L{FlattenerError} initialized with roots and a traceback contains a formatted representation of those roots (using C{_formatRoot}) and a formatted traceback.
test_reprWithRootsAndWithTraceback
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
MIT
def test_reprWithoutRootsAndWithTraceback(self): """ The representation of a L{FlattenerError} initialized without roots but with a traceback contains a formatted traceback but no roots. """ e = self.makeFlattenerError([]) self.assertTrue( re.match('Exception while flattening:\n' ' File "[^"]*", line [0-9]*, in makeFlattenerError\n' ' raise RuntimeError\("oh noes"\)\n' 'RuntimeError: oh noes\n$', repr(e), re.M | re.S), repr(e))
The representation of a L{FlattenerError} initialized without roots but with a traceback contains a formatted traceback but no roots.
test_reprWithoutRootsAndWithTraceback
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
MIT
def test_formatRootShortUnicodeString(self): """ The C{_formatRoot} method formats a short unicode string using the built-in repr. """ e = self.makeFlattenerError() self.assertEqual(e._formatRoot(nativeString('abcd')), repr('abcd'))
The C{_formatRoot} method formats a short unicode string using the built-in repr.
test_formatRootShortUnicodeString
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
MIT
def test_formatRootLongUnicodeString(self): """ The C{_formatRoot} method formats a long unicode string using the built-in repr with an ellipsis. """ e = self.makeFlattenerError() longString = nativeString('abcde-' * 20) self.assertEqual(e._formatRoot(longString), repr('abcde-abcde-abcde-ab<...>e-abcde-abcde-abcde-'))
The C{_formatRoot} method formats a long unicode string using the built-in repr with an ellipsis.
test_formatRootLongUnicodeString
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
MIT
def test_formatRootShortByteString(self): """ The C{_formatRoot} method formats a short byte string using the built-in repr. """ e = self.makeFlattenerError() self.assertEqual(e._formatRoot(b'abcd'), repr(b'abcd'))
The C{_formatRoot} method formats a short byte string using the built-in repr.
test_formatRootShortByteString
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
MIT
def test_formatRootLongByteString(self): """ The C{_formatRoot} method formats a long byte string using the built-in repr with an ellipsis. """ e = self.makeFlattenerError() longString = b'abcde-' * 20 self.assertEqual(e._formatRoot(longString), repr(b'abcde-abcde-abcde-ab<...>e-abcde-abcde-abcde-'))
The C{_formatRoot} method formats a long byte string using the built-in repr with an ellipsis.
test_formatRootLongByteString
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
MIT
def test_formatRootTagNoFilename(self): """ The C{_formatRoot} method formats a C{Tag} with no filename information as 'Tag <tagName>'. """ e = self.makeFlattenerError() self.assertEqual(e._formatRoot(Tag('a-tag')), 'Tag <a-tag>')
The C{_formatRoot} method formats a C{Tag} with no filename information as 'Tag <tagName>'.
test_formatRootTagNoFilename
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
MIT
def test_formatRootTagWithFilename(self): """ The C{_formatRoot} method formats a C{Tag} with filename information using the filename, line, column, and tag information """ e = self.makeFlattenerError() t = Tag('a-tag', filename='tpl.py', lineNumber=10, columnNumber=20) self.assertEqual(e._formatRoot(t), 'File "tpl.py", line 10, column 20, in "a-tag"')
The C{_formatRoot} method formats a C{Tag} with filename information using the filename, line, column, and tag information
test_formatRootTagWithFilename
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
MIT
def test_string(self): """ If a L{FlattenerError} is created with a string root, up to around 40 bytes from that string are included in the string representation of the exception. """ self.assertEqual( str(error.FlattenerError(RuntimeError("reason"), ['abc123xyz'], [])), "Exception while flattening:\n" " 'abc123xyz'\n" "RuntimeError: reason\n") self.assertEqual( str(error.FlattenerError( RuntimeError("reason"), ['0123456789' * 10], [])), "Exception while flattening:\n" " '01234567890123456789" "<...>01234567890123456789'\n" # TODO: re-add 0 "RuntimeError: reason\n")
If a L{FlattenerError} is created with a string root, up to around 40 bytes from that string are included in the string representation of the exception.
test_string
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
MIT
def test_unicode(self): """ If a L{FlattenerError} is created with a unicode root, up to around 40 characters from that string are included in the string representation of the exception. """ # the response includes the output of repr(), which differs between # Python 2 and 3 u = {'u': ''} if _PY3 else {'u': 'u'} self.assertEqual( str(error.FlattenerError( RuntimeError("reason"), [u'abc\N{SNOWMAN}xyz'], [])), "Exception while flattening:\n" " %(u)s'abc\\u2603xyz'\n" # Codepoint for SNOWMAN "RuntimeError: reason\n" % u) self.assertEqual( str(error.FlattenerError( RuntimeError("reason"), [u'01234567\N{SNOWMAN}9' * 10], [])), "Exception while flattening:\n" " %(u)s'01234567\\u2603901234567\\u26039" "<...>01234567\\u2603901234567" "\\u26039'\n" "RuntimeError: reason\n" % u)
If a L{FlattenerError} is created with a unicode root, up to around 40 characters from that string are included in the string representation of the exception.
test_unicode
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
MIT
def test_str(self): """ The C{__str__} for L{UnsupportedMethod} makes it clear that what it shows is a list of the supported methods, not the method that was unsupported. """ b = "b" if _PY3 else "" e = error.UnsupportedMethod([b"HEAD", b"PATCH"]) self.assertEqual( str(e), "Expected one of [{b}'HEAD', {b}'PATCH']".format(b=b), )
The C{__str__} for L{UnsupportedMethod} makes it clear that what it shows is a list of the supported methods, not the method that was unsupported.
test_str
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_error.py
MIT
def tearDown(self): """ Clean up all the event sources left behind by either directly by test methods or indirectly via some distrib API. """ dl = [defer.Deferred(), defer.Deferred()] if self.f1 is not None and self.f1.proto is not None: self.f1.proto.notifyOnDisconnect(lambda: dl[0].callback(None)) else: dl[0].callback(None) if self.sub is not None and self.sub.publisher is not None: self.sub.publisher.broker.notifyOnDisconnect( lambda: dl[1].callback(None)) self.sub.publisher.broker.transport.loseConnection() else: dl[1].callback(None) if self.port1 is not None: dl.append(self.port1.stopListening()) if self.port2 is not None: dl.append(self.port2.stopListening()) return defer.gatherResults(dl)
Clean up all the event sources left behind by either directly by test methods or indirectly via some distrib API.
tearDown
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
MIT
def _setupDistribServer(self, child): """ Set up a resource on a distrib site using L{ResourcePublisher}. @param child: The resource to publish using distrib. @return: A tuple consisting of the host and port on which to contact the created site. """ distribRoot = resource.Resource() distribRoot.putChild(b"child", child) distribSite = server.Site(distribRoot) self.f1 = distribFactory = PBServerFactory( distrib.ResourcePublisher(distribSite)) distribPort = reactor.listenTCP( 0, distribFactory, interface="127.0.0.1") self.addCleanup(distribPort.stopListening) addr = distribPort.getHost() self.sub = mainRoot = distrib.ResourceSubscription( addr.host, addr.port) mainSite = server.Site(mainRoot) mainPort = reactor.listenTCP(0, mainSite, interface="127.0.0.1") self.addCleanup(mainPort.stopListening) mainAddr = mainPort.getHost() return mainPort, mainAddr
Set up a resource on a distrib site using L{ResourcePublisher}. @param child: The resource to publish using distrib. @return: A tuple consisting of the host and port on which to contact the created site.
_setupDistribServer
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
MIT
def _requestTest(self, child, **kwargs): """ Set up a resource on a distrib site using L{ResourcePublisher} and then retrieve it from a L{ResourceSubscription} via an HTTP client. @param child: The resource to publish using distrib. @param **kwargs: Extra keyword arguments to pass to L{Agent.request} when requesting the resource. @return: A L{Deferred} which fires with the result of the request. """ mainPort, mainAddr = self._setupDistribServer(child) agent = client.Agent(reactor) url = "http://%s:%s/child" % (mainAddr.host, mainAddr.port) url = url.encode("ascii") d = agent.request(b"GET", url, **kwargs) d.addCallback(client.readBody) return d
Set up a resource on a distrib site using L{ResourcePublisher} and then retrieve it from a L{ResourceSubscription} via an HTTP client. @param child: The resource to publish using distrib. @param **kwargs: Extra keyword arguments to pass to L{Agent.request} when requesting the resource. @return: A L{Deferred} which fires with the result of the request.
_requestTest
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
MIT
def _requestAgentTest(self, child, **kwargs): """ Set up a resource on a distrib site using L{ResourcePublisher} and then retrieve it from a L{ResourceSubscription} via an HTTP client. @param child: The resource to publish using distrib. @param **kwargs: Extra keyword arguments to pass to L{Agent.request} when requesting the resource. @return: A L{Deferred} which fires with a tuple consisting of a L{twisted.test.proto_helpers.AccumulatingProtocol} containing the body of the response and an L{IResponse} with the response itself. """ mainPort, mainAddr = self._setupDistribServer(child) url = "http://{}:{}/child".format(mainAddr.host, mainAddr.port) url = url.encode("ascii") d = client.Agent(reactor).request(b"GET", url, **kwargs) def cbCollectBody(response): protocol = proto_helpers.AccumulatingProtocol() response.deliverBody(protocol) d = protocol.closedDeferred = defer.Deferred() d.addCallback(lambda _: (protocol, response)) return d d.addCallback(cbCollectBody) return d
Set up a resource on a distrib site using L{ResourcePublisher} and then retrieve it from a L{ResourceSubscription} via an HTTP client. @param child: The resource to publish using distrib. @param **kwargs: Extra keyword arguments to pass to L{Agent.request} when requesting the resource. @return: A L{Deferred} which fires with a tuple consisting of a L{twisted.test.proto_helpers.AccumulatingProtocol} containing the body of the response and an L{IResponse} with the response itself.
_requestAgentTest
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
MIT
def test_requestHeaders(self): """ The request headers are available on the request object passed to a distributed resource's C{render} method. """ requestHeaders = {} logObserver = proto_helpers.EventLoggingObserver() globalLogPublisher.addObserver(logObserver) req = [None] class ReportRequestHeaders(resource.Resource): def render(self, request): req[0] = request requestHeaders.update(dict( request.requestHeaders.getAllRawHeaders())) return b"" def check_logs(): msgs = [e["log_format"] for e in logObserver] self.assertIn('connected to publisher', msgs) self.assertIn( "could not connect to distributed web service: {msg}", msgs ) self.assertIn(req[0], msgs) globalLogPublisher.removeObserver(logObserver) request = self._requestTest( ReportRequestHeaders(), headers=Headers({'foo': ['bar']})) def cbRequested(result): self.f1.proto.notifyOnDisconnect(check_logs) self.assertEqual(requestHeaders[b'Foo'], [b'bar']) request.addCallback(cbRequested) return request
The request headers are available on the request object passed to a distributed resource's C{render} method.
test_requestHeaders
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
MIT
def test_requestResponseCode(self): """ The response code can be set by the request object passed to a distributed resource's C{render} method. """ class SetResponseCode(resource.Resource): def render(self, request): request.setResponseCode(200) return "" request = self._requestAgentTest(SetResponseCode()) def cbRequested(result): self.assertEqual(result[0].data, b"") self.assertEqual(result[1].code, 200) self.assertEqual(result[1].phrase, b"OK") request.addCallback(cbRequested) return request
The response code can be set by the request object passed to a distributed resource's C{render} method.
test_requestResponseCode
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
MIT