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 test_callRemoteCallsMakeArguments(self):
"""
Making a remote call on a L{amp.Command} subclass which
overrides the C{makeArguments} method should call that
C{makeArguments} method to get the response.
"""
client = NoNetworkProtocol()
argument = object()
response = client.callRemote(MagicSchemaCommand, weird=argument)
def gotResponse(ign):
self.assertEqual(client.makeArgumentsArguments,
({"weird": argument}, client))
response.addCallback(gotResponse)
return response | Making a remote call on a L{amp.Command} subclass which
overrides the C{makeArguments} method should call that
C{makeArguments} method to get the response. | test_callRemoteCallsMakeArguments | 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_extraArgumentsDisallowed(self):
"""
L{Command.makeArguments} raises L{amp.InvalidSignature} if the objects
dictionary passed to it includes a key which does not correspond to the
Python identifier for a defined argument.
"""
self.assertRaises(
amp.InvalidSignature,
Hello.makeArguments,
dict(hello="hello", bogusArgument=object()), None) | L{Command.makeArguments} raises L{amp.InvalidSignature} if the objects
dictionary passed to it includes a key which does not correspond to the
Python identifier for a defined argument. | test_extraArgumentsDisallowed | 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_wireSpellingDisallowed(self):
"""
If a command argument conflicts with a Python keyword, the
untransformed argument name is not allowed as a key in the dictionary
passed to L{Command.makeArguments}. If it is supplied,
L{amp.InvalidSignature} is raised.
This may be a pointless implementation restriction which may be lifted.
The current behavior is tested to verify that such arguments are not
silently dropped on the floor (the previous behavior).
"""
self.assertRaises(
amp.InvalidSignature,
Hello.makeArguments,
dict(hello="required", **{"print": "print value"}),
None) | If a command argument conflicts with a Python keyword, the
untransformed argument name is not allowed as a key in the dictionary
passed to L{Command.makeArguments}. If it is supplied,
L{amp.InvalidSignature} is raised.
This may be a pointless implementation restriction which may be lifted.
The current behavior is tested to verify that such arguments are not
silently dropped on the floor (the previous behavior). | test_wireSpellingDisallowed | 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_commandNameDefaultsToClassNameAsByteString(self):
"""
A L{Command} subclass without a defined C{commandName} that's
not a byte string.
"""
class NewCommand(amp.Command):
"""
A new command.
"""
self.assertEqual(b"NewCommand", NewCommand.commandName) | A L{Command} subclass without a defined C{commandName} that's
not a byte string. | test_commandNameDefaultsToClassNameAsByteString | 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_commandNameMustBeAByteString(self):
"""
A L{Command} subclass cannot be defined with a C{commandName} that's
not a byte string.
"""
error = self.assertRaises(
TypeError, type, "NewCommand", (amp.Command, ),
{"commandName": u"FOO"})
self.assertRegex(
str(error), "^Command names must be byte strings, got: u?'FOO'$") | A L{Command} subclass cannot be defined with a C{commandName} that's
not a byte string. | test_commandNameMustBeAByteString | 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_commandArgumentsMustBeNamedWithByteStrings(self):
"""
A L{Command} subclass's C{arguments} must have byte string names.
"""
error = self.assertRaises(
TypeError, type, "NewCommand", (amp.Command, ),
{"arguments": [(u"foo", None)]})
self.assertRegex(
str(error), "^Argument names must be byte strings, got: u?'foo'$") | A L{Command} subclass's C{arguments} must have byte string names. | test_commandArgumentsMustBeNamedWithByteStrings | 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_commandResponseMustBeNamedWithByteStrings(self):
"""
A L{Command} subclass's C{response} must have byte string names.
"""
error = self.assertRaises(
TypeError, type, "NewCommand", (amp.Command, ),
{"response": [(u"foo", None)]})
self.assertRegex(
str(error), "^Response names must be byte strings, got: u?'foo'$") | A L{Command} subclass's C{response} must have byte string names. | test_commandResponseMustBeNamedWithByteStrings | 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_commandErrorsIsConvertedToDict(self):
"""
A L{Command} subclass's C{errors} is coerced into a C{dict}.
"""
class NewCommand(amp.Command):
errors = [(ZeroDivisionError, b"ZDE")]
self.assertEqual(
{ZeroDivisionError: b"ZDE"},
NewCommand.errors) | A L{Command} subclass's C{errors} is coerced into a C{dict}. | test_commandErrorsIsConvertedToDict | 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_commandErrorsMustUseBytesForOnWireRepresentation(self):
"""
A L{Command} subclass's C{errors} must map exceptions to byte strings.
"""
error = self.assertRaises(
TypeError, type, "NewCommand", (amp.Command, ),
{"errors": [(ZeroDivisionError, u"foo")]})
self.assertRegex(
str(error), "^Error names must be byte strings, got: u?'foo'$") | A L{Command} subclass's C{errors} must map exceptions to byte strings. | test_commandErrorsMustUseBytesForOnWireRepresentation | 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_commandFatalErrorsIsConvertedToDict(self):
"""
A L{Command} subclass's C{fatalErrors} is coerced into a C{dict}.
"""
class NewCommand(amp.Command):
fatalErrors = [(ZeroDivisionError, b"ZDE")]
self.assertEqual(
{ZeroDivisionError: b"ZDE"},
NewCommand.fatalErrors) | A L{Command} subclass's C{fatalErrors} is coerced into a C{dict}. | test_commandFatalErrorsIsConvertedToDict | 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_commandFatalErrorsMustUseBytesForOnWireRepresentation(self):
"""
A L{Command} subclass's C{fatalErrors} must map exceptions to byte
strings.
"""
error = self.assertRaises(
TypeError, type, "NewCommand", (amp.Command, ),
{"fatalErrors": [(ZeroDivisionError, u"foo")]})
self.assertRegex(
str(error), "^Fatal error names must be byte strings, "
"got: u?'foo'$") | A L{Command} subclass's C{fatalErrors} must map exceptions to byte
strings. | test_commandFatalErrorsMustUseBytesForOnWireRepresentation | 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_toBox(self):
"""
L{ListOf.toBox} extracts the list of objects from the C{objects}
dictionary passed to it, using the C{name} key also passed to it,
serializes each of the elements in that list using the L{Argument}
instance previously passed to its initializer, combines the serialized
results, and inserts the result into the C{strings} dictionary using
the same C{name} key.
"""
stringList = amp.ListOf(self.elementType)
strings = amp.AmpBox()
for key in self.objects:
stringList.toBox(
key.encode("ascii"), strings, self.objects.copy(), None)
self.assertEqual(strings, self.strings) | L{ListOf.toBox} extracts the list of objects from the C{objects}
dictionary passed to it, using the C{name} key also passed to it,
serializes each of the elements in that list using the L{Argument}
instance previously passed to its initializer, combines the serialized
results, and inserts the result into the C{strings} dictionary using
the same C{name} key. | test_toBox | 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_fromBox(self):
"""
L{ListOf.fromBox} reverses the operation performed by L{ListOf.toBox}.
"""
stringList = amp.ListOf(self.elementType)
objects = {}
for key in self.strings:
stringList.fromBox(key, self.strings.copy(), objects, None)
self.assertEqual(objects, self.objects) | L{ListOf.fromBox} reverses the operation performed by L{ListOf.toBox}. | test_fromBox | 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_fromBox(self):
"""
L{ListOf.fromBox} reverses the operation performed by L{ListOf.toBox}.
"""
# Helpers. Decimal.is_{qnan,snan,signed}() are new in 2.6 (or 2.5.2,
# but who's counting).
def is_qnan(decimal):
return 'NaN' in str(decimal) and 'sNaN' not in str(decimal)
def is_snan(decimal):
return 'sNaN' in str(decimal)
def is_signed(decimal):
return '-' in str(decimal)
# NaN values have unusual equality semantics, so this method is
# overridden to compare the resulting objects in a way which works with
# NaNs.
stringList = amp.ListOf(self.elementType)
objects = {}
for key in self.strings:
stringList.fromBox(key, self.strings.copy(), objects, None)
n = objects["nan"]
self.assertTrue(is_qnan(n[0]) and not is_signed(n[0]))
self.assertTrue(is_qnan(n[1]) and is_signed(n[1]))
self.assertTrue(is_snan(n[2]) and not is_signed(n[2]))
self.assertTrue(is_snan(n[3]) and is_signed(n[3])) | L{ListOf.fromBox} reverses the operation performed by L{ListOf.toBox}. | test_fromBox | 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_nonDecimal(self):
"""
L{amp.Decimal.toString} raises L{ValueError} if passed an object which
is not an instance of C{decimal.Decimal}.
"""
argument = amp.Decimal()
self.assertRaises(ValueError, argument.toString, "1.234")
self.assertRaises(ValueError, argument.toString, 1.234)
self.assertRaises(ValueError, argument.toString, 1234) | L{amp.Decimal.toString} raises L{ValueError} if passed an object which
is not an instance of C{decimal.Decimal}. | test_nonDecimal | 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_nonFloat(self):
"""
L{amp.Float.toString} raises L{ValueError} if passed an object which
is not a L{float}.
"""
argument = amp.Float()
self.assertRaises(ValueError, argument.toString, u"1.234")
self.assertRaises(ValueError, argument.toString, b"1.234")
self.assertRaises(ValueError, argument.toString, 1234) | L{amp.Float.toString} raises L{ValueError} if passed an object which
is not a L{float}. | test_nonFloat | 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_float(self):
"""
L{amp.Float.toString} returns a bytestring when it is given a L{float}.
"""
argument = amp.Float()
self.assertEqual(argument.toString(1.234), b"1.234") | L{amp.Float.toString} returns a bytestring when it is given a L{float}. | test_float | 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_requiredArgumentWithNoneValueRaisesTypeError(self):
"""
L{ListOf.toBox} raises C{TypeError} when passed a value of L{None}
for the argument.
"""
stringList = amp.ListOf(amp.Integer())
self.assertRaises(
TypeError, stringList.toBox, b'omitted', amp.AmpBox(),
{'omitted': None}, None) | L{ListOf.toBox} raises C{TypeError} when passed a value of L{None}
for the argument. | test_requiredArgumentWithNoneValueRaisesTypeError | 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_optionalArgumentWithNoneValueOmitted(self):
"""
L{ListOf.toBox} silently omits serializing any argument with a
value of L{None} that is designated as optional for the protocol.
"""
stringList = amp.ListOf(amp.Integer(), optional=True)
strings = amp.AmpBox()
stringList.toBox(b'omitted', strings, {b'omitted': None}, None)
self.assertEqual(strings, {}) | L{ListOf.toBox} silently omits serializing any argument with a
value of L{None} that is designated as optional for the protocol. | test_optionalArgumentWithNoneValueOmitted | 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_requiredArgumentWithKeyMissingRaisesKeyError(self):
"""
L{ListOf.toBox} raises C{KeyError} if the argument's key is not
present in the objects dictionary.
"""
stringList = amp.ListOf(amp.Integer())
self.assertRaises(
KeyError, stringList.toBox, b'ommited', amp.AmpBox(),
{'someOtherKey': 0}, None) | L{ListOf.toBox} raises C{KeyError} if the argument's key is not
present in the objects dictionary. | test_requiredArgumentWithKeyMissingRaisesKeyError | 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_optionalArgumentWithKeyMissingOmitted(self):
"""
L{ListOf.toBox} silently omits serializing any argument designated
as optional whose key is not present in the objects dictionary.
"""
stringList = amp.ListOf(amp.Integer(), optional=True)
stringList.toBox(b'ommited', amp.AmpBox(), {b'someOtherKey': 0}, None) | L{ListOf.toBox} silently omits serializing any argument designated
as optional whose key is not present in the objects dictionary. | test_optionalArgumentWithKeyMissingOmitted | 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_omittedOptionalArgumentDeserializesAsNone(self):
"""
L{ListOf.fromBox} correctly reverses the operation performed by
L{ListOf.toBox} for optional arguments.
"""
stringList = amp.ListOf(amp.Integer(), optional=True)
objects = {}
stringList.fromBox(b'omitted', {}, objects, None)
self.assertEqual(objects, {'omitted': None}) | L{ListOf.fromBox} correctly reverses the operation performed by
L{ListOf.toBox} for optional arguments. | test_omittedOptionalArgumentDeserializesAsNone | 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 __init__(self, descriptorFuzz):
"""
@param descriptorFuzz: An offset to apply to descriptors.
@type descriptorFuzz: C{int}
"""
self._fuzz = descriptorFuzz
self._queue = [] | @param descriptorFuzz: An offset to apply to descriptors.
@type descriptorFuzz: C{int} | __init__ | 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_fromStringProto(self):
"""
L{Descriptor.fromStringProto} constructs a file descriptor value by
extracting a previously received file descriptor corresponding to the
wire value of the argument from the L{_DescriptorExchanger} state of the
protocol passed to it.
This is a whitebox test which involves direct L{_DescriptorExchanger}
state inspection.
"""
argument = amp.Descriptor()
self.protocol.fileDescriptorReceived(5)
self.protocol.fileDescriptorReceived(3)
self.protocol.fileDescriptorReceived(1)
self.assertEqual(
5, argument.fromStringProto("0", self.protocol))
self.assertEqual(
3, argument.fromStringProto("1", self.protocol))
self.assertEqual(
1, argument.fromStringProto("2", self.protocol))
self.assertEqual({}, self.protocol._descriptors) | L{Descriptor.fromStringProto} constructs a file descriptor value by
extracting a previously received file descriptor corresponding to the
wire value of the argument from the L{_DescriptorExchanger} state of the
protocol passed to it.
This is a whitebox test which involves direct L{_DescriptorExchanger}
state inspection. | test_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 test_toStringProto(self):
"""
To send a file descriptor, L{Descriptor.toStringProto} uses the
L{IUNIXTransport.sendFileDescriptor} implementation of the transport of
the protocol passed to it to copy the file descriptor. Each subsequent
descriptor sent over a particular AMP connection is assigned the next
integer value, starting from 0. The base ten string representation of
this value is the byte encoding of the argument.
This is a whitebox test which involves direct L{_DescriptorExchanger}
state inspection and mutation.
"""
argument = amp.Descriptor()
self.assertEqual(b"0", argument.toStringProto(2, self.protocol))
self.assertEqual(
("fileDescriptorReceived", 2 + self.fuzz), self.transport._queue.pop(0))
self.assertEqual(b"1", argument.toStringProto(4, self.protocol))
self.assertEqual(
("fileDescriptorReceived", 4 + self.fuzz), self.transport._queue.pop(0))
self.assertEqual(b"2", argument.toStringProto(6, self.protocol))
self.assertEqual(
("fileDescriptorReceived", 6 + self.fuzz), self.transport._queue.pop(0))
self.assertEqual({}, self.protocol._descriptors) | To send a file descriptor, L{Descriptor.toStringProto} uses the
L{IUNIXTransport.sendFileDescriptor} implementation of the transport of
the protocol passed to it to copy the file descriptor. Each subsequent
descriptor sent over a particular AMP connection is assigned the next
integer value, starting from 0. The base ten string representation of
this value is the byte encoding of the argument.
This is a whitebox test which involves direct L{_DescriptorExchanger}
state inspection and mutation. | test_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 test_roundTrip(self):
"""
L{amp.Descriptor.fromBox} can interpret an L{amp.AmpBox} constructed by
L{amp.Descriptor.toBox} to reconstruct a file descriptor value.
"""
name = "alpha"
nameAsBytes = name.encode("ascii")
strings = {}
descriptor = 17
sendObjects = {name: descriptor}
argument = amp.Descriptor()
argument.toBox(nameAsBytes, strings, sendObjects.copy(), self.protocol)
receiver = amp.BinaryBoxProtocol(
amp.BoxDispatcher(amp.CommandLocator()))
for event in self.transport._queue:
getattr(receiver, event[0])(*event[1:])
receiveObjects = {}
argument.fromBox(
nameAsBytes, strings.copy(), receiveObjects, receiver)
# Make sure we got the descriptor. Adjust by fuzz to be more convincing
# of having gone through L{IUNIXTransport.sendFileDescriptor}, not just
# converted to a string and then parsed back into an integer.
self.assertEqual(descriptor + self.fuzz, receiveObjects[name]) | L{amp.Descriptor.fromBox} can interpret an L{amp.AmpBox} constructed by
L{amp.Descriptor.toBox} to reconstruct a file descriptor value. | test_roundTrip | 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_invalidString(self):
"""
L{amp.DateTime.fromString} raises L{ValueError} when passed a string
which does not represent a timestamp in the proper format.
"""
d = amp.DateTime()
self.assertRaises(ValueError, d.fromString, 'abc') | L{amp.DateTime.fromString} raises L{ValueError} when passed a string
which does not represent a timestamp in the proper format. | test_invalidString | 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_invalidDatetime(self):
"""
L{amp.DateTime.toString} raises L{ValueError} when passed a naive
datetime (a datetime with no timezone information).
"""
d = amp.DateTime()
self.assertRaises(ValueError, d.toString,
datetime.datetime(2010, 12, 25, 0, 0, 0)) | L{amp.DateTime.toString} raises L{ValueError} when passed a naive
datetime (a datetime with no timezone information). | test_invalidDatetime | 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_fromString(self):
"""
L{amp.DateTime.fromString} returns a C{datetime.datetime} with all of
its fields populated from the string passed to it.
"""
argument = amp.DateTime()
value = argument.fromString(self.string)
self.assertEqual(value, self.object) | L{amp.DateTime.fromString} returns a C{datetime.datetime} with all of
its fields populated from the string passed to it. | test_fromString | 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_toString(self):
"""
L{amp.DateTime.toString} returns a C{str} in the wire format including
all of the information from the C{datetime.datetime} passed into it,
including the timezone offset.
"""
argument = amp.DateTime()
value = argument.toString(self.object)
self.assertEqual(value, self.string) | L{amp.DateTime.toString} returns a C{str} in the wire format including
all of the information from the C{datetime.datetime} passed into it,
including the timezone offset. | test_toString | 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_tzname(self):
"""
L{amp.utc.tzname} returns C{"+00:00"}.
"""
self.assertEqual(amp.utc.tzname(None), '+00:00') | L{amp.utc.tzname} returns C{"+00:00"}. | test_tzname | 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_dst(self):
"""
L{amp.utc.dst} returns a zero timedelta.
"""
self.assertEqual(amp.utc.dst(None), datetime.timedelta(0)) | L{amp.utc.dst} returns a zero timedelta. | test_dst | 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_utcoffset(self):
"""
L{amp.utc.utcoffset} returns a zero timedelta.
"""
self.assertEqual(amp.utc.utcoffset(None), datetime.timedelta(0)) | L{amp.utc.utcoffset} returns a zero timedelta. | test_utcoffset | 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_badSign(self):
"""
L{amp._FixedOffsetTZInfo.fromSignHoursMinutes} raises L{ValueError} if
passed an offset sign other than C{'+'} or C{'-'}.
"""
self.assertRaises(ValueError, tz, '?', 0, 0) | L{amp._FixedOffsetTZInfo.fromSignHoursMinutes} raises L{ValueError} if
passed an offset sign other than C{'+'} or C{'-'}. | test_badSign | 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_stringMessage(self):
"""
L{amp.RemoteAmpError} renders the given C{errorCode} (C{bytes}) and
C{description} into a native string.
"""
error = amp.RemoteAmpError(b"BROKEN", "Something has broken")
self.assertEqual("Code<BROKEN>: Something has broken", str(error)) | L{amp.RemoteAmpError} renders the given C{errorCode} (C{bytes}) and
C{description} into a native string. | test_stringMessage | 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_stringMessageReplacesNonAsciiText(self):
"""
When C{errorCode} contains non-ASCII characters, L{amp.RemoteAmpError}
renders then as backslash-escape sequences.
"""
error = amp.RemoteAmpError(b"BROKEN-\xff", "Something has broken")
self.assertEqual("Code<BROKEN-\\xff>: Something has broken", str(error)) | When C{errorCode} contains non-ASCII characters, L{amp.RemoteAmpError}
renders then as backslash-escape sequences. | test_stringMessageReplacesNonAsciiText | 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_stringMessageWithLocalFailure(self):
"""
L{amp.RemoteAmpError} renders local errors with a "(local)" marker and
a brief traceback.
"""
failure = Failure(Exception("Something came loose"))
error = amp.RemoteAmpError(
b"BROKEN", "Something has broken", local=failure)
self.assertRegex(
str(error), (
"^Code<BROKEN> [(]local[)]: Something has broken\n"
"Traceback [(]failure with no frames[)]: "
"<.+Exception.>: Something came loose\n"
)) | L{amp.RemoteAmpError} renders local errors with a "(local)" marker and
a brief traceback. | test_stringMessageWithLocalFailure | 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 loopUntil(predicate, interval=0):
"""
Poor excuse for an event notification helper. This polls a condition and
calls back a Deferred when it is seen to be true.
Do not use this function.
"""
from twisted.internet import task
d = defer.Deferred()
def check():
res = predicate()
if res:
d.callback(res)
call = task.LoopingCall(check)
def stop(result):
call.stop()
return result
d.addCallback(stop)
d2 = call.start(interval)
d2.addErrback(d.errback)
return d | Poor excuse for an event notification helper. This polls a condition and
calls back a Deferred when it is seen to be true.
Do not use this function. | loopUntil | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def cleanUp(self):
"""
Clean-up for tests to wait for the port to stop listening.
"""
if self._cleanerUpper is None:
return self.port.stopListening()
return self._cleanerUpper | Clean-up for tests to wait for the port to stop listening. | cleanUp | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def buildProtocol(self, addr):
"""
Create a L{AccumulatingProtocol} and set it up to be able to perform
callbacks.
"""
self.peerAddresses.append(addr)
self.called += 1
p = self.protocolFactory()
p.factory = self
p.closedDeferred = self.protocolConnectionLost
self.protocolConnectionLost = None
self.protocol = p
return p | Create a L{AccumulatingProtocol} and set it up to be able to perform
callbacks. | buildProtocol | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def test_listen(self):
"""
L{IReactorTCP.listenTCP} returns an object which provides
L{IListeningPort}.
"""
f = MyServerFactory()
p1 = reactor.listenTCP(0, f, interface="127.0.0.1")
self.addCleanup(p1.stopListening)
self.assertTrue(interfaces.IListeningPort.providedBy(p1)) | L{IReactorTCP.listenTCP} returns an object which provides
L{IListeningPort}. | test_listen | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def testStopListening(self):
"""
The L{IListeningPort} returned by L{IReactorTCP.listenTCP} can be
stopped with its C{stopListening} method. After the L{Deferred} it
(optionally) returns has been called back, the port number can be bound
to a new server.
"""
f = MyServerFactory()
port = reactor.listenTCP(0, f, interface="127.0.0.1")
n = port.getHost().port
def cbStopListening(ignored):
# Make sure we can rebind the port right away
port = reactor.listenTCP(n, f, interface="127.0.0.1")
return port.stopListening()
d = defer.maybeDeferred(port.stopListening)
d.addCallback(cbStopListening)
return d | The L{IListeningPort} returned by L{IReactorTCP.listenTCP} can be
stopped with its C{stopListening} method. After the L{Deferred} it
(optionally) returns has been called back, the port number can be bound
to a new server. | testStopListening | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def test_serverRepr(self):
"""
Check that the repr string of the server transport get the good port
number if the server listens on 0.
"""
server = MyServerFactory()
serverConnMade = server.protocolConnectionMade = defer.Deferred()
port = reactor.listenTCP(0, server)
self.addCleanup(port.stopListening)
client = MyClientFactory()
clientConnMade = client.protocolConnectionMade = defer.Deferred()
connector = reactor.connectTCP("127.0.0.1",
port.getHost().port, client)
self.addCleanup(connector.disconnect)
def check(result):
serverProto, clientProto = result
portNumber = port.getHost().port
self.assertEqual(
repr(serverProto.transport),
"<AccumulatingProtocol #0 on %s>" % (portNumber,))
serverProto.transport.loseConnection()
clientProto.transport.loseConnection()
return defer.gatherResults([serverConnMade, clientConnMade]
).addCallback(check) | Check that the repr string of the server transport get the good port
number if the server listens on 0. | test_serverRepr | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def test_restartListening(self):
"""
Stop and then try to restart a L{tcp.Port}: after a restart, the
server should be able to handle client connections.
"""
serverFactory = MyServerFactory()
port = reactor.listenTCP(0, serverFactory, interface="127.0.0.1")
self.addCleanup(port.stopListening)
def cbStopListening(ignored):
port.startListening()
client = MyClientFactory()
serverFactory.protocolConnectionMade = defer.Deferred()
client.protocolConnectionMade = defer.Deferred()
connector = reactor.connectTCP("127.0.0.1",
port.getHost().port, client)
self.addCleanup(connector.disconnect)
return defer.gatherResults([serverFactory.protocolConnectionMade,
client.protocolConnectionMade]
).addCallback(close)
def close(result):
serverProto, clientProto = result
clientProto.transport.loseConnection()
serverProto.transport.loseConnection()
d = defer.maybeDeferred(port.stopListening)
d.addCallback(cbStopListening)
return d | Stop and then try to restart a L{tcp.Port}: after a restart, the
server should be able to handle client connections. | test_restartListening | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def test_exceptInStop(self):
"""
If the server factory raises an exception in C{stopFactory}, the
deferred returned by L{tcp.Port.stopListening} should fail with the
corresponding error.
"""
serverFactory = MyServerFactory()
def raiseException():
raise RuntimeError("An error")
serverFactory.stopFactory = raiseException
port = reactor.listenTCP(0, serverFactory, interface="127.0.0.1")
return self.assertFailure(port.stopListening(), RuntimeError) | If the server factory raises an exception in C{stopFactory}, the
deferred returned by L{tcp.Port.stopListening} should fail with the
corresponding error. | test_exceptInStop | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def test_restartAfterExcept(self):
"""
Even if the server factory raise an exception in C{stopFactory}, the
corresponding C{tcp.Port} instance should be in a sane state and can
be restarted.
"""
serverFactory = MyServerFactory()
def raiseException():
raise RuntimeError("An error")
serverFactory.stopFactory = raiseException
port = reactor.listenTCP(0, serverFactory, interface="127.0.0.1")
self.addCleanup(port.stopListening)
def cbStopListening(ignored):
del serverFactory.stopFactory
port.startListening()
client = MyClientFactory()
serverFactory.protocolConnectionMade = defer.Deferred()
client.protocolConnectionMade = defer.Deferred()
connector = reactor.connectTCP("127.0.0.1",
port.getHost().port, client)
self.addCleanup(connector.disconnect)
return defer.gatherResults([serverFactory.protocolConnectionMade,
client.protocolConnectionMade]
).addCallback(close)
def close(result):
serverProto, clientProto = result
clientProto.transport.loseConnection()
serverProto.transport.loseConnection()
return self.assertFailure(port.stopListening(), RuntimeError
).addCallback(cbStopListening) | Even if the server factory raise an exception in C{stopFactory}, the
corresponding C{tcp.Port} instance should be in a sane state and can
be restarted. | test_restartAfterExcept | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def test_directConnectionLostCall(self):
"""
If C{connectionLost} is called directly on a port object, it succeeds
(and doesn't expect the presence of a C{deferred} attribute).
C{connectionLost} is called by L{reactor.disconnectAll} at shutdown.
"""
serverFactory = MyServerFactory()
port = reactor.listenTCP(0, serverFactory, interface="127.0.0.1")
portNumber = port.getHost().port
port.connectionLost(None)
client = MyClientFactory()
serverFactory.protocolConnectionMade = defer.Deferred()
client.protocolConnectionMade = defer.Deferred()
reactor.connectTCP("127.0.0.1", portNumber, client)
def check(ign):
client.reason.trap(error.ConnectionRefusedError)
return client.failDeferred.addCallback(check) | If C{connectionLost} is called directly on a port object, it succeeds
(and doesn't expect the presence of a C{deferred} attribute).
C{connectionLost} is called by L{reactor.disconnectAll} at shutdown. | test_directConnectionLostCall | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def test_exceptInConnectionLostCall(self):
"""
If C{connectionLost} is called directory on a port object and that the
server factory raises an exception in C{stopFactory}, the exception is
passed through to the caller.
C{connectionLost} is called by L{reactor.disconnectAll} at shutdown.
"""
serverFactory = MyServerFactory()
def raiseException():
raise RuntimeError("An error")
serverFactory.stopFactory = raiseException
port = reactor.listenTCP(0, serverFactory, interface="127.0.0.1")
self.assertRaises(RuntimeError, port.connectionLost, None) | If C{connectionLost} is called directory on a port object and that the
server factory raises an exception in C{stopFactory}, the exception is
passed through to the caller.
C{connectionLost} is called by L{reactor.disconnectAll} at shutdown. | test_exceptInConnectionLostCall | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def test_closePortInProtocolFactory(self):
"""
A port created with L{IReactorTCP.listenTCP} can be connected to with
L{IReactorTCP.connectTCP}.
"""
f = ClosingFactory()
port = reactor.listenTCP(0, f, interface="127.0.0.1")
f.port = port
self.addCleanup(f.cleanUp)
portNumber = port.getHost().port
clientF = MyClientFactory()
reactor.connectTCP("127.0.0.1", portNumber, clientF)
def check(x):
self.assertTrue(clientF.protocol.made)
self.assertTrue(port.disconnected)
clientF.lostReason.trap(error.ConnectionDone)
return clientF.deferred.addCallback(check) | A port created with L{IReactorTCP.listenTCP} can be connected to with
L{IReactorTCP.connectTCP}. | test_closePortInProtocolFactory | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def _connectedClientAndServerTest(self, callback):
"""
Invoke the given callback with a client protocol and a server protocol
which have been connected to each other.
"""
serverFactory = MyServerFactory()
serverConnMade = defer.Deferred()
serverFactory.protocolConnectionMade = serverConnMade
port = reactor.listenTCP(0, serverFactory, interface="127.0.0.1")
self.addCleanup(port.stopListening)
portNumber = port.getHost().port
clientF = MyClientFactory()
clientConnMade = defer.Deferred()
clientF.protocolConnectionMade = clientConnMade
reactor.connectTCP("127.0.0.1", portNumber, clientF)
connsMade = defer.gatherResults([serverConnMade, clientConnMade])
def connected(result):
serverProtocol, clientProtocol = result
callback(serverProtocol, clientProtocol)
serverProtocol.transport.loseConnection()
clientProtocol.transport.loseConnection()
connsMade.addCallback(connected)
return connsMade | Invoke the given callback with a client protocol and a server protocol
which have been connected to each other. | _connectedClientAndServerTest | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def test_tcpNoDelay(self):
"""
The transport of a protocol connected with L{IReactorTCP.connectTCP} or
L{IReactor.TCP.listenTCP} can have its I{TCP_NODELAY} state inspected
and manipulated with L{ITCPTransport.getTcpNoDelay} and
L{ITCPTransport.setTcpNoDelay}.
"""
def check(serverProtocol, clientProtocol):
for p in [serverProtocol, clientProtocol]:
transport = p.transport
self.assertEqual(transport.getTcpNoDelay(), 0)
transport.setTcpNoDelay(1)
self.assertEqual(transport.getTcpNoDelay(), 1)
transport.setTcpNoDelay(0)
self.assertEqual(transport.getTcpNoDelay(), 0)
return self._connectedClientAndServerTest(check) | The transport of a protocol connected with L{IReactorTCP.connectTCP} or
L{IReactor.TCP.listenTCP} can have its I{TCP_NODELAY} state inspected
and manipulated with L{ITCPTransport.getTcpNoDelay} and
L{ITCPTransport.setTcpNoDelay}. | test_tcpNoDelay | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def test_tcpKeepAlive(self):
"""
The transport of a protocol connected with L{IReactorTCP.connectTCP} or
L{IReactor.TCP.listenTCP} can have its I{SO_KEEPALIVE} state inspected
and manipulated with L{ITCPTransport.getTcpKeepAlive} and
L{ITCPTransport.setTcpKeepAlive}.
"""
def check(serverProtocol, clientProtocol):
for p in [serverProtocol, clientProtocol]:
transport = p.transport
self.assertEqual(transport.getTcpKeepAlive(), 0)
transport.setTcpKeepAlive(1)
self.assertEqual(transport.getTcpKeepAlive(), 1)
transport.setTcpKeepAlive(0)
self.assertEqual(transport.getTcpKeepAlive(), 0)
return self._connectedClientAndServerTest(check) | The transport of a protocol connected with L{IReactorTCP.connectTCP} or
L{IReactor.TCP.listenTCP} can have its I{SO_KEEPALIVE} state inspected
and manipulated with L{ITCPTransport.getTcpKeepAlive} and
L{ITCPTransport.setTcpKeepAlive}. | test_tcpKeepAlive | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def connected(proto):
"""
Darn. Kill it and try again, if there are any tries left.
"""
proto.transport.loseConnection()
if serverSockets:
return tryConnectFailure()
self.fail("Could not fail to connect - could not test errno for that case.") | Darn. Kill it and try again, if there are any tries left. | test_connectionRefusedErrorNumber.test_connectionRefusedErrorNumber.tryConnectFailure.connected | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def tryConnectFailure():
def connected(proto):
"""
Darn. Kill it and try again, if there are any tries left.
"""
proto.transport.loseConnection()
if serverSockets:
return tryConnectFailure()
self.fail("Could not fail to connect - could not test errno for that case.")
serverSocket = serverSockets.pop()
serverHost, serverPort = serverSocket.getsockname()
serverSocket.close()
connectDeferred = clientCreator.connectTCP(serverHost, serverPort)
connectDeferred.addCallback(connected)
return connectDeferred | Darn. Kill it and try again, if there are any tries left. | test_connectionRefusedErrorNumber.tryConnectFailure | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def test_connectionRefusedErrorNumber(self):
"""
Assert that the error number of the ConnectionRefusedError is
ECONNREFUSED, and not some other socket related error.
"""
# Bind a number of ports in the operating system. We will attempt
# to connect to these in turn immediately after closing them, in the
# hopes that no one else has bound them in the mean time. Any
# connection which succeeds is ignored and causes us to move on to
# the next port. As soon as a connection attempt fails, we move on
# to making an assertion about how it failed. If they all succeed,
# the test will fail.
# It would be nice to have a simpler, reliable way to cause a
# connection failure from the platform.
#
# On Linux (2.6.15), connecting to port 0 always fails. FreeBSD
# (5.4) rejects the connection attempt with EADDRNOTAVAIL.
#
# On FreeBSD (5.4), listening on a port and then repeatedly
# connecting to it without ever accepting any connections eventually
# leads to an ECONNREFUSED. On Linux (2.6.15), a seemingly
# unbounded number of connections succeed.
serverSockets = []
for i in range(10):
serverSocket = socket.socket()
serverSocket.bind(('127.0.0.1', 0))
serverSocket.listen(1)
serverSockets.append(serverSocket)
random.shuffle(serverSockets)
clientCreator = protocol.ClientCreator(reactor, protocol.Protocol)
def tryConnectFailure():
def connected(proto):
"""
Darn. Kill it and try again, if there are any tries left.
"""
proto.transport.loseConnection()
if serverSockets:
return tryConnectFailure()
self.fail("Could not fail to connect - could not test errno for that case.")
serverSocket = serverSockets.pop()
serverHost, serverPort = serverSocket.getsockname()
serverSocket.close()
connectDeferred = clientCreator.connectTCP(serverHost, serverPort)
connectDeferred.addCallback(connected)
return connectDeferred
refusedDeferred = tryConnectFailure()
self.assertFailure(refusedDeferred, error.ConnectionRefusedError)
def connRefused(exc):
self.assertEqual(exc.osError, errno.ECONNREFUSED)
refusedDeferred.addCallback(connRefused)
def cleanup(passthrough):
while serverSockets:
serverSockets.pop().close()
return passthrough
refusedDeferred.addBoth(cleanup)
return refusedDeferred | Assert that the error number of the ConnectionRefusedError is
ECONNREFUSED, and not some other socket related error. | test_connectionRefusedErrorNumber | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def test_connectByServiceFail(self):
"""
Connecting to a named service which does not exist raises
L{error.ServiceNameUnknownError}.
"""
self.assertRaises(
error.ServiceNameUnknownError,
reactor.connectTCP,
"127.0.0.1", "thisbetternotexist", MyClientFactory()) | Connecting to a named service which does not exist raises
L{error.ServiceNameUnknownError}. | test_connectByServiceFail | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def test_connectByService(self):
"""
L{IReactorTCP.connectTCP} accepts the name of a service instead of a
port number and connects to the port number associated with that
service, as defined by L{socket.getservbyname}.
"""
serverFactory = MyServerFactory()
serverConnMade = defer.Deferred()
serverFactory.protocolConnectionMade = serverConnMade
port = reactor.listenTCP(0, serverFactory, interface="127.0.0.1")
self.addCleanup(port.stopListening)
portNumber = port.getHost().port
clientFactory = MyClientFactory()
clientConnMade = defer.Deferred()
clientFactory.protocolConnectionMade = clientConnMade
def fakeGetServicePortByName(serviceName, protocolName):
if serviceName == 'http' and protocolName == 'tcp':
return portNumber
return 10
self.patch(socket, 'getservbyname', fakeGetServicePortByName)
reactor.connectTCP('127.0.0.1', 'http', clientFactory)
connMade = defer.gatherResults([serverConnMade, clientConnMade])
def connected(result):
serverProtocol, clientProtocol = result
self.assertTrue(
serverFactory.called,
"Server factory was not called upon to build a protocol.")
serverProtocol.transport.loseConnection()
clientProtocol.transport.loseConnection()
connMade.addCallback(connected)
return connMade | L{IReactorTCP.connectTCP} accepts the name of a service instead of a
port number and connects to the port number associated with that
service, as defined by L{socket.getservbyname}. | test_connectByService | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def test_serverStartStop(self):
"""
The factory passed to L{IReactorTCP.listenTCP} should be started only
when it transitions from being used on no ports to being used on one
port and should be stopped only when it transitions from being used on
one port to being used on no ports.
"""
# Note - this test doesn't need to use listenTCP. It is exercising
# logic implemented in Factory.doStart and Factory.doStop, so it could
# just call that directly. Some other test can make sure that
# listenTCP and stopListening correctly call doStart and
# doStop. -exarkun
f = StartStopFactory()
# listen on port
p1 = reactor.listenTCP(0, f, interface='127.0.0.1')
self.addCleanup(p1.stopListening)
self.assertEqual((f.started, f.stopped), (1, 0))
# listen on two more ports
p2 = reactor.listenTCP(0, f, interface='127.0.0.1')
p3 = reactor.listenTCP(0, f, interface='127.0.0.1')
self.assertEqual((f.started, f.stopped), (1, 0))
# close two ports
d1 = defer.maybeDeferred(p1.stopListening)
d2 = defer.maybeDeferred(p2.stopListening)
closedDeferred = defer.gatherResults([d1, d2])
def cbClosed(ignored):
self.assertEqual((f.started, f.stopped), (1, 0))
# Close the last port
return p3.stopListening()
closedDeferred.addCallback(cbClosed)
def cbClosedAll(ignored):
self.assertEqual((f.started, f.stopped), (1, 1))
closedDeferred.addCallback(cbClosedAll)
return closedDeferred | The factory passed to L{IReactorTCP.listenTCP} should be started only
when it transitions from being used on no ports to being used on one
port and should be stopped only when it transitions from being used on
one port to being used on no ports. | test_serverStartStop | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def test_clientStartStop(self):
"""
The factory passed to L{IReactorTCP.connectTCP} should be started when
the connection attempt starts and stopped when it is over.
"""
f = ClosingFactory()
p = reactor.listenTCP(0, f, interface="127.0.0.1")
f.port = p
self.addCleanup(f.cleanUp)
portNumber = p.getHost().port
factory = ClientStartStopFactory()
reactor.connectTCP("127.0.0.1", portNumber, factory)
self.assertTrue(factory.started)
return loopUntil(lambda: factory.stopped) | The factory passed to L{IReactorTCP.connectTCP} should be started when
the connection attempt starts and stopped when it is over. | test_clientStartStop | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def test_cannotBind(self):
"""
L{IReactorTCP.listenTCP} raises L{error.CannotListenError} if the
address to listen on is already in use.
"""
f = MyServerFactory()
p1 = reactor.listenTCP(0, f, interface='127.0.0.1')
self.addCleanup(p1.stopListening)
n = p1.getHost().port
dest = p1.getHost()
self.assertEqual(dest.type, "TCP")
self.assertEqual(dest.host, "127.0.0.1")
self.assertEqual(dest.port, n)
# make sure new listen raises error
self.assertRaises(error.CannotListenError,
reactor.listenTCP, n, f, interface='127.0.0.1') | L{IReactorTCP.listenTCP} raises L{error.CannotListenError} if the
address to listen on is already in use. | test_cannotBind | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def _fireWhenDoneFunc(self, d, f):
"""Returns closure that when called calls f and then callbacks d.
"""
@wraps(f)
def newf(*args, **kw):
rtn = f(*args, **kw)
d.callback('')
return rtn
return newf | Returns closure that when called calls f and then callbacks d. | _fireWhenDoneFunc | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def test_clientBind(self):
"""
L{IReactorTCP.connectTCP} calls C{Factory.clientConnectionFailed} with
L{error.ConnectBindError} if the bind address specified is already in
use.
"""
theDeferred = defer.Deferred()
sf = MyServerFactory()
sf.startFactory = self._fireWhenDoneFunc(theDeferred, sf.startFactory)
p = reactor.listenTCP(0, sf, interface="127.0.0.1")
self.addCleanup(p.stopListening)
def _connect1(results):
d = defer.Deferred()
cf1 = MyClientFactory()
cf1.buildProtocol = self._fireWhenDoneFunc(d, cf1.buildProtocol)
reactor.connectTCP("127.0.0.1", p.getHost().port, cf1,
bindAddress=("127.0.0.1", 0))
d.addCallback(_conmade, cf1)
return d
def _conmade(results, cf1):
d = defer.Deferred()
cf1.protocol.connectionMade = self._fireWhenDoneFunc(
d, cf1.protocol.connectionMade)
d.addCallback(_check1connect2, cf1)
return d
def _check1connect2(results, cf1):
self.assertEqual(cf1.protocol.made, 1)
d1 = defer.Deferred()
d2 = defer.Deferred()
port = cf1.protocol.transport.getHost().port
cf2 = MyClientFactory()
cf2.clientConnectionFailed = self._fireWhenDoneFunc(
d1, cf2.clientConnectionFailed)
cf2.stopFactory = self._fireWhenDoneFunc(d2, cf2.stopFactory)
reactor.connectTCP("127.0.0.1", p.getHost().port, cf2,
bindAddress=("127.0.0.1", port))
d1.addCallback(_check2failed, cf1, cf2)
d2.addCallback(_check2stopped, cf1, cf2)
dl = defer.DeferredList([d1, d2])
dl.addCallback(_stop, cf1, cf2)
return dl
def _check2failed(results, cf1, cf2):
self.assertEqual(cf2.failed, 1)
cf2.reason.trap(error.ConnectBindError)
self.assertTrue(cf2.reason.check(error.ConnectBindError))
return results
def _check2stopped(results, cf1, cf2):
self.assertEqual(cf2.stopped, 1)
return results
def _stop(results, cf1, cf2):
d = defer.Deferred()
d.addCallback(_check1cleanup, cf1)
cf1.stopFactory = self._fireWhenDoneFunc(d, cf1.stopFactory)
cf1.protocol.transport.loseConnection()
return d
def _check1cleanup(results, cf1):
self.assertEqual(cf1.stopped, 1)
theDeferred.addCallback(_connect1)
return theDeferred | L{IReactorTCP.connectTCP} calls C{Factory.clientConnectionFailed} with
L{error.ConnectBindError} if the bind address specified is already in
use. | test_clientBind | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def test_hostAddress(self):
"""
L{IListeningPort.getHost} returns the same address as a client
connection's L{ITCPTransport.getPeer}.
"""
serverFactory = MyServerFactory()
serverFactory.protocolConnectionLost = defer.Deferred()
serverConnectionLost = serverFactory.protocolConnectionLost
port = reactor.listenTCP(0, serverFactory, interface='127.0.0.1')
self.addCleanup(port.stopListening)
n = port.getHost().port
clientFactory = MyClientFactory()
onConnection = clientFactory.protocolConnectionMade = defer.Deferred()
connector = reactor.connectTCP('127.0.0.1', n, clientFactory)
def check(ignored):
self.assertEqual([port.getHost()], clientFactory.peerAddresses)
self.assertEqual(
port.getHost(), clientFactory.protocol.transport.getPeer())
onConnection.addCallback(check)
def cleanup(ignored):
# Clean up the client explicitly here so that tear down of
# the server side of the connection begins, then wait for
# the server side to actually disconnect.
connector.disconnect()
return serverConnectionLost
onConnection.addCallback(cleanup)
return onConnection | L{IListeningPort.getHost} returns the same address as a client
connection's L{ITCPTransport.getPeer}. | test_hostAddress | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def test_writer(self):
"""
L{ITCPTransport.write} and L{ITCPTransport.writeSequence} send bytes to
the other end of the connection.
"""
f = protocol.Factory()
f.protocol = WriterProtocol
f.done = 0
f.problem = 0
wrappedF = WiredFactory(f)
p = reactor.listenTCP(0, wrappedF, interface="127.0.0.1")
self.addCleanup(p.stopListening)
n = p.getHost().port
clientF = WriterClientFactory()
wrappedClientF = WiredFactory(clientF)
reactor.connectTCP("127.0.0.1", n, wrappedClientF)
def check(ignored):
self.assertTrue(f.done, "writer didn't finish, it probably died")
self.assertTrue(f.problem == 0, "writer indicated an error")
self.assertTrue(clientF.done,
"client didn't see connection dropped")
expected = b"".join([b"Hello Cleveland!\n",
b"Goodbye", b" cruel", b" world", b"\n"])
self.assertTrue(clientF.data == expected,
"client didn't receive all the data it expected")
d = defer.gatherResults([wrappedF.onDisconnect,
wrappedClientF.onDisconnect])
return d.addCallback(check) | L{ITCPTransport.write} and L{ITCPTransport.writeSequence} send bytes to
the other end of the connection. | test_writer | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def connectionMade(self):
"""
Set up a callback on clientPaused to lose the connection.
"""
msg('Disconnector.connectionMade')
def disconnect(ignored):
msg('Disconnector.connectionMade disconnect')
self.transport.loseConnection()
msg('loseConnection called')
clientPaused.addCallback(disconnect) | Set up a callback on clientPaused to lose the connection. | test_writeAfterShutdownWithoutReading.connectionMade | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def connectionLost(self, reason):
"""
Notify observers that the server side of the connection has
ended.
"""
msg('Disconnecter.connectionLost')
serverLost.callback(None)
msg('serverLost called back') | Notify observers that the server side of the connection has
ended. | test_writeAfterShutdownWithoutReading.connectionLost | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def test_writeAfterShutdownWithoutReading(self):
"""
A TCP transport which is written to after the connection has been shut
down should notify its protocol that the connection has been lost, even
if the TCP transport is not actively being monitored for read events
(ie, pauseProducing was called on it).
"""
# This is an unpleasant thing. Generally tests shouldn't skip or
# run based on the name of the reactor being used (most tests
# shouldn't care _at all_ what reactor is being used, in fact). The
# IOCP reactor cannot pass this test, though -- please see the skip
# reason below for details.
if reactor.__class__.__name__ == 'IOCPReactor':
raise unittest.SkipTest(
"iocpreactor does not, in fact, stop reading immediately after "
"pauseProducing is called. This results in a bonus disconnection "
"notification. Under some circumstances, it might be possible to "
"not receive this notifications (specifically, pauseProducing, "
"deliver some data, proceed with this test).")
# Called back after the protocol for the client side of the connection
# has paused its transport, preventing it from reading, therefore
# preventing it from noticing the disconnection before the rest of the
# actions which are necessary to trigger the case this test is for have
# been taken.
clientPaused = defer.Deferred()
# Called back when the protocol for the server side of the connection
# has received connection lost notification.
serverLost = defer.Deferred()
class Disconnecter(protocol.Protocol):
"""
Protocol for the server side of the connection which disconnects
itself in a callback on clientPaused and publishes notification
when its connection is actually lost.
"""
def connectionMade(self):
"""
Set up a callback on clientPaused to lose the connection.
"""
msg('Disconnector.connectionMade')
def disconnect(ignored):
msg('Disconnector.connectionMade disconnect')
self.transport.loseConnection()
msg('loseConnection called')
clientPaused.addCallback(disconnect)
def connectionLost(self, reason):
"""
Notify observers that the server side of the connection has
ended.
"""
msg('Disconnecter.connectionLost')
serverLost.callback(None)
msg('serverLost called back')
# Create the server port to which a connection will be made.
server = protocol.ServerFactory()
server.protocol = Disconnecter
port = reactor.listenTCP(0, server, interface='127.0.0.1')
self.addCleanup(port.stopListening)
addr = port.getHost()
@implementer(IPullProducer)
class Infinite(object):
"""
A producer which will write to its consumer as long as
resumeProducing is called.
@ivar consumer: The L{IConsumer} which will be written to.
"""
def __init__(self, consumer):
self.consumer = consumer
def resumeProducing(self):
msg('Infinite.resumeProducing')
self.consumer.write(b'x')
msg('Infinite.resumeProducing wrote to consumer')
def stopProducing(self):
msg('Infinite.stopProducing')
class UnreadingWriter(protocol.Protocol):
"""
Trivial protocol which pauses its transport immediately and then
writes some bytes to it.
"""
def connectionMade(self):
msg('UnreadingWriter.connectionMade')
self.transport.pauseProducing()
clientPaused.callback(None)
msg('clientPaused called back')
def write(ignored):
msg('UnreadingWriter.connectionMade write')
# This needs to be enough bytes to spill over into the
# userspace Twisted send buffer - if it all fits into
# the kernel, Twisted won't even poll for OUT events,
# which means it won't poll for any events at all, so
# the disconnection is never noticed. This is due to
# #1662. When #1662 is fixed, this test will likely
# need to be adjusted, otherwise connection lost
# notification will happen too soon and the test will
# probably begin to fail with ConnectionDone instead of
# ConnectionLost (in any case, it will no longer be
# entirely correct).
producer = Infinite(self.transport)
msg('UnreadingWriter.connectionMade write created producer')
self.transport.registerProducer(producer, False)
msg('UnreadingWriter.connectionMade write registered producer')
serverLost.addCallback(write)
# Create the client and initiate the connection
client = MyClientFactory()
client.protocolFactory = UnreadingWriter
clientConnectionLost = client.deferred
def cbClientLost(ignored):
msg('cbClientLost')
return client.lostReason
clientConnectionLost.addCallback(cbClientLost)
msg('Connecting to %s:%s' % (addr.host, addr.port))
reactor.connectTCP(addr.host, addr.port, client)
# By the end of the test, the client should have received notification
# of unclean disconnection.
msg('Returning Deferred')
return self.assertFailure(clientConnectionLost, error.ConnectionLost) | A TCP transport which is written to after the connection has been shut
down should notify its protocol that the connection has been lost, even
if the TCP transport is not actively being monitored for read events
(ie, pauseProducing was called on it). | test_writeAfterShutdownWithoutReading | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def makeConnection(self, transport):
"""
Save the platform-specific socket handle for future
introspection.
"""
self.handle = transport.getHandle()
return protocol.Protocol.makeConnection(self, transport) | Save the platform-specific socket handle for future
introspection. | makeConnection | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def createServer(self, address, portNumber, factory):
"""
Bind a server port to which connections will be made. The server
should use the given protocol factory.
@return: The L{IListeningPort} for the server created.
"""
raise NotImplementedError() | Bind a server port to which connections will be made. The server
should use the given protocol factory.
@return: The L{IListeningPort} for the server created. | createServer | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def connectClient(self, address, portNumber, clientCreator):
"""
Establish a connection to the given address using the given
L{ClientCreator} instance.
@return: A Deferred which will fire with the connected protocol instance.
"""
raise NotImplementedError() | Establish a connection to the given address using the given
L{ClientCreator} instance.
@return: A Deferred which will fire with the connected protocol instance. | connectClient | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def getHandleExceptionType(self):
"""
Return the exception class which will be raised when an operation is
attempted on a closed platform handle.
"""
raise NotImplementedError() | Return the exception class which will be raised when an operation is
attempted on a closed platform handle. | getHandleExceptionType | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def getHandleErrorCodeMatcher(self):
"""
Return a L{hamcrest.core.matcher.Matcher} that matches the
errno expected to result from writing to a closed platform
socket handle.
"""
# Windows and Python 3: returns WSAENOTSOCK
# Windows and Python 2: returns EBADF
# Linux, FreeBSD, macOS: returns EBADF
if platform.isWindows() and _PY3:
return hamcrest.equal_to(errno.WSAENOTSOCK)
return hamcrest.equal_to(errno.EBADF) | Return a L{hamcrest.core.matcher.Matcher} that matches the
errno expected to result from writing to a closed platform
socket handle. | getHandleErrorCodeMatcher | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def clientConnected(client):
"""
Disconnect the client. Return a Deferred which fires when both
the client and the server have received disconnect notification.
"""
client.transport.write(
b'some bytes to make sure the connection is set up')
client.transport.loseConnection()
return defer.gatherResults([
onClientConnectionLost, onServerConnectionLost]) | Disconnect the client. Return a Deferred which fires when both
the client and the server have received disconnect notification. | test_properlyCloseFiles.clientConnected | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def clientDisconnected(result):
"""
Verify that the underlying platform socket handle has been
cleaned up.
"""
client, server = result
if not client.lostConnectionReason.check(error.ConnectionClosed):
err(client.lostConnectionReason,
"Client lost connection for unexpected reason")
if not server.lostConnectionReason.check(error.ConnectionClosed):
err(server.lostConnectionReason,
"Server lost connection for unexpected reason")
errorCodeMatcher = self.getHandleErrorCodeMatcher()
exception = self.assertRaises(
self.getHandleExceptionType(), client.handle.send, b'bytes')
hamcrest.assert_that(
exception.args[0],
errorCodeMatcher,
) | Verify that the underlying platform socket handle has been
cleaned up. | test_properlyCloseFiles.clientDisconnected | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def cleanup(passthrough):
"""
Shut down the server port. Return a Deferred which fires when
this has completed.
"""
result = defer.maybeDeferred(serverPort.stopListening)
result.addCallback(lambda ign: passthrough)
return result | Shut down the server port. Return a Deferred which fires when
this has completed. | test_properlyCloseFiles.cleanup | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def test_properlyCloseFiles(self):
"""
Test that lost connections properly have their underlying socket
resources cleaned up.
"""
onServerConnectionLost = defer.Deferred()
serverFactory = protocol.ServerFactory()
serverFactory.protocol = lambda: ConnectionLostNotifyingProtocol(
onServerConnectionLost)
serverPort = self.createServer('127.0.0.1', 0, serverFactory)
onClientConnectionLost = defer.Deferred()
serverAddr = serverPort.getHost()
clientCreator = protocol.ClientCreator(
reactor, lambda: HandleSavingProtocol(onClientConnectionLost))
clientDeferred = self.connectClient(
serverAddr.host, serverAddr.port, clientCreator)
def clientConnected(client):
"""
Disconnect the client. Return a Deferred which fires when both
the client and the server have received disconnect notification.
"""
client.transport.write(
b'some bytes to make sure the connection is set up')
client.transport.loseConnection()
return defer.gatherResults([
onClientConnectionLost, onServerConnectionLost])
clientDeferred.addCallback(clientConnected)
def clientDisconnected(result):
"""
Verify that the underlying platform socket handle has been
cleaned up.
"""
client, server = result
if not client.lostConnectionReason.check(error.ConnectionClosed):
err(client.lostConnectionReason,
"Client lost connection for unexpected reason")
if not server.lostConnectionReason.check(error.ConnectionClosed):
err(server.lostConnectionReason,
"Server lost connection for unexpected reason")
errorCodeMatcher = self.getHandleErrorCodeMatcher()
exception = self.assertRaises(
self.getHandleExceptionType(), client.handle.send, b'bytes')
hamcrest.assert_that(
exception.args[0],
errorCodeMatcher,
)
clientDeferred.addCallback(clientDisconnected)
def cleanup(passthrough):
"""
Shut down the server port. Return a Deferred which fires when
this has completed.
"""
result = defer.maybeDeferred(serverPort.stopListening)
result.addCallback(lambda ign: passthrough)
return result
clientDeferred.addBoth(cleanup)
return clientDeferred | Test that lost connections properly have their underlying socket
resources cleaned up. | test_properlyCloseFiles | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def createServer(self, address, portNumber, factory):
"""
Create a TCP server using L{IReactorTCP.listenTCP}.
"""
return reactor.listenTCP(portNumber, factory, interface=address) | Create a TCP server using L{IReactorTCP.listenTCP}. | createServer | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def connectClient(self, address, portNumber, clientCreator):
"""
Create a TCP client using L{IReactorTCP.connectTCP}.
"""
return clientCreator.connectTCP(address, portNumber) | Create a TCP client using L{IReactorTCP.connectTCP}. | connectClient | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def getHandleExceptionType(self):
"""
Return L{socket.error} as the expected error type which will be
raised by a write to the low-level socket object after it has been
closed.
"""
return socket.error | Return L{socket.error} as the expected error type which will be
raised by a write to the low-level socket object after it has been
closed. | getHandleExceptionType | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def buildProtocol(self, addr):
"""
Append the given address to C{self.addresses} and forward
the call to C{self.factory}.
"""
self.addresses.append(addr)
return self.factory.buildProtocol(addr) | Append the given address to C{self.addresses} and forward
the call to C{self.factory}. | setUp.buildProtocol | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def setUp(self):
"""
Create a port and connected client/server pair which can be used
to test factory behavior related to addresses.
@return: A L{defer.Deferred} which will be called back when both the
client and server protocols have received their connection made
callback.
"""
class RememberingWrapper(protocol.ClientFactory):
"""
Simple wrapper factory which records the addresses which are
passed to its L{buildProtocol} method and delegates actual
protocol creation to another factory.
@ivar addresses: A list of the objects passed to buildProtocol.
@ivar factory: The wrapped factory to which protocol creation is
delegated.
"""
def __init__(self, factory):
self.addresses = []
self.factory = factory
# Only bother to pass on buildProtocol calls to the wrapped
# factory - doStart, doStop, etc aren't necessary for this test
# to pass.
def buildProtocol(self, addr):
"""
Append the given address to C{self.addresses} and forward
the call to C{self.factory}.
"""
self.addresses.append(addr)
return self.factory.buildProtocol(addr)
# Make a server which we can receive connection and disconnection
# notification for, and which will record the address passed to its
# buildProtocol.
self.server = MyServerFactory()
self.serverConnMade = self.server.protocolConnectionMade = defer.Deferred()
self.serverConnLost = self.server.protocolConnectionLost = defer.Deferred()
# RememberingWrapper is a ClientFactory, but ClientFactory is-a
# ServerFactory, so this is okay.
self.serverWrapper = RememberingWrapper(self.server)
# Do something similar for a client.
self.client = MyClientFactory()
self.clientConnMade = self.client.protocolConnectionMade = defer.Deferred()
self.clientConnLost = self.client.protocolConnectionLost = defer.Deferred()
self.clientWrapper = RememberingWrapper(self.client)
self.port = reactor.listenTCP(0, self.serverWrapper, interface='127.0.0.1')
self.connector = reactor.connectTCP(
self.port.getHost().host, self.port.getHost().port, self.clientWrapper)
return defer.gatherResults([self.serverConnMade, self.clientConnMade]) | Create a port and connected client/server pair which can be used
to test factory behavior related to addresses.
@return: A L{defer.Deferred} which will be called back when both the
client and server protocols have received their connection made
callback. | setUp | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def tearDown(self):
"""
Disconnect the client/server pair and shutdown the port created in
L{setUp}.
"""
self.connector.disconnect()
return defer.gatherResults([
self.serverConnLost, self.clientConnLost,
defer.maybeDeferred(self.port.stopListening)]) | Disconnect the client/server pair and shutdown the port created in
L{setUp}. | tearDown | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def test_buildProtocolClient(self):
"""
L{ClientFactory.buildProtocol} should be invoked with the address of
the server to which a connection has been established, which should
be the same as the address reported by the C{getHost} method of the
transport of the server protocol and as the C{getPeer} method of the
transport of the client protocol.
"""
serverHost = self.server.protocol.transport.getHost()
clientPeer = self.client.protocol.transport.getPeer()
self.assertEqual(
self.clientWrapper.addresses,
[IPv4Address('TCP', serverHost.host, serverHost.port)])
self.assertEqual(
self.clientWrapper.addresses,
[IPv4Address('TCP', clientPeer.host, clientPeer.port)]) | L{ClientFactory.buildProtocol} should be invoked with the address of
the server to which a connection has been established, which should
be the same as the address reported by the C{getHost} method of the
transport of the server protocol and as the C{getPeer} method of the
transport of the client protocol. | test_buildProtocolClient | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def testNoNotification(self):
"""
TCP protocols support half-close connections, but not all of them
support being notified of write closes. In this case, test that
half-closing the connection causes the peer's connection to be
closed.
"""
self.client.transport.write(b"hello")
self.client.transport.loseWriteConnection()
self.f.protocol.closedDeferred = d = defer.Deferred()
self.client.closedDeferred = d2 = defer.Deferred()
d.addCallback(lambda x:
self.assertEqual(self.f.protocol.data, b'hello'))
d.addCallback(lambda x: self.assertTrue(self.f.protocol.closed))
return defer.gatherResults([d, d2]) | TCP protocols support half-close connections, but not all of them
support being notified of write closes. In this case, test that
half-closing the connection causes the peer's connection to be
closed. | testNoNotification | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def testShutdownException(self):
"""
If the other side has already closed its connection,
loseWriteConnection should pass silently.
"""
self.f.protocol.transport.loseConnection()
self.client.transport.write(b"X")
self.client.transport.loseWriteConnection()
self.f.protocol.closedDeferred = d = defer.Deferred()
self.client.closedDeferred = d2 = defer.Deferred()
d.addCallback(lambda x:
self.assertTrue(self.f.protocol.closed))
return defer.gatherResults([d, d2]) | If the other side has already closed its connection,
loseWriteConnection should pass silently. | testShutdownException | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def setUp(self):
"""
Set up a server and connect a client to it. Return a Deferred which
only fires once this is done.
"""
self.serverFactory = MyHCFactory()
self.serverFactory.protocolConnectionMade = defer.Deferred()
self.port = reactor.listenTCP(
0, self.serverFactory, interface="127.0.0.1")
self.addCleanup(self.port.stopListening)
addr = self.port.getHost()
creator = protocol.ClientCreator(reactor, MyHCProtocol)
clientDeferred = creator.connectTCP(addr.host, addr.port)
def setClient(clientProtocol):
self.clientProtocol = clientProtocol
clientDeferred.addCallback(setClient)
return defer.gatherResults([
self.serverFactory.protocolConnectionMade,
clientDeferred]) | Set up a server and connect a client to it. Return a Deferred which
only fires once this is done. | setUp | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def aBug(self, *args):
"""
Fake implementation of a callback which illegally raises an
exception.
"""
raise RuntimeError("ONO I AM BUGGY CODE") | Fake implementation of a callback which illegally raises an
exception. | aBug | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def _notificationRaisesTest(self):
"""
Helper for testing that an exception is logged by the time the
client protocol loses its connection.
"""
closed = self.clientProtocol.closedDeferred = defer.Deferred()
self.clientProtocol.transport.loseWriteConnection()
def check(ignored):
errors = self.flushLoggedErrors(RuntimeError)
self.assertEqual(len(errors), 1)
closed.addCallback(check)
return closed | Helper for testing that an exception is logged by the time the
client protocol loses its connection. | _notificationRaisesTest | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def test_readNotificationRaises(self):
"""
If C{readConnectionLost} raises an exception when the transport
calls it to notify the protocol of that event, the exception should
be logged and the protocol should be disconnected completely.
"""
self.serverFactory.protocol.readConnectionLost = self.aBug
return self._notificationRaisesTest() | If C{readConnectionLost} raises an exception when the transport
calls it to notify the protocol of that event, the exception should
be logged and the protocol should be disconnected completely. | test_readNotificationRaises | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def test_writeNotificationRaises(self):
"""
If C{writeConnectionLost} raises an exception when the transport
calls it to notify the protocol of that event, the exception should
be logged and the protocol should be disconnected completely.
"""
self.clientProtocol.writeConnectionLost = self.aBug
return self._notificationRaisesTest() | If C{writeConnectionLost} raises an exception when the transport
calls it to notify the protocol of that event, the exception should
be logged and the protocol should be disconnected completely. | test_writeNotificationRaises | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def test_logstrClientSetup(self):
"""
Check that the log customization of the client transport happens
once the client is connected.
"""
server = MyServerFactory()
client = MyClientFactory()
client.protocolConnectionMade = defer.Deferred()
port = reactor.listenTCP(0, server, interface='127.0.0.1')
self.addCleanup(port.stopListening)
connector = reactor.connectTCP(
port.getHost().host, port.getHost().port, client)
self.addCleanup(connector.disconnect)
# It should still have the default value
self.assertEqual(connector.transport.logstr,
"Uninitialized")
def cb(ign):
self.assertEqual(connector.transport.logstr,
"AccumulatingProtocol,client")
client.protocolConnectionMade.addCallback(cb)
return client.protocolConnectionMade | Check that the log customization of the client transport happens
once the client is connected. | test_logstrClientSetup | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def test_pauseProducingInConnectionMade(self):
"""
In C{connectionMade} of a client protocol, C{pauseProducing} used to be
ignored: this test is here to ensure it's not ignored.
"""
server = MyServerFactory()
client = MyClientFactory()
client.protocolConnectionMade = defer.Deferred()
port = reactor.listenTCP(0, server, interface='127.0.0.1')
self.addCleanup(port.stopListening)
connector = reactor.connectTCP(
port.getHost().host, port.getHost().port, client)
self.addCleanup(connector.disconnect)
def checkInConnectionMade(proto):
tr = proto.transport
# The transport should already be monitored
self.assertIn(tr, reactor.getReaders() +
reactor.getWriters())
proto.transport.pauseProducing()
self.assertNotIn(tr, reactor.getReaders() +
reactor.getWriters())
d = defer.Deferred()
d.addCallback(checkAfterConnectionMade)
reactor.callLater(0, d.callback, proto)
return d
def checkAfterConnectionMade(proto):
tr = proto.transport
# The transport should still not be monitored
self.assertNotIn(tr, reactor.getReaders() +
reactor.getWriters())
client.protocolConnectionMade.addCallback(checkInConnectionMade)
return client.protocolConnectionMade | In C{connectionMade} of a client protocol, C{pauseProducing} used to be
ignored: this test is here to ensure it's not ignored. | test_pauseProducingInConnectionMade | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def _cbCM(res):
"""
protocol.connectionMade callback
"""
reactor.callLater(0, client.protocol.transport.loseConnection) | protocol.connectionMade callback | test_loseOrder._cbCM | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def _cbCCL(res):
"""
factory.clientConnectionLost callback
"""
return 'CCL' | factory.clientConnectionLost callback | test_loseOrder._cbCCL | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def _cbCL(res):
"""
protocol.connectionLost callback
"""
return 'CL' | protocol.connectionLost callback | test_loseOrder._cbCL | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def test_loseOrder(self):
"""
Check that Protocol.connectionLost is called before factory's
clientConnectionLost
"""
server = MyServerFactory()
server.protocolConnectionMade = (defer.Deferred()
.addCallback(lambda proto: self.addCleanup(
proto.transport.loseConnection)))
client = MyClientFactory()
client.protocolConnectionLost = defer.Deferred()
client.protocolConnectionMade = defer.Deferred()
def _cbCM(res):
"""
protocol.connectionMade callback
"""
reactor.callLater(0, client.protocol.transport.loseConnection)
client.protocolConnectionMade.addCallback(_cbCM)
port = reactor.listenTCP(0, server, interface='127.0.0.1')
self.addCleanup(port.stopListening)
connector = reactor.connectTCP(
port.getHost().host, port.getHost().port, client)
self.addCleanup(connector.disconnect)
def _cbCCL(res):
"""
factory.clientConnectionLost callback
"""
return 'CCL'
def _cbCL(res):
"""
protocol.connectionLost callback
"""
return 'CL'
def _cbGather(res):
self.assertEqual(res, ['CL', 'CCL'])
d = defer.gatherResults([
client.protocolConnectionLost.addCallback(_cbCL),
client.deferred.addCallback(_cbCCL)])
return d.addCallback(_cbGather) | Check that Protocol.connectionLost is called before factory's
clientConnectionLost | test_loseOrder | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py | MIT |
def method(self):
"""
A no-op method which can be discovered.
""" | A no-op method which can be discovered. | method | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_reflect.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_reflect.py | MIT |
def good_method(self):
"""
A no-op method which a matching prefix to be discovered.
""" | A no-op method which a matching prefix to be discovered. | good_method | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_reflect.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_reflect.py | MIT |
def bad_method(self):
"""
A no-op method with a mismatched prefix to not be discovered.
""" | A no-op method with a mismatched prefix to not be discovered. | bad_method | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_reflect.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_reflect.py | MIT |
def test_ownClass(self):
"""
If x is and instance of Base and Base defines a method named method,
L{accumulateMethods} adds an item to the given dictionary with
C{"method"} as the key and a bound method object for Base.method value.
"""
x = Base()
output = {}
accumulateMethods(x, output)
self.assertEqual({"method": x.method}, output) | If x is and instance of Base and Base defines a method named method,
L{accumulateMethods} adds an item to the given dictionary with
C{"method"} as the key and a bound method object for Base.method value. | test_ownClass | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_reflect.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_reflect.py | MIT |
Subsets and Splits