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
194
| url
stringlengths 46
254
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
def _checkSimpleGreeting(self, locatorClass, expected):
"""
Check that a locator of type C{locatorClass} finds a responder
for command named I{simple} and that the found responder answers
with the C{expected} result to a C{SimpleGreeting<"ni hao", 5>}
command.
"""
locator = locatorClass()
responderCallable = locator.locateResponder(b"simple")
result = responderCallable(amp.Box(greeting=b"ni hao", cookie=b"5"))
def done(values):
self.assertEqual(values, amp.AmpBox(cookieplus=intToBytes(expected)))
return result.addCallback(done) | Check that a locator of type C{locatorClass} finds a responder
for command named I{simple} and that the found responder answers
with the C{expected} result to a C{SimpleGreeting<"ni hao", 5>}
command. | _checkSimpleGreeting | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_responderDecorator(self):
"""
A method on a L{CommandLocator} subclass decorated with a L{Command}
subclass's L{responder} decorator should be returned from
locateResponder, wrapped in logic to serialize and deserialize its
arguments.
"""
return self._checkSimpleGreeting(TestLocator, 8) | A method on a L{CommandLocator} subclass decorated with a L{Command}
subclass's L{responder} decorator should be returned from
locateResponder, wrapped in logic to serialize and deserialize its
arguments. | test_responderDecorator | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_responderOverriding(self):
"""
L{CommandLocator} subclasses can override a responder inherited from
a base class by using the L{Command.responder} decorator to register
a new responder method.
"""
return self._checkSimpleGreeting(OverridingLocator, 9) | L{CommandLocator} subclasses can override a responder inherited from
a base class by using the L{Command.responder} decorator to register
a new responder method. | test_responderOverriding | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_responderInheritance(self):
"""
Responder lookup follows the same rules as normal method lookup
rules, particularly with respect to inheritance.
"""
return self._checkSimpleGreeting(InheritingLocator, 9) | Responder lookup follows the same rules as normal method lookup
rules, particularly with respect to inheritance. | test_responderInheritance | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_lookupFunctionDeprecatedOverride(self):
"""
Subclasses which override locateResponder under its old name,
lookupFunction, should have the override invoked instead. (This tests
an AMP subclass, because in the version of the code that could invoke
this deprecated code path, there was no L{CommandLocator}.)
"""
locator = OverrideLocatorAMP()
customResponderObject = self.assertWarns(
PendingDeprecationWarning,
"Override locateResponder, not lookupFunction.",
__file__, lambda : locator.locateResponder(b"custom"))
self.assertEqual(locator.customResponder, customResponderObject)
# Make sure upcalling works too
normalResponderObject = self.assertWarns(
PendingDeprecationWarning,
"Override locateResponder, not lookupFunction.",
__file__, lambda : locator.locateResponder(b"simple"))
result = normalResponderObject(amp.Box(greeting=b"ni hao", cookie=b"5"))
def done(values):
self.assertEqual(values, amp.AmpBox(cookieplus=b'8'))
return result.addCallback(done) | Subclasses which override locateResponder under its old name,
lookupFunction, should have the override invoked instead. (This tests
an AMP subclass, because in the version of the code that could invoke
this deprecated code path, there was no L{CommandLocator}.) | test_lookupFunctionDeprecatedOverride | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_lookupFunctionDeprecatedInvoke(self):
"""
Invoking locateResponder under its old name, lookupFunction, should
emit a deprecation warning, but do the same thing.
"""
locator = TestLocator()
responderCallable = self.assertWarns(
PendingDeprecationWarning,
"Call locateResponder, not lookupFunction.", __file__,
lambda : locator.lookupFunction(b"simple"))
result = responderCallable(amp.Box(greeting=b"ni hao", cookie=b"5"))
def done(values):
self.assertEqual(values, amp.AmpBox(cookieplus=b'8'))
return result.addCallback(done) | Invoking locateResponder under its old name, lookupFunction, should
emit a deprecation warning, but do the same thing. | test_lookupFunctionDeprecatedInvoke | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def setUp(self):
"""
Keep track of all boxes received by this test in its capacity as an
L{IBoxReceiver} implementor.
"""
self.boxes = []
self.data = [] | Keep track of all boxes received by this test in its capacity as an
L{IBoxReceiver} implementor. | setUp | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def startReceivingBoxes(self, sender):
"""
Implement L{IBoxReceiver.startReceivingBoxes} to just remember the
value passed in.
"""
self._boxSender = sender | Implement L{IBoxReceiver.startReceivingBoxes} to just remember the
value passed in. | startReceivingBoxes | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def ampBoxReceived(self, box):
"""
A box was received by the protocol.
"""
self.boxes.append(box) | A box was received by the protocol. | ampBoxReceived | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def stopReceivingBoxes(self, reason):
"""
Record the reason that we stopped receiving boxes.
"""
self.stopReason = reason | Record the reason that we stopped receiving boxes. | stopReceivingBoxes | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_startReceivingBoxes(self):
"""
When L{amp.BinaryBoxProtocol} is connected to a transport, it calls
C{startReceivingBoxes} on its L{IBoxReceiver} with itself as the
L{IBoxSender} parameter.
"""
protocol = amp.BinaryBoxProtocol(self)
protocol.makeConnection(None)
self.assertIs(self._boxSender, protocol) | When L{amp.BinaryBoxProtocol} is connected to a transport, it calls
C{startReceivingBoxes} on its L{IBoxReceiver} with itself as the
L{IBoxSender} parameter. | test_startReceivingBoxes | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_sendBoxInStartReceivingBoxes(self):
"""
The L{IBoxReceiver} which is started when L{amp.BinaryBoxProtocol} is
connected to a transport can call C{sendBox} on the L{IBoxSender}
passed to it before C{startReceivingBoxes} returns and have that box
sent.
"""
class SynchronouslySendingReceiver:
def startReceivingBoxes(self, sender):
sender.sendBox(amp.Box({b'foo': b'bar'}))
transport = StringTransport()
protocol = amp.BinaryBoxProtocol(SynchronouslySendingReceiver())
protocol.makeConnection(transport)
self.assertEqual(
transport.value(),
b'\x00\x03foo\x00\x03bar\x00\x00') | The L{IBoxReceiver} which is started when L{amp.BinaryBoxProtocol} is
connected to a transport can call C{sendBox} on the L{IBoxSender}
passed to it before C{startReceivingBoxes} returns and have that box
sent. | test_sendBoxInStartReceivingBoxes | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_receiveBoxStateMachine(self):
"""
When a binary box protocol receives:
* a key
* a value
* an empty string
it should emit a box and send it to its boxReceiver.
"""
a = amp.BinaryBoxProtocol(self)
a.stringReceived(b"hello")
a.stringReceived(b"world")
a.stringReceived(b"")
self.assertEqual(self.boxes, [amp.AmpBox(hello=b"world")]) | When a binary box protocol receives:
* a key
* a value
* an empty string
it should emit a box and send it to its boxReceiver. | test_receiveBoxStateMachine | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_firstBoxFirstKeyExcessiveLength(self):
"""
L{amp.BinaryBoxProtocol} drops its connection if the length prefix for
the first a key it receives is larger than 255.
"""
transport = StringTransport()
protocol = amp.BinaryBoxProtocol(self)
protocol.makeConnection(transport)
protocol.dataReceived(b'\x01\x00')
self.assertTrue(transport.disconnecting) | L{amp.BinaryBoxProtocol} drops its connection if the length prefix for
the first a key it receives is larger than 255. | test_firstBoxFirstKeyExcessiveLength | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_firstBoxSubsequentKeyExcessiveLength(self):
"""
L{amp.BinaryBoxProtocol} drops its connection if the length prefix for
a subsequent key in the first box it receives is larger than 255.
"""
transport = StringTransport()
protocol = amp.BinaryBoxProtocol(self)
protocol.makeConnection(transport)
protocol.dataReceived(b'\x00\x01k\x00\x01v')
self.assertFalse(transport.disconnecting)
protocol.dataReceived(b'\x01\x00')
self.assertTrue(transport.disconnecting) | L{amp.BinaryBoxProtocol} drops its connection if the length prefix for
a subsequent key in the first box it receives is larger than 255. | test_firstBoxSubsequentKeyExcessiveLength | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_subsequentBoxFirstKeyExcessiveLength(self):
"""
L{amp.BinaryBoxProtocol} drops its connection if the length prefix for
the first key in a subsequent box it receives is larger than 255.
"""
transport = StringTransport()
protocol = amp.BinaryBoxProtocol(self)
protocol.makeConnection(transport)
protocol.dataReceived(b'\x00\x01k\x00\x01v\x00\x00')
self.assertFalse(transport.disconnecting)
protocol.dataReceived(b'\x01\x00')
self.assertTrue(transport.disconnecting) | L{amp.BinaryBoxProtocol} drops its connection if the length prefix for
the first key in a subsequent box it receives is larger than 255. | test_subsequentBoxFirstKeyExcessiveLength | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_excessiveKeyFailure(self):
"""
If L{amp.BinaryBoxProtocol} disconnects because it received a key
length prefix which was too large, the L{IBoxReceiver}'s
C{stopReceivingBoxes} method is called with a L{TooLong} failure.
"""
protocol = amp.BinaryBoxProtocol(self)
protocol.makeConnection(StringTransport())
protocol.dataReceived(b'\x01\x00')
protocol.connectionLost(
Failure(error.ConnectionDone("simulated connection done")))
self.stopReason.trap(amp.TooLong)
self.assertTrue(self.stopReason.value.isKey)
self.assertFalse(self.stopReason.value.isLocal)
self.assertIsNone(self.stopReason.value.value)
self.assertIsNone(self.stopReason.value.keyName) | If L{amp.BinaryBoxProtocol} disconnects because it received a key
length prefix which was too large, the L{IBoxReceiver}'s
C{stopReceivingBoxes} method is called with a L{TooLong} failure. | test_excessiveKeyFailure | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_unhandledErrorWithTransport(self):
"""
L{amp.BinaryBoxProtocol.unhandledError} logs the failure passed to it
and disconnects its transport.
"""
transport = StringTransport()
protocol = amp.BinaryBoxProtocol(self)
protocol.makeConnection(transport)
protocol.unhandledError(Failure(RuntimeError("Fake error")))
self.assertEqual(1, len(self.flushLoggedErrors(RuntimeError)))
self.assertTrue(transport.disconnecting) | L{amp.BinaryBoxProtocol.unhandledError} logs the failure passed to it
and disconnects its transport. | test_unhandledErrorWithTransport | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_unhandledErrorWithoutTransport(self):
"""
L{amp.BinaryBoxProtocol.unhandledError} completes without error when
there is no associated transport.
"""
protocol = amp.BinaryBoxProtocol(self)
protocol.makeConnection(StringTransport())
protocol.connectionLost(Failure(Exception("Simulated")))
protocol.unhandledError(Failure(RuntimeError("Fake error")))
self.assertEqual(1, len(self.flushLoggedErrors(RuntimeError))) | L{amp.BinaryBoxProtocol.unhandledError} completes without error when
there is no associated transport. | test_unhandledErrorWithoutTransport | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_receiveBoxData(self):
"""
When a binary box protocol receives the serialized form of an AMP box,
it should emit a similar box to its boxReceiver.
"""
a = amp.BinaryBoxProtocol(self)
a.dataReceived(amp.Box({b"testKey": b"valueTest",
b"anotherKey": b"anotherValue"}).serialize())
self.assertEqual(self.boxes,
[amp.Box({b"testKey": b"valueTest",
b"anotherKey": b"anotherValue"})]) | When a binary box protocol receives the serialized form of an AMP box,
it should emit a similar box to its boxReceiver. | test_receiveBoxData | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_receiveLongerBoxData(self):
"""
An L{amp.BinaryBoxProtocol} can receive serialized AMP boxes with
values of up to (2 ** 16 - 1) bytes.
"""
length = (2 ** 16 - 1)
value = b'x' * length
transport = StringTransport()
protocol = amp.BinaryBoxProtocol(self)
protocol.makeConnection(transport)
protocol.dataReceived(amp.Box({'k': value}).serialize())
self.assertEqual(self.boxes, [amp.Box({'k': value})])
self.assertFalse(transport.disconnecting) | An L{amp.BinaryBoxProtocol} can receive serialized AMP boxes with
values of up to (2 ** 16 - 1) bytes. | test_receiveLongerBoxData | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_sendBox(self):
"""
When a binary box protocol sends a box, it should emit the serialized
bytes of that box to its transport.
"""
a = amp.BinaryBoxProtocol(self)
a.makeConnection(self)
aBox = amp.Box({b"testKey": b"valueTest",
b"someData": b"hello"})
a.makeConnection(self)
a.sendBox(aBox)
self.assertEqual(b''.join(self.data), aBox.serialize()) | When a binary box protocol sends a box, it should emit the serialized
bytes of that box to its transport. | test_sendBox | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_connectionLostStopSendingBoxes(self):
"""
When a binary box protocol loses its connection, it should notify its
box receiver that it has stopped receiving boxes.
"""
a = amp.BinaryBoxProtocol(self)
a.makeConnection(self)
connectionFailure = Failure(RuntimeError())
a.connectionLost(connectionFailure)
self.assertIs(self.stopReason, connectionFailure) | When a binary box protocol loses its connection, it should notify its
box receiver that it has stopped receiving boxes. | test_connectionLostStopSendingBoxes | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_protocolSwitch(self):
"""
L{BinaryBoxProtocol} has the capacity to switch to a different protocol
on a box boundary. When a protocol is in the process of switching, it
cannot receive traffic.
"""
otherProto = TestProto(None, b"outgoing data")
test = self
class SwitchyReceiver:
switched = False
def startReceivingBoxes(self, sender):
pass
def ampBoxReceived(self, box):
test.assertFalse(self.switched,
"Should only receive one box!")
self.switched = True
a._lockForSwitch()
a._switchTo(otherProto)
a = amp.BinaryBoxProtocol(SwitchyReceiver())
anyOldBox = amp.Box({b"include": b"lots",
b"of": b"data"})
a.makeConnection(self)
# Include a 0-length box at the beginning of the next protocol's data,
# to make sure that AMP doesn't eat the data or try to deliver extra
# boxes either...
moreThanOneBox = anyOldBox.serialize() + b"\x00\x00Hello, world!"
a.dataReceived(moreThanOneBox)
self.assertIs(otherProto.transport, self)
self.assertEqual(b"".join(otherProto.data), b"\x00\x00Hello, world!")
self.assertEqual(self.data, [b"outgoing data"])
a.dataReceived(b"more data")
self.assertEqual(b"".join(otherProto.data),
b"\x00\x00Hello, world!more data")
self.assertRaises(amp.ProtocolSwitched, a.sendBox, anyOldBox) | L{BinaryBoxProtocol} has the capacity to switch to a different protocol
on a box boundary. When a protocol is in the process of switching, it
cannot receive traffic. | test_protocolSwitch | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_protocolSwitchEmptyBuffer(self):
"""
After switching to a different protocol, if no extra bytes beyond
the switch box were delivered, an empty string is not passed to the
switched protocol's C{dataReceived} method.
"""
a = amp.BinaryBoxProtocol(self)
a.makeConnection(self)
otherProto = TestProto(None, b"")
a._switchTo(otherProto)
self.assertEqual(otherProto.data, []) | After switching to a different protocol, if no extra bytes beyond
the switch box were delivered, an empty string is not passed to the
switched protocol's C{dataReceived} method. | test_protocolSwitchEmptyBuffer | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_protocolSwitchInvalidStates(self):
"""
In order to make sure the protocol never gets any invalid data sent
into the middle of a box, it must be locked for switching before it is
switched. It can only be unlocked if the switch failed, and attempting
to send a box while it is locked should raise an exception.
"""
a = amp.BinaryBoxProtocol(self)
a.makeConnection(self)
sampleBox = amp.Box({b"some": b"data"})
a._lockForSwitch()
self.assertRaises(amp.ProtocolSwitched, a.sendBox, sampleBox)
a._unlockFromSwitch()
a.sendBox(sampleBox)
self.assertEqual(b''.join(self.data), sampleBox.serialize())
a._lockForSwitch()
otherProto = TestProto(None, b"outgoing data")
a._switchTo(otherProto)
self.assertRaises(amp.ProtocolSwitched, a._unlockFromSwitch) | In order to make sure the protocol never gets any invalid data sent
into the middle of a box, it must be locked for switching before it is
switched. It can only be unlocked if the switch failed, and attempting
to send a box while it is locked should raise an exception. | test_protocolSwitchInvalidStates | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_protocolSwitchLoseConnection(self):
"""
When the protocol is switched, it should notify its nested protocol of
disconnection.
"""
class Loser(protocol.Protocol):
reason = None
def connectionLost(self, reason):
self.reason = reason
connectionLoser = Loser()
a = amp.BinaryBoxProtocol(self)
a.makeConnection(self)
a._lockForSwitch()
a._switchTo(connectionLoser)
connectionFailure = Failure(RuntimeError())
a.connectionLost(connectionFailure)
self.assertEqual(connectionLoser.reason, connectionFailure) | When the protocol is switched, it should notify its nested protocol of
disconnection. | test_protocolSwitchLoseConnection | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_protocolSwitchLoseClientConnection(self):
"""
When the protocol is switched, it should notify its nested client
protocol factory of disconnection.
"""
class ClientLoser:
reason = None
def clientConnectionLost(self, connector, reason):
self.reason = reason
a = amp.BinaryBoxProtocol(self)
connectionLoser = protocol.Protocol()
clientLoser = ClientLoser()
a.makeConnection(self)
a._lockForSwitch()
a._switchTo(connectionLoser, clientLoser)
connectionFailure = Failure(RuntimeError())
a.connectionLost(connectionFailure)
self.assertEqual(clientLoser.reason, connectionFailure) | When the protocol is switched, it should notify its nested client
protocol factory of disconnection. | test_protocolSwitchLoseClientConnection | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_interfaceDeclarations(self):
"""
The classes in the amp module ought to implement the interfaces that
are declared for their benefit.
"""
for interface, implementation in [(amp.IBoxSender, amp.BinaryBoxProtocol),
(amp.IBoxReceiver, amp.BoxDispatcher),
(amp.IResponderLocator, amp.CommandLocator),
(amp.IResponderLocator, amp.SimpleStringLocator),
(amp.IBoxSender, amp.AMP),
(amp.IBoxReceiver, amp.AMP),
(amp.IResponderLocator, amp.AMP)]:
self.assertTrue(interface.implementedBy(implementation),
"%s does not implements(%s)" % (implementation, interface)) | The classes in the amp module ought to implement the interfaces that
are declared for their benefit. | test_interfaceDeclarations | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_helloWorld(self):
"""
Verify that a simple command can be sent and its response received with
the simple low-level string-based API.
"""
c, s, p = connectedServerAndClient()
L = []
HELLO = b'world'
c.sendHello(HELLO).addCallback(L.append)
p.flush()
self.assertEqual(L[0][b'hello'], HELLO) | Verify that a simple command can be sent and its response received with
the simple low-level string-based API. | test_helloWorld | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_wireFormatRoundTrip(self):
"""
Verify that mixed-case, underscored and dashed arguments are mapped to
their python names properly.
"""
c, s, p = connectedServerAndClient()
L = []
HELLO = b'world'
c.sendHello(HELLO).addCallback(L.append)
p.flush()
self.assertEqual(L[0][b'hello'], HELLO) | Verify that mixed-case, underscored and dashed arguments are mapped to
their python names properly. | test_wireFormatRoundTrip | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_helloWorldUnicode(self):
"""
Verify that unicode arguments can be encoded and decoded.
"""
c, s, p = connectedServerAndClient(
ServerClass=SimpleSymmetricCommandProtocol,
ClientClass=SimpleSymmetricCommandProtocol)
L = []
HELLO = b'world'
HELLO_UNICODE = u'wor\u1234ld'
c.sendUnicodeHello(HELLO, HELLO_UNICODE).addCallback(L.append)
p.flush()
self.assertEqual(L[0]['hello'], HELLO)
self.assertEqual(L[0]['Print'], HELLO_UNICODE) | Verify that unicode arguments can be encoded and decoded. | test_helloWorldUnicode | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_callRemoteStringRequiresAnswerFalse(self):
"""
L{BoxDispatcher.callRemoteString} returns L{None} if C{requiresAnswer}
is C{False}.
"""
c, s, p = connectedServerAndClient()
ret = c.callRemoteString(b"WTF", requiresAnswer=False)
self.assertIsNone(ret) | L{BoxDispatcher.callRemoteString} returns L{None} if C{requiresAnswer}
is C{False}. | test_callRemoteStringRequiresAnswerFalse | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def clearAndAdd(e):
"""
You can't propagate the error...
"""
e.trap(amp.UnhandledCommand)
return "OK" | You can't propagate the error... | test_unknownCommandLow.clearAndAdd | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_unknownCommandLow(self):
"""
Verify that unknown commands using low-level APIs will be rejected with an
error, but will NOT terminate the connection.
"""
c, s, p = connectedServerAndClient()
L = []
def clearAndAdd(e):
"""
You can't propagate the error...
"""
e.trap(amp.UnhandledCommand)
return "OK"
c.callRemoteString(b"WTF").addErrback(clearAndAdd).addCallback(L.append)
p.flush()
self.assertEqual(L.pop(), "OK")
HELLO = b'world'
c.sendHello(HELLO).addCallback(L.append)
p.flush()
self.assertEqual(L[0][b'hello'], HELLO) | Verify that unknown commands using low-level APIs will be rejected with an
error, but will NOT terminate the connection. | test_unknownCommandLow | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def clearAndAdd(e):
"""
You can't propagate the error...
"""
e.trap(amp.UnhandledCommand)
return "OK" | You can't propagate the error... | test_unknownCommandHigh.clearAndAdd | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_unknownCommandHigh(self):
"""
Verify that unknown commands using high-level APIs will be rejected with an
error, but will NOT terminate the connection.
"""
c, s, p = connectedServerAndClient()
L = []
def clearAndAdd(e):
"""
You can't propagate the error...
"""
e.trap(amp.UnhandledCommand)
return "OK"
c.callRemote(WTF).addErrback(clearAndAdd).addCallback(L.append)
p.flush()
self.assertEqual(L.pop(), "OK")
HELLO = b'world'
c.sendHello(HELLO).addCallback(L.append)
p.flush()
self.assertEqual(L[0][b'hello'], HELLO) | Verify that unknown commands using high-level APIs will be rejected with an
error, but will NOT terminate the connection. | test_unknownCommandHigh | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_brokenReturnValue(self):
"""
It can be very confusing if you write some code which responds to a
command, but gets the return value wrong. Most commonly you end up
returning None instead of a dictionary.
Verify that if that happens, the framework logs a useful error.
"""
L = []
SimpleSymmetricCommandProtocol().dispatchCommand(
amp.AmpBox(_command=BrokenReturn.commandName)).addErrback(L.append)
L[0].trap(amp.BadLocalReturn)
self.failUnlessIn('None', repr(L[0].value)) | It can be very confusing if you write some code which responds to a
command, but gets the return value wrong. Most commonly you end up
returning None instead of a dictionary.
Verify that if that happens, the framework logs a useful error. | test_brokenReturnValue | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_unknownArgument(self):
"""
Verify that unknown arguments are ignored, and not passed to a Python
function which can't accept them.
"""
c, s, p = connectedServerAndClient(
ServerClass=SimpleSymmetricCommandProtocol,
ClientClass=SimpleSymmetricCommandProtocol)
L = []
HELLO = b'world'
# c.sendHello(HELLO).addCallback(L.append)
c.callRemote(FutureHello,
hello=HELLO,
bonus=b"I'm not in the book!").addCallback(
L.append)
p.flush()
self.assertEqual(L[0]['hello'], HELLO) | Verify that unknown arguments are ignored, and not passed to a Python
function which can't accept them. | test_unknownArgument | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_simpleReprs(self):
"""
Verify that the various Box objects repr properly, for debugging.
"""
self.assertEqual(type(repr(amp._SwitchBox('a'))), str)
self.assertEqual(type(repr(amp.QuitBox())), str)
self.assertEqual(type(repr(amp.AmpBox())), str)
self.assertIn("AmpBox", repr(amp.AmpBox())) | Verify that the various Box objects repr properly, for debugging. | test_simpleReprs | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_innerProtocolInRepr(self):
"""
Verify that L{AMP} objects output their innerProtocol when set.
"""
otherProto = TestProto(None, b"outgoing data")
a = amp.AMP()
a.innerProtocol = otherProto
self.assertEqual(
repr(a), "<AMP inner <TestProto #%d> at 0x%x>" % (
otherProto.instanceId, id(a))) | Verify that L{AMP} objects output their innerProtocol when set. | test_innerProtocolInRepr | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_innerProtocolNotInRepr(self):
"""
Verify that L{AMP} objects do not output 'inner' when no innerProtocol
is set.
"""
a = amp.AMP()
self.assertEqual(repr(a), "<AMP at 0x%x>" % (id(a),)) | Verify that L{AMP} objects do not output 'inner' when no innerProtocol
is set. | test_innerProtocolNotInRepr | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_simpleSSLRepr(self):
"""
L{amp._TLSBox.__repr__} returns a string.
"""
self.assertEqual(type(repr(amp._TLSBox())), str) | L{amp._TLSBox.__repr__} returns a string. | test_simpleSSLRepr | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_keyTooLong(self):
"""
Verify that a key that is too long will immediately raise a synchronous
exception.
"""
c, s, p = connectedServerAndClient()
x = "H" * (0xff+1)
tl = self.assertRaises(amp.TooLong,
c.callRemoteString, b"Hello",
**{x: b"hi"})
self.assertTrue(tl.isKey)
self.assertTrue(tl.isLocal)
self.assertIsNone(tl.keyName)
self.assertEqual(tl.value, x.encode("ascii"))
self.assertIn(str(len(x)), repr(tl))
self.assertIn("key", repr(tl)) | Verify that a key that is too long will immediately raise a synchronous
exception. | test_keyTooLong | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_valueTooLong(self):
"""
Verify that attempting to send value longer than 64k will immediately
raise an exception.
"""
c, s, p = connectedServerAndClient()
x = b"H" * (0xffff+1)
tl = self.assertRaises(amp.TooLong, c.sendHello, x)
p.flush()
self.assertFalse(tl.isKey)
self.assertTrue(tl.isLocal)
self.assertEqual(tl.keyName, b'hello')
self.failUnlessIdentical(tl.value, x)
self.assertIn(str(len(x)), repr(tl))
self.assertIn("value", repr(tl))
self.assertIn('hello', repr(tl)) | Verify that attempting to send value longer than 64k will immediately
raise an exception. | test_valueTooLong | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_helloWorldCommand(self):
"""
Verify that a simple command can be sent and its response received with
the high-level value parsing API.
"""
c, s, p = connectedServerAndClient(
ServerClass=SimpleSymmetricCommandProtocol,
ClientClass=SimpleSymmetricCommandProtocol)
L = []
HELLO = b'world'
c.sendHello(HELLO).addCallback(L.append)
p.flush()
self.assertEqual(L[0]['hello'], HELLO) | Verify that a simple command can be sent and its response received with
the high-level value parsing API. | test_helloWorldCommand | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_helloErrorHandling(self):
"""
Verify that if a known error type is raised and handled, it will be
properly relayed to the other end of the connection and translated into
an exception, and no error will be logged.
"""
L=[]
c, s, p = connectedServerAndClient(
ServerClass=SimpleSymmetricCommandProtocol,
ClientClass=SimpleSymmetricCommandProtocol)
HELLO = b'fuck you'
c.sendHello(HELLO).addErrback(L.append)
p.flush()
L[0].trap(UnfriendlyGreeting)
self.assertEqual(str(L[0].value), "Don't be a dick.") | Verify that if a known error type is raised and handled, it will be
properly relayed to the other end of the connection and translated into
an exception, and no error will be logged. | test_helloErrorHandling | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_helloFatalErrorHandling(self):
"""
Verify that if a known, fatal error type is raised and handled, it will
be properly relayed to the other end of the connection and translated
into an exception, no error will be logged, and the connection will be
terminated.
"""
L=[]
c, s, p = connectedServerAndClient(
ServerClass=SimpleSymmetricCommandProtocol,
ClientClass=SimpleSymmetricCommandProtocol)
HELLO = b'die'
c.sendHello(HELLO).addErrback(L.append)
p.flush()
L.pop().trap(DeathThreat)
c.sendHello(HELLO).addErrback(L.append)
p.flush()
L.pop().trap(error.ConnectionDone) | Verify that if a known, fatal error type is raised and handled, it will
be properly relayed to the other end of the connection and translated
into an exception, no error will be logged, and the connection will be
terminated. | test_helloFatalErrorHandling | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_helloNoErrorHandling(self):
"""
Verify that if an unknown error type is raised, it will be relayed to
the other end of the connection and translated into an exception, it
will be logged, and then the connection will be dropped.
"""
L=[]
c, s, p = connectedServerAndClient(
ServerClass=SimpleSymmetricCommandProtocol,
ClientClass=SimpleSymmetricCommandProtocol)
HELLO = THING_I_DONT_UNDERSTAND
c.sendHello(HELLO).addErrback(L.append)
p.flush()
ure = L.pop()
ure.trap(amp.UnknownRemoteError)
c.sendHello(HELLO).addErrback(L.append)
cl = L.pop()
cl.trap(error.ConnectionDone)
# The exception should have been logged.
self.assertTrue(self.flushLoggedErrors(ThingIDontUnderstandError)) | Verify that if an unknown error type is raised, it will be relayed to
the other end of the connection and translated into an exception, it
will be logged, and then the connection will be dropped. | test_helloNoErrorHandling | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_lateAnswer(self):
"""
Verify that a command that does not get answered until after the
connection terminates will not cause any errors.
"""
c, s, p = connectedServerAndClient(
ServerClass=SimpleSymmetricCommandProtocol,
ClientClass=SimpleSymmetricCommandProtocol)
L = []
c.callRemote(WaitForever).addErrback(L.append)
p.flush()
self.assertEqual(L, [])
s.transport.loseConnection()
p.flush()
L.pop().trap(error.ConnectionDone)
# Just make sure that it doesn't error...
s.waiting.callback({})
return s.waiting | Verify that a command that does not get answered until after the
connection terminates will not cause any errors. | test_lateAnswer | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_requiresNoAnswer(self):
"""
Verify that a command that requires no answer is run.
"""
c, s, p = connectedServerAndClient(
ServerClass=SimpleSymmetricCommandProtocol,
ClientClass=SimpleSymmetricCommandProtocol)
HELLO = b'world'
c.callRemote(NoAnswerHello, hello=HELLO)
p.flush()
self.assertTrue(s.greeted) | Verify that a command that requires no answer is run. | test_requiresNoAnswer | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_requiresNoAnswerFail(self):
"""
Verify that commands sent after a failed no-answer request do not complete.
"""
L=[]
c, s, p = connectedServerAndClient(
ServerClass=SimpleSymmetricCommandProtocol,
ClientClass=SimpleSymmetricCommandProtocol)
HELLO = b'fuck you'
c.callRemote(NoAnswerHello, hello=HELLO)
p.flush()
# This should be logged locally.
self.assertTrue(self.flushLoggedErrors(amp.RemoteAmpError))
HELLO = b'world'
c.callRemote(Hello, hello=HELLO).addErrback(L.append)
p.flush()
L.pop().trap(error.ConnectionDone)
self.assertFalse(s.greeted) | Verify that commands sent after a failed no-answer request do not complete. | test_requiresNoAnswerFail | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_noAnswerResponderBadAnswer(self):
"""
Verify that responders of requiresAnswer=False commands have to return
a dictionary anyway.
(requiresAnswer is a hint from the _client_ - the server may be called
upon to answer commands in any case, if the client wants to know when
they complete.)
"""
c, s, p = connectedServerAndClient(
ServerClass=BadNoAnswerCommandProtocol,
ClientClass=SimpleSymmetricCommandProtocol)
c.callRemote(NoAnswerHello, hello=b"hello")
p.flush()
le = self.flushLoggedErrors(amp.BadLocalReturn)
self.assertEqual(len(le), 1) | Verify that responders of requiresAnswer=False commands have to return
a dictionary anyway.
(requiresAnswer is a hint from the _client_ - the server may be called
upon to answer commands in any case, if the client wants to know when
they complete.) | test_noAnswerResponderBadAnswer | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_noAnswerResponderAskedForAnswer(self):
"""
Verify that responders with requiresAnswer=False will actually respond
if the client sets requiresAnswer=True. In other words, verify that
requiresAnswer is a hint honored only by the client.
"""
c, s, p = connectedServerAndClient(
ServerClass=NoAnswerCommandProtocol,
ClientClass=SimpleSymmetricCommandProtocol)
L = []
c.callRemote(Hello, hello=b"Hello!").addCallback(L.append)
p.flush()
self.assertEqual(len(L), 1)
self.assertEqual(L, [dict(hello=b"Hello!-noanswer",
Print=None)]) # Optional response argument | Verify that responders with requiresAnswer=False will actually respond
if the client sets requiresAnswer=True. In other words, verify that
requiresAnswer is a hint honored only by the client. | test_noAnswerResponderAskedForAnswer | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_ampListCommand(self):
"""
Test encoding of an argument that uses the AmpList encoding.
"""
c, s, p = connectedServerAndClient(
ServerClass=SimpleSymmetricCommandProtocol,
ClientClass=SimpleSymmetricCommandProtocol)
L = []
c.callRemote(GetList, length=10).addCallback(L.append)
p.flush()
values = L.pop().get('body')
self.assertEqual(values, [{'x': 1}] * 10) | Test encoding of an argument that uses the AmpList encoding. | test_ampListCommand | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_optionalAmpListOmitted(self):
"""
Sending a command with an omitted AmpList argument that is
designated as optional does not raise an InvalidSignature error.
"""
c, s, p = connectedServerAndClient(
ServerClass=SimpleSymmetricCommandProtocol,
ClientClass=SimpleSymmetricCommandProtocol)
L = []
c.callRemote(DontRejectMe, magicWord=u'please').addCallback(L.append)
p.flush()
response = L.pop().get('response')
self.assertEqual(response, 'list omitted') | Sending a command with an omitted AmpList argument that is
designated as optional does not raise an InvalidSignature error. | test_optionalAmpListOmitted | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_optionalAmpListPresent(self):
"""
Sanity check that optional AmpList arguments are processed normally.
"""
c, s, p = connectedServerAndClient(
ServerClass=SimpleSymmetricCommandProtocol,
ClientClass=SimpleSymmetricCommandProtocol)
L = []
c.callRemote(DontRejectMe, magicWord=u'please',
list=[{'name': u'foo'}]).addCallback(L.append)
p.flush()
response = L.pop().get('response')
self.assertEqual(response, 'foo accepted') | Sanity check that optional AmpList arguments are processed normally. | test_optionalAmpListPresent | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_failEarlyOnArgSending(self):
"""
Verify that if we pass an invalid argument list (omitting an argument),
an exception will be raised.
"""
self.assertRaises(amp.InvalidSignature, Hello) | Verify that if we pass an invalid argument list (omitting an argument),
an exception will be raised. | test_failEarlyOnArgSending | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_doubleProtocolSwitch(self):
"""
As a debugging aid, a protocol system should raise a
L{ProtocolSwitched} exception when asked to switch a protocol that is
already switched.
"""
serverDeferred = defer.Deferred()
serverProto = SimpleSymmetricCommandProtocol(serverDeferred)
clientDeferred = defer.Deferred()
clientProto = SimpleSymmetricCommandProtocol(clientDeferred)
c, s, p = connectedServerAndClient(ServerClass=lambda: serverProto,
ClientClass=lambda: clientProto)
def switched(result):
self.assertRaises(amp.ProtocolSwitched, c.switchToTestProtocol)
self.testSucceeded = True
c.switchToTestProtocol().addCallback(switched)
p.flush()
self.assertTrue(self.testSucceeded) | As a debugging aid, a protocol system should raise a
L{ProtocolSwitched} exception when asked to switch a protocol that is
already switched. | test_doubleProtocolSwitch | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_protocolSwitch(self, switcher=SimpleSymmetricCommandProtocol,
spuriousTraffic=False,
spuriousError=False):
"""
Verify that it is possible to switch to another protocol mid-connection and
send data to it successfully.
"""
self.testSucceeded = False
serverDeferred = defer.Deferred()
serverProto = switcher(serverDeferred)
clientDeferred = defer.Deferred()
clientProto = switcher(clientDeferred)
c, s, p = connectedServerAndClient(ServerClass=lambda: serverProto,
ClientClass=lambda: clientProto)
if spuriousTraffic:
wfdr = [] # remote
c.callRemote(WaitForever).addErrback(wfdr.append)
switchDeferred = c.switchToTestProtocol()
if spuriousTraffic:
self.assertRaises(amp.ProtocolSwitched, c.sendHello, b'world')
def cbConnsLost(info):
((serverSuccess, serverData), (clientSuccess, clientData)) = info
self.assertTrue(serverSuccess)
self.assertTrue(clientSuccess)
self.assertEqual(b''.join(serverData), SWITCH_CLIENT_DATA)
self.assertEqual(b''.join(clientData), SWITCH_SERVER_DATA)
self.testSucceeded = True
def cbSwitch(proto):
return defer.DeferredList(
[serverDeferred, clientDeferred]).addCallback(cbConnsLost)
switchDeferred.addCallback(cbSwitch)
p.flush()
if serverProto.maybeLater is not None:
serverProto.maybeLater.callback(serverProto.maybeLaterProto)
p.flush()
if spuriousTraffic:
# switch is done here; do this here to make sure that if we're
# going to corrupt the connection, we do it before it's closed.
if spuriousError:
s.waiting.errback(amp.RemoteAmpError(
b"SPURIOUS",
"Here's some traffic in the form of an error."))
else:
s.waiting.callback({})
p.flush()
c.transport.loseConnection() # close it
p.flush()
self.assertTrue(self.testSucceeded) | Verify that it is possible to switch to another protocol mid-connection and
send data to it successfully. | test_protocolSwitch | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_protocolSwitchDeferred(self):
"""
Verify that protocol-switching even works if the value returned from
the command that does the switch is deferred.
"""
return self.test_protocolSwitch(switcher=DeferredSymmetricCommandProtocol) | Verify that protocol-switching even works if the value returned from
the command that does the switch is deferred. | test_protocolSwitchDeferred | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_protocolSwitchFail(self, switcher=SimpleSymmetricCommandProtocol):
"""
Verify that if we try to switch protocols and it fails, the connection
stays up and we can go back to speaking AMP.
"""
self.testSucceeded = False
serverDeferred = defer.Deferred()
serverProto = switcher(serverDeferred)
clientDeferred = defer.Deferred()
clientProto = switcher(clientDeferred)
c, s, p = connectedServerAndClient(ServerClass=lambda: serverProto,
ClientClass=lambda: clientProto)
L = []
c.switchToTestProtocol(fail=True).addErrback(L.append)
p.flush()
L.pop().trap(UnknownProtocol)
self.assertFalse(self.testSucceeded)
# It's a known error, so let's send a "hello" on the same connection;
# it should work.
c.sendHello(b'world').addCallback(L.append)
p.flush()
self.assertEqual(L.pop()['hello'], b'world') | Verify that if we try to switch protocols and it fails, the connection
stays up and we can go back to speaking AMP. | test_protocolSwitchFail | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_trafficAfterSwitch(self):
"""
Verify that attempts to send traffic after a switch will not corrupt
the nested protocol.
"""
return self.test_protocolSwitch(spuriousTraffic=True) | Verify that attempts to send traffic after a switch will not corrupt
the nested protocol. | test_trafficAfterSwitch | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_errorAfterSwitch(self):
"""
Returning an error after a protocol switch should record the underlying
error.
"""
return self.test_protocolSwitch(spuriousTraffic=True,
spuriousError=True) | Returning an error after a protocol switch should record the underlying
error. | test_errorAfterSwitch | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_quitBoxQuits(self):
"""
Verify that commands with a responseType of QuitBox will in fact
terminate the connection.
"""
c, s, p = connectedServerAndClient(
ServerClass=SimpleSymmetricCommandProtocol,
ClientClass=SimpleSymmetricCommandProtocol)
L = []
HELLO = b'world'
GOODBYE = b'everyone'
c.sendHello(HELLO).addCallback(L.append)
p.flush()
self.assertEqual(L.pop()['hello'], HELLO)
c.callRemote(Goodbye).addCallback(L.append)
p.flush()
self.assertEqual(L.pop()['goodbye'], GOODBYE)
c.sendHello(HELLO).addErrback(L.append)
L.pop().trap(error.ConnectionDone) | Verify that commands with a responseType of QuitBox will in fact
terminate the connection. | test_quitBoxQuits | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_basicLiteralEmit(self):
"""
Verify that the command dictionaries for a callRemoteN look correct
after being serialized and parsed.
"""
c, s, p = connectedServerAndClient()
L = []
s.ampBoxReceived = L.append
c.callRemote(Hello, hello=b'hello test', mixedCase=b'mixed case arg test',
dash_arg=b'x', underscore_arg=b'y')
p.flush()
self.assertEqual(len(L), 1)
for k, v in [(b'_command', Hello.commandName),
(b'hello', b'hello test'),
(b'mixedCase', b'mixed case arg test'),
(b'dash-arg', b'x'),
(b'underscore_arg', b'y')]:
self.assertEqual(L[-1].pop(k), v)
L[-1].pop(b'_ask')
self.assertEqual(L[-1], {}) | Verify that the command dictionaries for a callRemoteN look correct
after being serialized and parsed. | test_basicLiteralEmit | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_basicStructuredEmit(self):
"""
Verify that a call similar to basicLiteralEmit's is handled properly with
high-level quoting and passing to Python methods, and that argument
names are correctly handled.
"""
L = []
class StructuredHello(amp.AMP):
def h(self, *a, **k):
L.append((a, k))
return dict(hello=b'aaa')
Hello.responder(h)
c, s, p = connectedServerAndClient(ServerClass=StructuredHello)
c.callRemote(Hello, hello=b'hello test', mixedCase=b'mixed case arg test',
dash_arg=b'x', underscore_arg=b'y').addCallback(L.append)
p.flush()
self.assertEqual(len(L), 2)
self.assertEqual(L[0],
((), dict(
hello=b'hello test',
mixedCase=b'mixed case arg test',
dash_arg=b'x',
underscore_arg=b'y',
From=s.transport.getPeer(),
# XXX - should optional arguments just not be passed?
# passing None seems a little odd, looking at the way it
# turns out here... -glyph
Print=None,
optional=None,
)))
self.assertEqual(L[1], dict(Print=None, hello=b'aaa')) | Verify that a call similar to basicLiteralEmit's is handled properly with
high-level quoting and passing to Python methods, and that argument
names are correctly handled. | test_basicStructuredEmit | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def iosimVerify(self, otherCert):
"""
This isn't a real certificate, and wouldn't work on a real socket, but
iosim specifies a different API so that we don't have to do any crypto
math to demonstrate that the right functions get called in the right
places.
"""
assert otherCert is self
self.verifyCount += 1
return True | This isn't a real certificate, and wouldn't work on a real socket, but
iosim specifies a different API so that we don't have to do any crypto
math to demonstrate that the right functions get called in the right
places. | iosimVerify | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_startingTLS(self):
"""
Verify that starting TLS and succeeding at handshaking sends all the
notifications to all the right places.
"""
cli, svr, p = connectedServerAndClient(
ServerClass=SecurableProto,
ClientClass=SecurableProto)
okc = OKCert()
svr.certFactory = lambda : okc
cli.callRemote(
amp.StartTLS, tls_localCertificate=okc,
tls_verifyAuthorities=[PretendRemoteCertificateAuthority()])
# let's buffer something to be delivered securely
L = []
cli.callRemote(SecuredPing).addCallback(L.append)
p.flush()
# once for client once for server
self.assertEqual(okc.verifyCount, 2)
L = []
cli.callRemote(SecuredPing).addCallback(L.append)
p.flush()
self.assertEqual(L[0], {'pinged': True}) | Verify that starting TLS and succeeding at handshaking sends all the
notifications to all the right places. | test_startingTLS | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_startTooManyTimes(self):
"""
Verify that the protocol will complain if we attempt to renegotiate TLS,
which we don't support.
"""
cli, svr, p = connectedServerAndClient(
ServerClass=SecurableProto,
ClientClass=SecurableProto)
okc = OKCert()
svr.certFactory = lambda : okc
cli.callRemote(amp.StartTLS,
tls_localCertificate=okc,
tls_verifyAuthorities=[PretendRemoteCertificateAuthority()])
p.flush()
cli.noPeerCertificate = True # this is totally fake
self.assertRaises(
amp.OnlyOneTLS,
cli.callRemote,
amp.StartTLS,
tls_localCertificate=okc,
tls_verifyAuthorities=[PretendRemoteCertificateAuthority()]) | Verify that the protocol will complain if we attempt to renegotiate TLS,
which we don't support. | test_startTooManyTimes | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_negotiationFailed(self):
"""
Verify that starting TLS and failing on both sides at handshaking sends
notifications to all the right places and terminates the connection.
"""
badCert = GrumpyCert()
cli, svr, p = connectedServerAndClient(
ServerClass=SecurableProto,
ClientClass=SecurableProto)
svr.certFactory = lambda : badCert
cli.callRemote(amp.StartTLS,
tls_localCertificate=badCert)
p.flush()
# once for client once for server - but both fail
self.assertEqual(badCert.verifyCount, 2)
d = cli.callRemote(SecuredPing)
p.flush()
self.assertFailure(d, iosim.NativeOpenSSLError) | Verify that starting TLS and failing on both sides at handshaking sends
notifications to all the right places and terminates the connection. | test_negotiationFailed | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_negotiationFailedByClosing(self):
"""
Verify that starting TLS and failing by way of a lost connection
notices that it is probably an SSL problem.
"""
cli, svr, p = connectedServerAndClient(
ServerClass=SecurableProto,
ClientClass=SecurableProto)
droppyCert = DroppyCert(svr.transport)
svr.certFactory = lambda : droppyCert
cli.callRemote(amp.StartTLS, tls_localCertificate=droppyCert)
p.flush()
self.assertEqual(droppyCert.verifyCount, 2)
d = cli.callRemote(SecuredPing)
p.flush()
# it might be a good idea to move this exception somewhere more
# reasonable.
self.assertFailure(d, error.PeerVerifyError) | Verify that starting TLS and failing by way of a lost connection
notices that it is probably an SSL problem. | test_negotiationFailedByClosing | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def setUp(self):
"""
Disable ssl in amp.
"""
self.ssl = amp.ssl
amp.ssl = None | Disable ssl in amp. | setUp | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def tearDown(self):
"""
Restore ssl module.
"""
amp.ssl = self.ssl | Restore ssl module. | tearDown | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_callRemoteError(self):
"""
Check that callRemote raises an exception when called with a
L{amp.StartTLS}.
"""
cli, svr, p = connectedServerAndClient(
ServerClass=SecurableProto,
ClientClass=SecurableProto)
okc = OKCert()
svr.certFactory = lambda : okc
return self.assertFailure(cli.callRemote(
amp.StartTLS, tls_localCertificate=okc,
tls_verifyAuthorities=[PretendRemoteCertificateAuthority()]),
RuntimeError) | Check that callRemote raises an exception when called with a
L{amp.StartTLS}. | test_callRemoteError | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_messageReceivedError(self):
"""
When a client with SSL enabled talks to a server without SSL, it
should return a meaningful error.
"""
svr = SecurableProto()
okc = OKCert()
svr.certFactory = lambda : okc
box = amp.Box()
box[b'_command'] = b'StartTLS'
box[b'_ask'] = b'1'
boxes = []
svr.sendBox = boxes.append
svr.makeConnection(StringTransport())
svr.ampBoxReceived(box)
self.assertEqual(boxes,
[{b'_error_code': b'TLS_ERROR',
b'_error': b'1',
b'_error_description': b'TLS not available'}]) | When a client with SSL enabled talks to a server without SSL, it
should return a meaningful error. | test_messageReceivedError | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def errorCheck(self, err, proto, cmd, **kw):
"""
Check that the appropriate kind of error is raised when a given command
is sent to a given protocol.
"""
c, s, p = connectedServerAndClient(ServerClass=proto,
ClientClass=proto)
d = c.callRemote(cmd, **kw)
d2 = self.failUnlessFailure(d, err)
p.flush()
return d2 | Check that the appropriate kind of error is raised when a given command
is sent to a given protocol. | errorCheck | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_basicErrorPropagation(self):
"""
Verify that errors specified in a superclass are respected normally
even if it has subclasses.
"""
return self.errorCheck(
InheritedError, NormalCommandProtocol, BaseCommand) | Verify that errors specified in a superclass are respected normally
even if it has subclasses. | test_basicErrorPropagation | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_inheritedErrorPropagation(self):
"""
Verify that errors specified in a superclass command are propagated to
its subclasses.
"""
return self.errorCheck(
InheritedError, InheritedCommandProtocol, InheritedCommand) | Verify that errors specified in a superclass command are propagated to
its subclasses. | test_inheritedErrorPropagation | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_inheritedErrorAddition(self):
"""
Verify that new errors specified in a subclass of an existing command
are honored even if the superclass defines some errors.
"""
return self.errorCheck(
OtherInheritedError, AddedCommandProtocol, AddErrorsCommand, other=True) | Verify that new errors specified in a subclass of an existing command
are honored even if the superclass defines some errors. | test_inheritedErrorAddition | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_additionWithOriginalError(self):
"""
Verify that errors specified in a command's superclass are respected
even if that command defines new errors itself.
"""
return self.errorCheck(
InheritedError, AddedCommandProtocol, AddErrorsCommand, other=False) | Verify that errors specified in a command's superclass are respected
even if that command defines new errors itself. | test_additionWithOriginalError | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def setUp(self):
"""
Create an amp server and connect a client to it.
"""
from twisted.internet import reactor
self.serverFactory = protocol.ServerFactory()
self.serverFactory.protocol = self.serverProto
self.clientFactory = protocol.ClientFactory()
self.clientFactory.protocol = self.clientProto
self.clientFactory.onMade = defer.Deferred()
self.serverFactory.onMade = defer.Deferred()
self.serverPort = reactor.listenTCP(0, self.serverFactory)
self.addCleanup(self.serverPort.stopListening)
self.clientConn = reactor.connectTCP(
'127.0.0.1', self.serverPort.getHost().port,
self.clientFactory)
self.addCleanup(self.clientConn.disconnect)
def getProtos(rlst):
self.cli = self.clientFactory.theProto
self.svr = self.serverFactory.theProto
dl = defer.DeferredList([self.clientFactory.onMade,
self.serverFactory.onMade])
return dl.addCallback(getProtos) | Create an amp server and connect a client to it. | setUp | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def tearDown(self):
"""
Cleanup client and server connections, and check the error got at
C{connectionLost}.
"""
L = []
for conn in self.cli, self.svr:
if conn.transport is not None:
# depend on amp's function connection-dropping behavior
d = defer.Deferred().addErrback(_loseAndPass, conn)
conn.connectionLost = d.errback
conn.transport.loseConnection()
L.append(d)
return defer.gatherResults(L
).addErrback(lambda first: first.value.subFailure) | Cleanup client and server connections, and check the error got at
C{connectionLost}. | tearDown | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_liveFireCustomTLS(self):
"""
Using real, live TLS, actually negotiate a connection.
This also looks at the 'peerCertificate' attribute's correctness, since
that's actually loaded using OpenSSL calls, but the main purpose is to
make sure that we didn't miss anything obvious in iosim about TLS
negotiations.
"""
cert = tempcert
self.svr.verifyFactory = lambda : [cert]
self.svr.certFactory = lambda : cert
# only needed on the server, we specify the client below.
def secured(rslt):
x = cert.digest()
def pinged(rslt2):
# Interesting. OpenSSL won't even _tell_ us about the peer
# cert until we negotiate. we should be able to do this in
# 'secured' instead, but it looks like we can't. I think this
# is a bug somewhere far deeper than here.
self.assertEqual(x, self.cli.hostCertificate.digest())
self.assertEqual(x, self.cli.peerCertificate.digest())
self.assertEqual(x, self.svr.hostCertificate.digest())
self.assertEqual(x, self.svr.peerCertificate.digest())
return self.cli.callRemote(SecuredPing).addCallback(pinged)
return self.cli.callRemote(amp.StartTLS,
tls_localCertificate=cert,
tls_verifyAuthorities=[cert]).addCallback(secured) | Using real, live TLS, actually negotiate a connection.
This also looks at the 'peerCertificate' attribute's correctness, since
that's actually loaded using OpenSSL calls, but the main purpose is to
make sure that we didn't miss anything obvious in iosim about TLS
negotiations. | test_liveFireCustomTLS | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def getTLSVars(self):
"""
@return: the global C{tempcert} certificate as local certificate.
"""
return dict(tls_localCertificate=tempcert) | @return: the global C{tempcert} certificate as local certificate. | getTLSVars | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_liveFireDefaultTLS(self):
"""
Verify that out of the box, we can start TLS to at least encrypt the
connection, even if we don't have any certificates to use.
"""
def secured(result):
return self.cli.callRemote(SecuredPing)
return self.cli.callRemote(amp.StartTLS).addCallback(secured) | Verify that out of the box, we can start TLS to at least encrypt the
connection, even if we don't have any certificates to use. | test_liveFireDefaultTLS | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_anonymousVerifyingClient(self):
"""
Verify that anonymous clients can verify server certificates.
"""
def secured(result):
return self.cli.callRemote(SecuredPing)
return self.cli.callRemote(amp.StartTLS,
tls_verifyAuthorities=[tempcert]
).addCallback(secured) | Verify that anonymous clients can verify server certificates. | test_anonymousVerifyingClient | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def fromStringProto(self, string, protocol):
"""
Don't decode anything; just return all possible information.
@return: A two-tuple of the input string and the protocol.
"""
return (string, protocol) | Don't decode anything; just return all possible information.
@return: A two-tuple of the input string and the protocol. | fromStringProto | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def toStringProto(self, obj, protocol):
"""
Encode identifying information about L{object} and protocol
into a string for later verification.
@type obj: L{object}
@type protocol: L{amp.AMP}
"""
ident = u"%d:%d" % (id(obj), id(protocol))
return ident.encode("ascii") | Encode identifying information about L{object} and protocol
into a string for later verification.
@type obj: L{object}
@type protocol: L{amp.AMP} | toStringProto | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def parseResponse(self, strings, protocol):
"""
Don't do any parsing, just jam the input strings and protocol
onto the C{protocol.parseResponseArguments} attribute as a
two-tuple. Return the original strings.
"""
protocol.parseResponseArguments = (strings, protocol)
return strings | Don't do any parsing, just jam the input strings and protocol
onto the C{protocol.parseResponseArguments} attribute as a
two-tuple. Return the original strings. | parseResponse | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def parseArguments(cls, strings, protocol):
"""
Don't do any parsing, just jam the input strings and protocol
onto the C{protocol.parseArgumentsArguments} attribute as a
two-tuple. Return the original strings.
"""
protocol.parseArgumentsArguments = (strings, protocol)
return strings | Don't do any parsing, just jam the input strings and protocol
onto the C{protocol.parseArgumentsArguments} attribute as a
two-tuple. Return the original strings. | parseArguments | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def makeArguments(cls, objects, protocol):
"""
Don't do any serializing, just jam the input strings and protocol
onto the C{protocol.makeArgumentsArguments} attribute as a
two-tuple. Return the original strings.
"""
protocol.makeArgumentsArguments = (objects, protocol)
return objects | Don't do any serializing, just jam the input strings and protocol
onto the C{protocol.makeArgumentsArguments} attribute as a
two-tuple. Return the original strings. | makeArguments | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def _sendBoxCommand(self, commandName, strings, requiresAnswer):
"""
Return a Deferred which fires with the original strings.
"""
return defer.succeed(strings) | Return a Deferred which fires with the original strings. | _sendBoxCommand | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_argumentInterface(self):
"""
L{Argument} instances provide L{amp.IArgumentType}.
"""
self.assertTrue(verifyObject(amp.IArgumentType, amp.Argument())) | L{Argument} instances provide L{amp.IArgumentType}. | test_argumentInterface | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_parseResponse(self):
"""
There should be a class method of Command which accepts a
mapping of argument names to serialized forms and returns a
similar mapping whose values have been parsed via the
Command's response schema.
"""
protocol = object()
result = b'whatever'
strings = {b'weird': result}
self.assertEqual(
ProtocolIncludingCommand.parseResponse(strings, protocol),
{'weird': (result, protocol)}) | There should be a class method of Command which accepts a
mapping of argument names to serialized forms and returns a
similar mapping whose values have been parsed via the
Command's response schema. | test_parseResponse | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_callRemoteCallsParseResponse(self):
"""
Making a remote call on a L{amp.Command} subclass which
overrides the C{parseResponse} method should call that
C{parseResponse} method to get the response.
"""
client = NoNetworkProtocol()
thingy = b"weeoo"
response = client.callRemote(MagicSchemaCommand, weird=thingy)
def gotResponse(ign):
self.assertEqual(client.parseResponseArguments,
({"weird": thingy}, client))
response.addCallback(gotResponse)
return response | Making a remote call on a L{amp.Command} subclass which
overrides the C{parseResponse} method should call that
C{parseResponse} method to get the response. | test_callRemoteCallsParseResponse | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_parseArguments(self):
"""
There should be a class method of L{amp.Command} which accepts
a mapping of argument names to serialized forms and returns a
similar mapping whose values have been parsed via the
command's argument schema.
"""
protocol = object()
result = b'whatever'
strings = {b'weird': result}
self.assertEqual(
ProtocolIncludingCommand.parseArguments(strings, protocol),
{'weird': (result, protocol)}) | There should be a class method of L{amp.Command} which accepts
a mapping of argument names to serialized forms and returns a
similar mapping whose values have been parsed via the
command's argument schema. | test_parseArguments | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_responderCallsParseArguments(self):
"""
Making a remote call on a L{amp.Command} subclass which
overrides the C{parseArguments} method should call that
C{parseArguments} method to get the arguments.
"""
protocol = NoNetworkProtocol()
responder = protocol.locateResponder(MagicSchemaCommand.commandName)
argument = object()
response = responder(dict(weird=argument))
response.addCallback(
lambda ign: self.assertEqual(protocol.parseArgumentsArguments,
({"weird": argument}, protocol)))
return response | Making a remote call on a L{amp.Command} subclass which
overrides the C{parseArguments} method should call that
C{parseArguments} method to get the arguments. | test_responderCallsParseArguments | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_makeArguments(self):
"""
There should be a class method of L{amp.Command} which accepts
a mapping of argument names to objects and returns a similar
mapping whose values have been serialized via the command's
argument schema.
"""
protocol = object()
argument = object()
objects = {'weird': argument}
ident = u"%d:%d" % (id(argument), id(protocol))
self.assertEqual(
ProtocolIncludingCommand.makeArguments(objects, protocol),
{b'weird': ident.encode("ascii")}) | There should be a class method of L{amp.Command} which accepts
a mapping of argument names to objects and returns a similar
mapping whose values have been serialized via the command's
argument schema. | test_makeArguments | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
def test_makeArgumentsUsesCommandType(self):
"""
L{amp.Command.makeArguments}'s return type should be the type
of the result of L{amp.Command.commandType}.
"""
protocol = object()
objects = {"weird": b"whatever"}
result = ProtocolIncludingCommandWithDifferentCommandType.makeArguments(
objects, protocol)
self.assertIs(type(result), MyBox) | L{amp.Command.makeArguments}'s return type should be the type
of the result of L{amp.Command.commandType}. | test_makeArgumentsUsesCommandType | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py | MIT |
Subsets and Splits