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_noSubcommand(self): """ If no subcommand is specified and no default subcommand is assigned, a subcommand will not be implied. """ o = SubCommandOptions() o.parseOptions(['--europian-swallow']) self.assertTrue(o['europian-swallow']) self.assertIsNone(o.subCommand) self.assertFalse(hasattr(o, 'subOptions'))
If no subcommand is specified and no default subcommand is assigned, a subcommand will not be implied.
test_noSubcommand
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
MIT
def test_defaultSubcommand(self): """ Flags and options in the default subcommand are assigned. """ o = SubCommandOptions() o.defaultSubCommand = 'inquest' o.parseOptions(['--europian-swallow']) self.assertTrue(o['europian-swallow']) self.assertEqual(o.subCommand, 'inquisition') self.assertIsInstance(o.subOptions, InquisitionOptions) self.assertFalse(o.subOptions['expect']) self.assertEqual(o.subOptions['torture-device'], 'comfy-chair')
Flags and options in the default subcommand are assigned.
test_defaultSubcommand
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
MIT
def test_subCommandParseOptionsHasParent(self): """ The parseOptions method from the Options object specified for the given subcommand is called. """ class SubOpt(usage.Options): def parseOptions(self, *a, **kw): self.sawParent = self.parent usage.Options.parseOptions(self, *a, **kw) class Opt(usage.Options): subCommands = [ ('foo', 'f', SubOpt, 'bar'), ] o = Opt() o.parseOptions(['foo']) self.assertTrue(hasattr(o.subOptions, 'sawParent')) self.assertEqual(o.subOptions.sawParent , o)
The parseOptions method from the Options object specified for the given subcommand is called.
test_subCommandParseOptionsHasParent
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
MIT
def test_subCommandInTwoPlaces(self): """ The .parent pointer is correct even when the same Options class is used twice. """ class SubOpt(usage.Options): pass class OptFoo(usage.Options): subCommands = [ ('foo', 'f', SubOpt, 'quux'), ] class OptBar(usage.Options): subCommands = [ ('bar', 'b', SubOpt, 'quux'), ] oFoo = OptFoo() oFoo.parseOptions(['foo']) oBar=OptBar() oBar.parseOptions(['bar']) self.assertTrue(hasattr(oFoo.subOptions, 'parent')) self.assertTrue(hasattr(oBar.subOptions, 'parent')) self.failUnlessIdentical(oFoo.subOptions.parent, oFoo) self.failUnlessIdentical(oBar.subOptions.parent, oBar)
The .parent pointer is correct even when the same Options class is used twice.
test_subCommandInTwoPlaces
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
MIT
def setUp(self): """ Instantiate a well-behaved Options class. """ self.niceArgV = ("--long Alpha -n Beta " "--shortless Gamma -f --myflag " "--myparam Tofu").split() self.nice = WellBehaved()
Instantiate a well-behaved Options class.
setUp
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
MIT
def test_noGoBoom(self): """ __str__ shouldn't go boom. """ try: self.nice.__str__() except Exception as e: self.fail(e)
__str__ shouldn't go boom.
test_noGoBoom
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
MIT
def test_whitespaceStripFlagsAndParameters(self): """ Extra whitespace in flag and parameters docs is stripped. """ # We test this by making sure aflag and it's help string are on the # same line. lines = [s for s in str(self.nice).splitlines() if s.find("aflag")>=0] self.assertTrue(len(lines) > 0) self.assertTrue(lines[0].find("flagallicious") >= 0)
Extra whitespace in flag and parameters docs is stripped.
test_whitespaceStripFlagsAndParameters
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
MIT
def test_validCoerce(self): """ Test the answers with valid input. """ self.assertEqual(0, usage.portCoerce("0")) self.assertEqual(3210, usage.portCoerce("3210")) self.assertEqual(65535, usage.portCoerce("65535"))
Test the answers with valid input.
test_validCoerce
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
MIT
def test_errorCoerce(self): """ Test error path. """ self.assertRaises(ValueError, usage.portCoerce, "") self.assertRaises(ValueError, usage.portCoerce, "-21") self.assertRaises(ValueError, usage.portCoerce, "212189") self.assertRaises(ValueError, usage.portCoerce, "foo")
Test error path.
test_errorCoerce
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
MIT
def test_completer(self): """ Completer produces zsh shell-code that produces no completion matches. """ c = usage.Completer() got = c._shellCode('some-option', usage._ZSH) self.assertEqual(got, ':some-option:') c = usage.Completer(descr='some action', repeat=True) got = c._shellCode('some-option', usage._ZSH) self.assertEqual(got, '*:some action:')
Completer produces zsh shell-code that produces no completion matches.
test_completer
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
MIT
def test_files(self): """ CompleteFiles produces zsh shell-code that completes file names according to a glob. """ c = usage.CompleteFiles() got = c._shellCode('some-option', usage._ZSH) self.assertEqual(got, ':some-option (*):_files -g "*"') c = usage.CompleteFiles('*.py') got = c._shellCode('some-option', usage._ZSH) self.assertEqual(got, ':some-option (*.py):_files -g "*.py"') c = usage.CompleteFiles('*.py', descr="some action", repeat=True) got = c._shellCode('some-option', usage._ZSH) self.assertEqual(got, '*:some action (*.py):_files -g "*.py"')
CompleteFiles produces zsh shell-code that completes file names according to a glob.
test_files
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
MIT
def test_dirs(self): """ CompleteDirs produces zsh shell-code that completes directory names. """ c = usage.CompleteDirs() got = c._shellCode('some-option', usage._ZSH) self.assertEqual(got, ':some-option:_directories') c = usage.CompleteDirs(descr="some action", repeat=True) got = c._shellCode('some-option', usage._ZSH) self.assertEqual(got, '*:some action:_directories')
CompleteDirs produces zsh shell-code that completes directory names.
test_dirs
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
MIT
def test_list(self): """ CompleteList produces zsh shell-code that completes words from a fixed list of possibilities. """ c = usage.CompleteList('ABC') got = c._shellCode('some-option', usage._ZSH) self.assertEqual(got, ':some-option:(A B C)') c = usage.CompleteList(['1', '2', '3']) got = c._shellCode('some-option', usage._ZSH) self.assertEqual(got, ':some-option:(1 2 3)') c = usage.CompleteList(['1', '2', '3'], descr='some action', repeat=True) got = c._shellCode('some-option', usage._ZSH) self.assertEqual(got, '*:some action:(1 2 3)')
CompleteList produces zsh shell-code that completes words from a fixed list of possibilities.
test_list
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
MIT
def test_multiList(self): """ CompleteMultiList produces zsh shell-code that completes multiple comma-separated words from a fixed list of possibilities. """ c = usage.CompleteMultiList('ABC') got = c._shellCode('some-option', usage._ZSH) self.assertEqual(got, ':some-option:_values -s , \'some-option\' A B C') c = usage.CompleteMultiList(['1','2','3']) got = c._shellCode('some-option', usage._ZSH) self.assertEqual(got, ':some-option:_values -s , \'some-option\' 1 2 3') c = usage.CompleteMultiList(['1','2','3'], descr='some action', repeat=True) got = c._shellCode('some-option', usage._ZSH) expected = '*:some action:_values -s , \'some action\' 1 2 3' self.assertEqual(got, expected)
CompleteMultiList produces zsh shell-code that completes multiple comma-separated words from a fixed list of possibilities.
test_multiList
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
MIT
def test_usernames(self): """ CompleteUsernames produces zsh shell-code that completes system usernames. """ c = usage.CompleteUsernames() out = c._shellCode('some-option', usage._ZSH) self.assertEqual(out, ':some-option:_users') c = usage.CompleteUsernames(descr='some action', repeat=True) out = c._shellCode('some-option', usage._ZSH) self.assertEqual(out, '*:some action:_users')
CompleteUsernames produces zsh shell-code that completes system usernames.
test_usernames
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
MIT
def test_groups(self): """ CompleteGroups produces zsh shell-code that completes system group names. """ c = usage.CompleteGroups() out = c._shellCode('some-option', usage._ZSH) self.assertEqual(out, ':group:_groups') c = usage.CompleteGroups(descr='some action', repeat=True) out = c._shellCode('some-option', usage._ZSH) self.assertEqual(out, '*:some action:_groups')
CompleteGroups produces zsh shell-code that completes system group names.
test_groups
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
MIT
def test_hostnames(self): """ CompleteHostnames produces zsh shell-code that completes hostnames. """ c = usage.CompleteHostnames() out = c._shellCode('some-option', usage._ZSH) self.assertEqual(out, ':some-option:_hosts') c = usage.CompleteHostnames(descr='some action', repeat=True) out = c._shellCode('some-option', usage._ZSH) self.assertEqual(out, '*:some action:_hosts')
CompleteHostnames produces zsh shell-code that completes hostnames.
test_hostnames
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
MIT
def test_userAtHost(self): """ CompleteUserAtHost produces zsh shell-code that completes hostnames or a word of the form <username>@<hostname>. """ c = usage.CompleteUserAtHost() out = c._shellCode('some-option', usage._ZSH) self.assertTrue(out.startswith(':host | user@host:')) c = usage.CompleteUserAtHost(descr='some action', repeat=True) out = c._shellCode('some-option', usage._ZSH) self.assertTrue(out.startswith('*:some action:'))
CompleteUserAtHost produces zsh shell-code that completes hostnames or a word of the form <username>@<hostname>.
test_userAtHost
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
MIT
def test_netInterfaces(self): """ CompleteNetInterfaces produces zsh shell-code that completes system network interface names. """ c = usage.CompleteNetInterfaces() out = c._shellCode('some-option', usage._ZSH) self.assertEqual(out, ':some-option:_net_interfaces') c = usage.CompleteNetInterfaces(descr='some action', repeat=True) out = c._shellCode('some-option', usage._ZSH) self.assertEqual(out, '*:some action:_net_interfaces')
CompleteNetInterfaces produces zsh shell-code that completes system network interface names.
test_netInterfaces
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
MIT
def test_unknownShell(self): """ Using an unknown shellType should raise NotImplementedError """ classes = [usage.Completer, usage.CompleteFiles, usage.CompleteDirs, usage.CompleteList, usage.CompleteMultiList, usage.CompleteUsernames, usage.CompleteGroups, usage.CompleteHostnames, usage.CompleteUserAtHost, usage.CompleteNetInterfaces] for cls in classes: try: action = cls() except: action = cls(None) self.assertRaises(NotImplementedError, action._shellCode, None, "bad_shell_type")
Using an unknown shellType should raise NotImplementedError
test_unknownShell
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
MIT
def oneArg(self, a): """ A one argument method to be tested by L{usage.flagFunction}. @param a: a useless argument to satisfy the function's signature. """
A one argument method to be tested by L{usage.flagFunction}. @param a: a useless argument to satisfy the function's signature.
oneArg
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
MIT
def noArg(self): """ A no argument method to be tested by L{usage.flagFunction}. """
A no argument method to be tested by L{usage.flagFunction}.
noArg
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
MIT
def manyArgs(self, a, b, c): """ A multiple arguments method to be tested by L{usage.flagFunction}. @param a: a useless argument to satisfy the function's signature. @param b: a useless argument to satisfy the function's signature. @param c: a useless argument to satisfy the function's signature. """
A multiple arguments method to be tested by L{usage.flagFunction}. @param a: a useless argument to satisfy the function's signature. @param b: a useless argument to satisfy the function's signature. @param c: a useless argument to satisfy the function's signature.
manyArgs
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
MIT
def test_hasArg(self): """ L{usage.flagFunction} returns C{False} if the method checked allows exactly one argument. """ self.assertIs(False, usage.flagFunction(self.SomeClass().oneArg))
L{usage.flagFunction} returns C{False} if the method checked allows exactly one argument.
test_hasArg
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
MIT
def test_noArg(self): """ L{usage.flagFunction} returns C{True} if the method checked allows exactly no argument. """ self.assertIs(True, usage.flagFunction(self.SomeClass().noArg))
L{usage.flagFunction} returns C{True} if the method checked allows exactly no argument.
test_noArg
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
MIT
def test_tooManyArguments(self): """ L{usage.flagFunction} raises L{usage.UsageError} if the method checked allows more than one argument. """ exc = self.assertRaises( usage.UsageError, usage.flagFunction, self.SomeClass().manyArgs) self.assertEqual("Invalid Option function for manyArgs", str(exc))
L{usage.flagFunction} raises L{usage.UsageError} if the method checked allows more than one argument.
test_tooManyArguments
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
MIT
def test_tooManyArgumentsAndSpecificErrorMessage(self): """ L{usage.flagFunction} uses the given method name in the error message raised when the method allows too many arguments. """ exc = self.assertRaises( usage.UsageError, usage.flagFunction, self.SomeClass().manyArgs, "flubuduf") self.assertEqual("Invalid Option function for flubuduf", str(exc))
L{usage.flagFunction} uses the given method name in the error message raised when the method allows too many arguments.
test_tooManyArgumentsAndSpecificErrorMessage
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
MIT
def opt_very_very_long(self): """ This is an option method with a very long name, that is going to be aliased. """
This is an option method with a very long name, that is going to be aliased.
test_optionsAliasesOrder.opt_very_very_long
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
MIT
def test_optionsAliasesOrder(self): """ Options which are synonyms to another option are aliases towards the longest option name. """ class Opts(usage.Options): def opt_very_very_long(self): """ This is an option method with a very long name, that is going to be aliased. """ opt_short = opt_very_very_long opt_s = opt_very_very_long opts = Opts() self.assertEqual( dict.fromkeys( ["s", "short", "very-very-long"], "very-very-long"), { "s": opts.synonyms["s"], "short": opts.synonyms["short"], "very-very-long": opts.synonyms["very-very-long"], })
Options which are synonyms to another option are aliases towards the longest option name.
test_optionsAliasesOrder
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_usage.py
MIT
def stringReceived(self, msg): """ Override this. """ raise NotImplementedError
Override this.
stringReceived
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_stateful.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_stateful.py
MIT
def sendString(self, data): """ Send an int32-prefixed string to the other end of the connection. """ self.transport.write(pack(self.structFormat, len(data)) + data)
Send an int32-prefixed string to the other end of the connection.
sendString
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_stateful.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_stateful.py
MIT
def pump(self): """Move data back and forth. Returns whether any data was moved. """ self.clientIO.seek(0) self.serverIO.seek(0) cData = self.clientIO.read() sData = self.serverIO.read() self.clientIO.seek(0) self.serverIO.seek(0) self.clientIO.truncate() self.serverIO.truncate() for byte in cData: self.server.dataReceived(byte) for byte in sData: self.client.dataReceived(byte) if cData or sData: return 1 else: return 0
Move data back and forth. Returns whether any data was moved.
pump
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/testutils.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/testutils.py
MIT
def returnConnected(server, client): """Take two Protocol instances and connect them. """ cio = BytesIO() sio = BytesIO() client.makeConnection(FileWrapper(cio)) server.makeConnection(FileWrapper(sio)) pump = IOPump(client, server, cio, sio) # Challenge-response authentication: pump.flush() # Uh... pump.flush() return pump
Take two Protocol instances and connect them.
returnConnected
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/testutils.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/testutils.py
MIT
def assertXMLEqual(self, first, second): """ Verify that two strings represent the same XML document. @param first: An XML string. @type first: L{bytes} @param second: An XML string that should match C{first}. @type second: L{bytes} """ self.assertEqual( dom.parseString(first).toxml(), dom.parseString(second).toxml())
Verify that two strings represent the same XML document. @param first: An XML string. @type first: L{bytes} @param second: An XML string that should match C{first}. @type second: L{bytes}
assertXMLEqual
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/testutils.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/testutils.py
MIT
def assertNormalEqualityImplementation(self, firstValueOne, secondValueOne, valueTwo): """ Assert that C{firstValueOne} is equal to C{secondValueOne} but not equal to C{valueOne} and that it defines equality cooperatively with other types it doesn't know about. @param firstValueOne: An object which is expected to compare as equal to C{secondValueOne} and not equal to C{valueTwo}. @param secondValueOne: A different object than C{firstValueOne} but which is expected to compare equal to that object. @param valueTwo: An object which is expected to compare as not equal to C{firstValueOne}. """ # This doesn't use assertEqual and assertNotEqual because the exact # operator those functions use is not very well defined. The point # of these assertions is to check the results of the use of specific # operators (precisely to ensure that using different permutations # (eg "x == y" or "not (x != y)") which should yield the same results # actually does yield the same result). -exarkun self.assertTrue(firstValueOne == firstValueOne) self.assertTrue(firstValueOne == secondValueOne) self.assertFalse(firstValueOne == valueTwo) self.assertFalse(firstValueOne != firstValueOne) self.assertFalse(firstValueOne != secondValueOne) self.assertTrue(firstValueOne != valueTwo) self.assertTrue(firstValueOne == _Equal()) self.assertFalse(firstValueOne != _Equal()) self.assertFalse(firstValueOne == _NotEqual()) self.assertTrue(firstValueOne != _NotEqual())
Assert that C{firstValueOne} is equal to C{secondValueOne} but not equal to C{valueOne} and that it defines equality cooperatively with other types it doesn't know about. @param firstValueOne: An object which is expected to compare as equal to C{secondValueOne} and not equal to C{valueTwo}. @param secondValueOne: A different object than C{firstValueOne} but which is expected to compare equal to that object. @param valueTwo: An object which is expected to compare as not equal to C{firstValueOne}.
assertNormalEqualityImplementation
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/testutils.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/testutils.py
MIT
def func(self): """ A function on an old style class. @return: "hi", for testing. """ return "hi"
A function on an old style class. @return: "hi", for testing.
func
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_nooldstyle.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_nooldstyle.py
MIT
def test_makesNewStyle(self): """ L{_oldstyle._oldStyle} wraps an old-style class and returns a new-style class that has the same functions, attributes, etc. """ class SomeClassThatUsesOldStyle(SomeOldStyleClass): pass self.assertEqual(type(SomeClassThatUsesOldStyle), types.ClassType) updatedClass = _oldstyle._oldStyle(SomeClassThatUsesOldStyle) self.assertEqual(type(updatedClass), type) self.assertEqual(updatedClass.__bases__, (SomeOldStyleClass, object)) self.assertEqual(updatedClass().func(), "hi") self.assertEqual(updatedClass().bar, "baz")
L{_oldstyle._oldStyle} wraps an old-style class and returns a new-style class that has the same functions, attributes, etc.
test_makesNewStyle
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_nooldstyle.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_nooldstyle.py
MIT
def test_carriesAttributes(self): """ The class returned by L{_oldstyle._oldStyle} has the same C{__name__}, C{__module__}, and docstring (C{__doc__}) attributes as the original. """ updatedClass = _oldstyle._oldStyle(SomeOldStyleClass) self.assertEqual(updatedClass.__name__, SomeOldStyleClass.__name__) self.assertEqual(updatedClass.__doc__, SomeOldStyleClass.__doc__) self.assertEqual(updatedClass.__module__, SomeOldStyleClass.__module__)
The class returned by L{_oldstyle._oldStyle} has the same C{__name__}, C{__module__}, and docstring (C{__doc__}) attributes as the original.
test_carriesAttributes
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_nooldstyle.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_nooldstyle.py
MIT
def test_onlyOldStyleMayBeDecorated(self): """ Using L{_oldstyle._oldStyle} on a new-style class on Python 2 will raise an exception. """ with self.assertRaises(ValueError) as e: _oldstyle._oldStyle(SomeNewStyleClass) self.assertEqual( e.exception.args[0], ("twisted.python._oldstyle._oldStyle is being used to decorate a " "new-style class (twisted.test.test_nooldstyle.SomeNewStyleClass)" ". This should only be used to decorate old-style classes."))
Using L{_oldstyle._oldStyle} on a new-style class on Python 2 will raise an exception.
test_onlyOldStyleMayBeDecorated
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_nooldstyle.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_nooldstyle.py
MIT
def test_noOpByDefault(self): """ On Python 3 or on Py2 when C{TWISTED_NEWSTYLE} is not set, L{_oldStyle._oldStyle} is a no-op. """ updatedClass = _oldstyle._oldStyle(SomeOldStyleClass) self.assertEqual(type(updatedClass), type(SomeOldStyleClass)) self.assertIs(updatedClass, SomeOldStyleClass)
On Python 3 or on Py2 when C{TWISTED_NEWSTYLE} is not set, L{_oldStyle._oldStyle} is a no-op.
test_noOpByDefault
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_nooldstyle.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_nooldstyle.py
MIT
def test_newStyleClassesOnly(self): """ Test that C{self.module} has no old-style classes in it. """ try: module = namedAny(self.module) except ImportError as e: raise unittest.SkipTest("Not importable: {}".format(e)) oldStyleClasses = [] for name, val in inspect.getmembers(module): if hasattr(val, "__module__") \ and val.__module__ == self.module: if isinstance(val, types.ClassType): oldStyleClasses.append(fullyQualifiedName(val)) if oldStyleClasses: self.todo = "Not all classes are made new-style yet. See #8243." for x in forbiddenModules: if self.module.startswith(x): delattr(self, "todo") raise unittest.FailTest( "Old-style classes in {module}: {val}".format( module=self.module, val=", ".join(oldStyleClasses)))
Test that C{self.module} has no old-style classes in it.
test_newStyleClassesOnly
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_nooldstyle.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_nooldstyle.py
MIT
def _buildTestClasses(_locals): """ Build the test classes that use L{NewStyleOnly}, one class per module. @param _locals: The global C{locals()} dict. """ for x in getModule("twisted").walkModules(): ignoredModules = [ "twisted.test.reflect_helper", "twisted.internet.test.process_", "twisted.test.process_" ] isIgnored = [x.name.startswith(ignored) for ignored in ignoredModules] if True in isIgnored: continue class Test(NewStyleOnly, unittest.TestCase): """ @see: L{NewStyleOnly} """ module = x.name acceptableName = x.name.replace(".", "_") Test.__name__ = acceptableName if hasattr(Test, "__qualname__"): Test.__qualname__ = acceptableName _locals.update({acceptableName: Test})
Build the test classes that use L{NewStyleOnly}, one class per module. @param _locals: The global C{locals()} dict.
_buildTestClasses
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_nooldstyle.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_nooldstyle.py
MIT
def makeSourceFile(self, sourceLines): """ Write the given list of lines to a text file and return the absolute path to it. """ script = self.mktemp() with open(script, 'wt') as scriptFile: scriptFile.write(os.linesep.join(sourceLines) + os.linesep) return os.path.abspath(script)
Write the given list of lines to a text file and return the absolute path to it.
makeSourceFile
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iutils.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iutils.py
MIT
def test_output(self): """ L{getProcessOutput} returns a L{Deferred} which fires with the complete output of the process it runs after that process exits. """ scriptFile = self.makeSourceFile([ "import sys", "for s in b'hello world\\n':", " if hasattr(sys.stdout, 'buffer'):", " # Python 3", " s = bytes([s])", " sys.stdout.buffer.write(s)", " else:", " # Python 2", " sys.stdout.write(s)", " sys.stdout.flush()"]) d = utils.getProcessOutput(self.exe, ['-u', scriptFile]) return d.addCallback(self.assertEqual, b"hello world\n")
L{getProcessOutput} returns a L{Deferred} which fires with the complete output of the process it runs after that process exits.
test_output
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iutils.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iutils.py
MIT
def test_outputWithErrorIgnored(self): """ The L{Deferred} returned by L{getProcessOutput} is fired with an L{IOError} L{Failure} if the child process writes to stderr. """ # make sure stderr raises an error normally scriptFile = self.makeSourceFile([ 'import sys', 'sys.stderr.write("hello world\\n")' ]) d = utils.getProcessOutput(self.exe, ['-u', scriptFile]) d = self.assertFailure(d, IOError) def cbFailed(err): return self.assertFailure(err.processEnded, error.ProcessDone) d.addCallback(cbFailed) return d
The L{Deferred} returned by L{getProcessOutput} is fired with an L{IOError} L{Failure} if the child process writes to stderr.
test_outputWithErrorIgnored
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iutils.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iutils.py
MIT
def test_outputWithErrorCollected(self): """ If a C{True} value is supplied for the C{errortoo} parameter to L{getProcessOutput}, the returned L{Deferred} fires with the child's stderr output as well as its stdout output. """ scriptFile = self.makeSourceFile([ 'import sys', # Write the same value to both because ordering isn't guaranteed so # this simplifies the test. 'sys.stdout.write("foo")', 'sys.stdout.flush()', 'sys.stderr.write("foo")', 'sys.stderr.flush()']) d = utils.getProcessOutput(self.exe, ['-u', scriptFile], errortoo=True) return d.addCallback(self.assertEqual, b"foofoo")
If a C{True} value is supplied for the C{errortoo} parameter to L{getProcessOutput}, the returned L{Deferred} fires with the child's stderr output as well as its stdout output.
test_outputWithErrorCollected
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iutils.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iutils.py
MIT
def test_value(self): """ The L{Deferred} returned by L{getProcessValue} is fired with the exit status of the child process. """ scriptFile = self.makeSourceFile(["raise SystemExit(1)"]) d = utils.getProcessValue(self.exe, ['-u', scriptFile]) return d.addCallback(self.assertEqual, 1)
The L{Deferred} returned by L{getProcessValue} is fired with the exit status of the child process.
test_value
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iutils.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iutils.py
MIT
def test_outputAndValue(self): """ The L{Deferred} returned by L{getProcessOutputAndValue} fires with a three-tuple, the elements of which give the data written to the child's stdout, the data written to the child's stderr, and the exit status of the child. """ scriptFile = self.makeSourceFile([ "import sys", "if hasattr(sys.stdout, 'buffer'):", " # Python 3", " sys.stdout.buffer.write(b'hello world!\\n')", " sys.stderr.buffer.write(b'goodbye world!\\n')", "else:", " # Python 2", " sys.stdout.write(b'hello world!\\n')", " sys.stderr.write(b'goodbye world!\\n')", "sys.exit(1)" ]) def gotOutputAndValue(out_err_code): out, err, code = out_err_code self.assertEqual(out, b"hello world!\n") if _PY3: self.assertEqual(err, b"goodbye world!\n") else: self.assertEqual(err, b"goodbye world!" + os.linesep) self.assertEqual(code, 1) d = utils.getProcessOutputAndValue(self.exe, ["-u", scriptFile]) return d.addCallback(gotOutputAndValue)
The L{Deferred} returned by L{getProcessOutputAndValue} fires with a three-tuple, the elements of which give the data written to the child's stdout, the data written to the child's stderr, and the exit status of the child.
test_outputAndValue
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iutils.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iutils.py
MIT
def test_outputSignal(self): """ If the child process exits because of a signal, the L{Deferred} returned by L{getProcessOutputAndValue} fires a L{Failure} of a tuple containing the child's stdout, stderr, and the signal which caused it to exit. """ # Use SIGKILL here because it's guaranteed to be delivered. Using # SIGHUP might not work in, e.g., a buildbot slave run under the # 'nohup' command. scriptFile = self.makeSourceFile([ "import sys, os, signal", "sys.stdout.write('stdout bytes\\n')", "sys.stderr.write('stderr bytes\\n')", "sys.stdout.flush()", "sys.stderr.flush()", "os.kill(os.getpid(), signal.SIGKILL)"]) def gotOutputAndValue(out_err_sig): out, err, sig = out_err_sig self.assertEqual(out, b"stdout bytes\n") self.assertEqual(err, b"stderr bytes\n") self.assertEqual(sig, signal.SIGKILL) d = utils.getProcessOutputAndValue(self.exe, ['-u', scriptFile]) d = self.assertFailure(d, tuple) return d.addCallback(gotOutputAndValue)
If the child process exits because of a signal, the L{Deferred} returned by L{getProcessOutputAndValue} fires a L{Failure} of a tuple containing the child's stdout, stderr, and the signal which caused it to exit.
test_outputSignal
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iutils.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iutils.py
MIT
def test_getProcessOutputPath(self): """ L{getProcessOutput} runs the given command with the working directory given by the C{path} parameter. """ return self._pathTest(utils.getProcessOutput, self.assertEqual)
L{getProcessOutput} runs the given command with the working directory given by the C{path} parameter.
test_getProcessOutputPath
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iutils.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iutils.py
MIT
def test_getProcessValuePath(self): """ L{getProcessValue} runs the given command with the working directory given by the C{path} parameter. """ def check(result, ignored): self.assertEqual(result, 0) return self._pathTest(utils.getProcessValue, check)
L{getProcessValue} runs the given command with the working directory given by the C{path} parameter.
test_getProcessValuePath
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iutils.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iutils.py
MIT
def test_getProcessOutputAndValuePath(self): """ L{getProcessOutputAndValue} runs the given command with the working directory given by the C{path} parameter. """ def check(out_err_status, dir): out, err, status = out_err_status self.assertEqual(out, dir) self.assertEqual(status, 0) return self._pathTest(utils.getProcessOutputAndValue, check)
L{getProcessOutputAndValue} runs the given command with the working directory given by the C{path} parameter.
test_getProcessOutputAndValuePath
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iutils.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iutils.py
MIT
def test_getProcessOutputDefaultPath(self): """ If no value is supplied for the C{path} parameter, L{getProcessOutput} runs the given command in the same working directory as the parent process and succeeds even if the current working directory is not accessible. """ return self._defaultPathTest(utils.getProcessOutput, self.assertEqual)
If no value is supplied for the C{path} parameter, L{getProcessOutput} runs the given command in the same working directory as the parent process and succeeds even if the current working directory is not accessible.
test_getProcessOutputDefaultPath
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iutils.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iutils.py
MIT
def test_getProcessValueDefaultPath(self): """ If no value is supplied for the C{path} parameter, L{getProcessValue} runs the given command in the same working directory as the parent process and succeeds even if the current working directory is not accessible. """ def check(result, ignored): self.assertEqual(result, 0) return self._defaultPathTest(utils.getProcessValue, check)
If no value is supplied for the C{path} parameter, L{getProcessValue} runs the given command in the same working directory as the parent process and succeeds even if the current working directory is not accessible.
test_getProcessValueDefaultPath
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iutils.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iutils.py
MIT
def test_getProcessOutputAndValueDefaultPath(self): """ If no value is supplied for the C{path} parameter, L{getProcessOutputAndValue} runs the given command in the same working directory as the parent process and succeeds even if the current working directory is not accessible. """ def check(out_err_status, dir): out, err, status = out_err_status self.assertEqual(out, dir) self.assertEqual(status, 0) return self._defaultPathTest( utils.getProcessOutputAndValue, check)
If no value is supplied for the C{path} parameter, L{getProcessOutputAndValue} runs the given command in the same working directory as the parent process and succeeds even if the current working directory is not accessible.
test_getProcessOutputAndValueDefaultPath
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iutils.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iutils.py
MIT
def test_get_processOutputAndValueStdin(self): """ Standard input can be made available to the child process by passing bytes for the `stdinBytes` parameter. """ scriptFile = self.makeSourceFile([ "import sys", "sys.stdout.write(sys.stdin.read())", ]) stdinBytes = b"These are the bytes to see." d = utils.getProcessOutputAndValue( self.exe, ['-u', scriptFile], stdinBytes=stdinBytes, ) def gotOutputAndValue(out_err_code): out, err, code = out_err_code # Avoid making an exact equality comparison in case there is extra # random output on stdout (warnings, stray print statements, # logging, who knows). self.assertIn(stdinBytes, out) self.assertEqual(0, code) d.addCallback(gotOutputAndValue) return d
Standard input can be made available to the child process by passing bytes for the `stdinBytes` parameter.
test_get_processOutputAndValueStdin
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iutils.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iutils.py
MIT
def test_suppressWarnings(self): """ L{utils.suppressWarnings} decorates a function so that the given warnings are suppressed. """ result = [] def showwarning(self, *a, **kw): result.append((a, kw)) self.patch(warnings, "showwarning", showwarning) def f(msg): warnings.warn(msg) g = utils.suppressWarnings(f, (('ignore',), dict(message="This is message"))) # Start off with a sanity check - calling the original function # should emit the warning. f("Sanity check message") self.assertEqual(len(result), 1) # Now that that's out of the way, call the wrapped function, and # make sure no new warnings show up. g("This is message") self.assertEqual(len(result), 1) # Finally, emit another warning which should not be ignored, and # make sure it is not. g("Unignored message") self.assertEqual(len(result), 2)
L{utils.suppressWarnings} decorates a function so that the given warnings are suppressed.
test_suppressWarnings
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iutils.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iutils.py
MIT
def test_deferredCallback(self): """ If the function called by L{utils.runWithWarningsSuppressed} returns a C{Deferred}, the warning filters aren't removed until the Deferred fires. """ filters = [(("ignore", ".*foo.*"), {}), (("ignore", ".*bar.*"), {})] result = Deferred() self.runWithWarningsSuppressed(filters, lambda: result) warnings.warn("ignore foo") result.callback(3) warnings.warn("ignore foo 2") self.assertEqual( ["ignore foo 2"], [w['message'] for w in self.flushWarnings()])
If the function called by L{utils.runWithWarningsSuppressed} returns a C{Deferred}, the warning filters aren't removed until the Deferred fires.
test_deferredCallback
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iutils.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iutils.py
MIT
def test_deferredErrback(self): """ If the function called by L{utils.runWithWarningsSuppressed} returns a C{Deferred}, the warning filters aren't removed until the Deferred fires with an errback. """ filters = [(("ignore", ".*foo.*"), {}), (("ignore", ".*bar.*"), {})] result = Deferred() d = self.runWithWarningsSuppressed(filters, lambda: result) warnings.warn("ignore foo") result.errback(ZeroDivisionError()) d.addErrback(lambda f: f.trap(ZeroDivisionError)) warnings.warn("ignore foo 2") self.assertEqual( ["ignore foo 2"], [w['message'] for w in self.flushWarnings()])
If the function called by L{utils.runWithWarningsSuppressed} returns a C{Deferred}, the warning filters aren't removed until the Deferred fires with an errback.
test_deferredErrback
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iutils.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iutils.py
MIT
def generateCertificateObjects(organization, organizationalUnit): """ Create a certificate for given C{organization} and C{organizationalUnit}. @return: a tuple of (key, request, certificate) objects. """ pkey = crypto.PKey() pkey.generate_key(crypto.TYPE_RSA, 1024) req = crypto.X509Req() subject = req.get_subject() subject.O = organization subject.OU = organizationalUnit req.set_pubkey(pkey) req.sign(pkey, "md5") # Here comes the actual certificate cert = crypto.X509() cert.set_serial_number(1) cert.gmtime_adj_notBefore(0) cert.gmtime_adj_notAfter(60) # Testing certificates need not be long lived cert.set_issuer(req.get_subject()) cert.set_subject(req.get_subject()) cert.set_pubkey(req.get_pubkey()) cert.sign(pkey, "md5") return pkey, req, cert
Create a certificate for given C{organization} and C{organizationalUnit}. @return: a tuple of (key, request, certificate) objects.
generateCertificateObjects
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_ssl.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_ssl.py
MIT
def generateCertificateFiles(basename, organization, organizationalUnit): """ Create certificate files key, req and cert prefixed by C{basename} for given C{organization} and C{organizationalUnit}. """ pkey, req, cert = generateCertificateObjects(organization, organizationalUnit) for ext, obj, dumpFunc in [ ('key', pkey, crypto.dump_privatekey), ('req', req, crypto.dump_certificate_request), ('cert', cert, crypto.dump_certificate)]: fName = os.extsep.join((basename, ext)).encode("utf-8") FilePath(fName).setContent(dumpFunc(crypto.FILETYPE_PEM, obj))
Create certificate files key, req and cert prefixed by C{basename} for given C{organization} and C{organizationalUnit}.
generateCertificateFiles
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_ssl.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_ssl.py
MIT
def createServer(self, address, portNumber, factory): """ Create an SSL server with a certificate using L{IReactorSSL.listenSSL}. """ cert = ssl.PrivateCertificate.loadPEM(FilePath(certPath).getContent()) contextFactory = cert.options() return reactor.listenSSL( portNumber, factory, contextFactory, interface=address)
Create an SSL server with a certificate using L{IReactorSSL.listenSSL}.
createServer
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_ssl.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_ssl.py
MIT
def connectClient(self, address, portNumber, clientCreator): """ Create an SSL client using L{IReactorSSL.connectSSL}. """ contextFactory = ssl.CertificateOptions() return clientCreator.connectSSL(address, portNumber, contextFactory)
Create an SSL client using L{IReactorSSL.connectSSL}.
connectClient
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_ssl.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_ssl.py
MIT
def getHandleExceptionType(self): """ Return L{OpenSSL.SSL.Error} as the expected error type which will be raised by a write to the L{OpenSSL.SSL.Connection} object after it has been closed. """ return SSL.Error
Return L{OpenSSL.SSL.Error} as the expected error type which will be raised by a write to the L{OpenSSL.SSL.Connection} object after it has been closed.
getHandleExceptionType
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_ssl.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_ssl.py
MIT
def getHandleErrorCodeMatcher(self): """ Return a L{hamcrest.core.matcher.Matcher} for the argument L{OpenSSL.SSL.Error} will be constructed with for this case. This is basically just a random OpenSSL implementation detail. It would be better if this test worked in a way which did not require this. """ # We expect an error about how we tried to write to a shutdown # connection. This is terribly implementation-specific. return hamcrest.contains( hamcrest.contains( hamcrest.equal_to('SSL routines'), hamcrest.any_of( hamcrest.equal_to('SSL_write'), hamcrest.equal_to('ssl_write_internal'), ), hamcrest.equal_to('protocol is shutdown'), ), )
Return a L{hamcrest.core.matcher.Matcher} for the argument L{OpenSSL.SSL.Error} will be constructed with for this case. This is basically just a random OpenSSL implementation detail. It would be better if this test worked in a way which did not require this.
getHandleErrorCodeMatcher
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_ssl.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_ssl.py
MIT
def _runTest(self, clientProto, serverProto, clientIsServer=False): """ Helper method to run TLS tests. @param clientProto: protocol instance attached to the client connection. @param serverProto: protocol instance attached to the server connection. @param clientIsServer: flag indicated if client should initiate startTLS instead of server. @return: a L{defer.Deferred} that will fire when both connections are lost. """ self.clientProto = clientProto cf = self.clientFactory = protocol.ClientFactory() cf.protocol = lambda: clientProto if clientIsServer: cf.server = False else: cf.client = True self.serverProto = serverProto sf = self.serverFactory = protocol.ServerFactory() sf.protocol = lambda: serverProto if clientIsServer: sf.client = False else: sf.server = True port = reactor.listenTCP(0, sf, interface="127.0.0.1") self.addCleanup(port.stopListening) reactor.connectTCP('127.0.0.1', port.getHost().port, cf) return defer.gatherResults([clientProto.deferred, serverProto.deferred])
Helper method to run TLS tests. @param clientProto: protocol instance attached to the client connection. @param serverProto: protocol instance attached to the server connection. @param clientIsServer: flag indicated if client should initiate startTLS instead of server. @return: a L{defer.Deferred} that will fire when both connections are lost.
_runTest
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_ssl.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_ssl.py
MIT
def test_TLS(self): """ Test for server and client startTLS: client should received data both before and after the startTLS. """ def check(ignore): self.assertEqual( self.serverFactory.lines, UnintelligentProtocol.pretext + UnintelligentProtocol.posttext ) d = self._runTest(UnintelligentProtocol(), LineCollector(True, self.fillBuffer)) return d.addCallback(check)
Test for server and client startTLS: client should received data both before and after the startTLS.
test_TLS
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_ssl.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_ssl.py
MIT
def test_unTLS(self): """ Test for server startTLS not followed by a startTLS in client: the data received after server startTLS should be received as raw. """ def check(ignored): self.assertEqual( self.serverFactory.lines, UnintelligentProtocol.pretext ) self.assertTrue(self.serverFactory.rawdata, "No encrypted bytes received") d = self._runTest(UnintelligentProtocol(), LineCollector(False, self.fillBuffer)) return d.addCallback(check)
Test for server startTLS not followed by a startTLS in client: the data received after server startTLS should be received as raw.
test_unTLS
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_ssl.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_ssl.py
MIT
def test_backwardsTLS(self): """ Test startTLS first initiated by client. """ def check(ignored): self.assertEqual( self.clientFactory.lines, UnintelligentProtocol.pretext + UnintelligentProtocol.posttext ) d = self._runTest(LineCollector(True, self.fillBuffer), UnintelligentProtocol(), True) return d.addCallback(check)
Test startTLS first initiated by client.
test_backwardsTLS
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_ssl.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_ssl.py
MIT
def test_bothSidesLoseConnection(self): """ Both sides of SSL connection close connection; the connections should close cleanly, and only after the underlying TCP connection has disconnected. """ @implementer(interfaces.IHandshakeListener) class CloseAfterHandshake(protocol.Protocol): gotData = False def __init__(self): self.done = defer.Deferred() def handshakeCompleted(self): self.transport.loseConnection() def connectionLost(self, reason): self.done.errback(reason) del self.done org = "twisted.test.test_ssl" self.setupServerAndClient( (org, org + ", client"), {}, (org, org + ", server"), {}) serverProtocol = CloseAfterHandshake() serverProtocolFactory = protocol.ServerFactory() serverProtocolFactory.protocol = lambda: serverProtocol serverPort = reactor.listenSSL(0, serverProtocolFactory, self.serverCtxFactory) self.addCleanup(serverPort.stopListening) clientProtocol = CloseAfterHandshake() clientProtocolFactory = protocol.ClientFactory() clientProtocolFactory.protocol = lambda: clientProtocol reactor.connectSSL('127.0.0.1', serverPort.getHost().port, clientProtocolFactory, self.clientCtxFactory) def checkResult(failure): failure.trap(ConnectionDone) return defer.gatherResults( [clientProtocol.done.addErrback(checkResult), serverProtocol.done.addErrback(checkResult)])
Both sides of SSL connection close connection; the connections should close cleanly, and only after the underlying TCP connection has disconnected.
test_bothSidesLoseConnection
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_ssl.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_ssl.py
MIT
def test_method(self): """ L{ssl.DefaultOpenSSLContextFactory.getContext} returns an SSL context which can use SSLv3 or TLSv1 but not SSLv2. """ # SSLv23_METHOD allows SSLv2, SSLv3, or TLSv1 self.assertEqual(self.context._method, SSL.SSLv23_METHOD) # And OP_NO_SSLv2 disables the SSLv2 support. self.assertEqual(self.context._options & SSL.OP_NO_SSLv2, SSL.OP_NO_SSLv2) # Make sure SSLv3 and TLSv1 aren't disabled though. self.assertFalse(self.context._options & SSL.OP_NO_SSLv3) self.assertFalse(self.context._options & SSL.OP_NO_TLSv1)
L{ssl.DefaultOpenSSLContextFactory.getContext} returns an SSL context which can use SSLv3 or TLSv1 but not SSLv2.
test_method
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_ssl.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_ssl.py
MIT
def test_missingCertificateFile(self): """ Instantiating L{ssl.DefaultOpenSSLContextFactory} with a certificate filename which does not identify an existing file results in the initializer raising L{OpenSSL.SSL.Error}. """ self.assertRaises( SSL.Error, ssl.DefaultOpenSSLContextFactory, certPath, self.mktemp())
Instantiating L{ssl.DefaultOpenSSLContextFactory} with a certificate filename which does not identify an existing file results in the initializer raising L{OpenSSL.SSL.Error}.
test_missingCertificateFile
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_ssl.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_ssl.py
MIT
def test_missingPrivateKeyFile(self): """ Instantiating L{ssl.DefaultOpenSSLContextFactory} with a private key filename which does not identify an existing file results in the initializer raising L{OpenSSL.SSL.Error}. """ self.assertRaises( SSL.Error, ssl.DefaultOpenSSLContextFactory, self.mktemp(), certPath)
Instantiating L{ssl.DefaultOpenSSLContextFactory} with a private key filename which does not identify an existing file results in the initializer raising L{OpenSSL.SSL.Error}.
test_missingPrivateKeyFile
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_ssl.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_ssl.py
MIT
def test_method(self): """ L{ssl.ClientContextFactory.getContext} returns a context which can use SSLv3 or TLSv1 but not SSLv2. """ self.assertEqual(self.context._method, SSL.SSLv23_METHOD) self.assertEqual(self.context._options & SSL.OP_NO_SSLv2, SSL.OP_NO_SSLv2) self.assertFalse(self.context._options & SSL.OP_NO_SSLv3) self.assertFalse(self.context._options & SSL.OP_NO_TLSv1)
L{ssl.ClientContextFactory.getContext} returns a context which can use SSLv3 or TLSv1 but not SSLv2.
test_method
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_ssl.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_ssl.py
MIT
def __repr__(self): """ Custom repr for testing to avoid coupling amp tests with repr from L{Protocol} Returns a string which contains a unique identifier that can be looked up using the instanceId property:: <TestProto #3> """ return "<TestProto #%d>" % (self.instanceId,)
Custom repr for testing to avoid coupling amp tests with repr from L{Protocol} Returns a string which contains a unique identifier that can be looked up using the instanceId property:: <TestProto #3>
__repr__
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 badResponder(self, hello, From, optional=None, Print=None, mixedCase=None, dash_arg=None, underscore_arg=None): """ This responder does nothing and forgets to return a dictionary. """
This responder does nothing and forgets to return a dictionary.
badResponder
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 connectedServerAndClient(ServerClass=SimpleSymmetricProtocol, ClientClass=SimpleSymmetricProtocol, *a, **kw): """Returns a 3-tuple: (client, server, pump) """ return iosim.connectedServerAndClient( ServerClass, ClientClass, *a, **kw)
Returns a 3-tuple: (client, server, pump)
connectedServerAndClient
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_serializeStr(self): """ Make sure that strs serialize to strs. """ a = amp.AmpBox(key=b'value') self.assertEqual(type(a.serialize()), bytes)
Make sure that strs serialize to strs.
test_serializeStr
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_serializeUnicodeKeyRaises(self): """ Verify that TypeError is raised when trying to serialize Unicode keys. """ a = amp.AmpBox(**{u'key': 'value'}) self.assertRaises(TypeError, a.serialize)
Verify that TypeError is raised when trying to serialize Unicode keys.
test_serializeUnicodeKeyRaises
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_serializeUnicodeValueRaises(self): """ Verify that TypeError is raised when trying to serialize Unicode values. """ a = amp.AmpBox(key=u'value') self.assertRaises(TypeError, a.serialize)
Verify that TypeError is raised when trying to serialize Unicode values.
test_serializeUnicodeValueRaises
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_booleanValues(self): """ Verify that the Boolean parser parses 'True' and 'False', but nothing else. """ b = amp.Boolean() self.assertTrue(b.fromString(b"True")) self.assertFalse(b.fromString(b"False")) self.assertRaises(TypeError, b.fromString, b"ninja") self.assertRaises(TypeError, b.fromString, b"true") self.assertRaises(TypeError, b.fromString, b"TRUE") self.assertEqual(b.toString(True), b'True') self.assertEqual(b.toString(False), b'False')
Verify that the Boolean parser parses 'True' and 'False', but nothing else.
test_booleanValues
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_pathValueRoundTrip(self): """ Verify the 'Path' argument can parse and emit a file path. """ fp = filepath.FilePath(self.mktemp()) p = amp.Path() s = p.toString(fp) v = p.fromString(s) self.assertIsNot(fp, v) # sanity check self.assertEqual(fp, v)
Verify the 'Path' argument can parse and emit a file path.
test_pathValueRoundTrip
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_sillyEmptyThing(self): """ Test that empty boxes raise an error; they aren't supposed to be sent on purpose. """ a = amp.AMP() return self.assertRaises(amp.NoEmptyBoxes, a.ampBoxReceived, amp.Box())
Test that empty boxes raise an error; they aren't supposed to be sent on purpose.
test_sillyEmptyThing
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_ParsingRoundTrip(self): """ Verify that various kinds of data make it through the encode/parse round-trip unharmed. """ c, s, p = connectedServerAndClient(ClientClass=LiteralAmp, ServerClass=LiteralAmp) SIMPLE = (b'simple', b'test') CE = (b'ceq', b': ') CR = (b'crtest', b'test\r') LF = (b'lftest', b'hello\n') NEWLINE = (b'newline', b'test\r\none\r\ntwo') NEWLINE2 = (b'newline2', b'test\r\none\r\n two') BODYTEST = (b'body', b'blah\r\n\r\ntesttest') testData = [ [SIMPLE], [SIMPLE, BODYTEST], [SIMPLE, CE], [SIMPLE, CR], [SIMPLE, CE, CR, LF], [CE, CR, LF], [SIMPLE, NEWLINE, CE, NEWLINE2], [BODYTEST, SIMPLE, NEWLINE] ] for test in testData: jb = amp.Box() jb.update(dict(test)) jb._sendTo(c) p.flush() self.assertEqual(s.boxes[-1], jb)
Verify that various kinds of data make it through the encode/parse round-trip unharmed.
test_ParsingRoundTrip
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): """ Remember the given keyword arguments as a set of responders. """ self.commands = {}
Remember the given keyword arguments as a set of responders.
__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 locateResponder(self, commandName): """ Look up and return a function passed as a keyword argument of the given name to the constructor. """ return self.commands[commandName]
Look up and return a function passed as a keyword argument of the given name to the constructor.
locateResponder
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): """ Create a fake sender and initialize the list of received boxes and unhandled errors. """ self.sentBoxes = [] self.unhandledErrors = [] self.expectedErrors = 0
Create a fake sender and initialize the list of received boxes and unhandled errors.
__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 expectError(self): """ Expect one error, so that the test doesn't fail. """ self.expectedErrors += 1
Expect one error, so that the test doesn't fail.
expectError
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 sendBox(self, box): """ Accept a box, but don't do anything. """ self.sentBoxes.append(box)
Accept a box, but don't do anything.
sendBox
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py
MIT
def unhandledError(self, failure): """ Deal with failures by instantly re-raising them for easier debugging. """ self.expectedErrors -= 1 if self.expectedErrors < 0: failure.raiseException() else: self.unhandledErrors.append(failure)
Deal with failures by instantly re-raising them for easier debugging.
unhandledError
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py
MIT
def setUp(self): """ Create a dispatcher to use. """ self.locator = FakeLocator() self.sender = FakeSender() self.dispatcher = amp.BoxDispatcher(self.locator) self.dispatcher.startReceivingBoxes(self.sender)
Create a dispatcher to use.
setUp
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_amp.py
MIT
def test_receivedAsk(self): """ L{CommandDispatcher.ampBoxReceived} should locate the appropriate command in its responder lookup, based on the '_ask' key. """ received = [] def thunk(box): received.append(box) return amp.Box({"hello": "goodbye"}) input = amp.Box(_command="hello", _ask="test-command-id", hello="world") self.locator.commands['hello'] = thunk self.dispatcher.ampBoxReceived(input) self.assertEqual(received, [input])
L{CommandDispatcher.ampBoxReceived} should locate the appropriate command in its responder lookup, based on the '_ask' key.
test_receivedAsk
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_sendUnhandledError(self): """ L{CommandDispatcher} should relay its unhandled errors in responding to boxes to its boxSender. """ err = RuntimeError("something went wrong, oh no") self.sender.expectError() self.dispatcher.unhandledError(Failure(err)) self.assertEqual(len(self.sender.unhandledErrors), 1) self.assertEqual(self.sender.unhandledErrors[0].value, err)
L{CommandDispatcher} should relay its unhandled errors in responding to boxes to its boxSender.
test_sendUnhandledError
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_unhandledSerializationError(self): """ Errors during serialization ought to be relayed to the sender's unhandledError method. """ err = RuntimeError("something undefined went wrong") def thunk(result): class BrokenBox(amp.Box): def _sendTo(self, proto): raise err return BrokenBox() self.locator.commands['hello'] = thunk input = amp.Box(_command="hello", _ask="test-command-id", hello="world") self.sender.expectError() self.dispatcher.ampBoxReceived(input) self.assertEqual(len(self.sender.unhandledErrors), 1) self.assertEqual(self.sender.unhandledErrors[0].value, err)
Errors during serialization ought to be relayed to the sender's unhandledError method.
test_unhandledSerializationError
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_callRemote(self): """ L{CommandDispatcher.callRemote} should emit a properly formatted '_ask' box to its boxSender and record an outstanding L{Deferred}. When a corresponding '_answer' packet is received, the L{Deferred} should be fired, and the results translated via the given L{Command}'s response de-serialization. """ D = self.dispatcher.callRemote(Hello, hello=b'world') self.assertEqual(self.sender.sentBoxes, [amp.AmpBox(_command=b"hello", _ask=b"1", hello=b"world")]) answers = [] D.addCallback(answers.append) self.assertEqual(answers, []) self.dispatcher.ampBoxReceived(amp.AmpBox({b'hello': b"yay", b'print': b"ignored", b'_answer': b"1"})) self.assertEqual(answers, [dict(hello=b"yay", Print=u"ignored")])
L{CommandDispatcher.callRemote} should emit a properly formatted '_ask' box to its boxSender and record an outstanding L{Deferred}. When a corresponding '_answer' packet is received, the L{Deferred} should be fired, and the results translated via the given L{Command}'s response de-serialization.
test_callRemote
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 _localCallbackErrorLoggingTest(self, callResult): """ Verify that C{callResult} completes with a L{None} result and that an unhandled error has been logged. """ finalResult = [] callResult.addBoth(finalResult.append) self.assertEqual(1, len(self.sender.unhandledErrors)) self.assertIsInstance( self.sender.unhandledErrors[0].value, ZeroDivisionError) self.assertEqual([None], finalResult)
Verify that C{callResult} completes with a L{None} result and that an unhandled error has been logged.
_localCallbackErrorLoggingTest
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_callRemoteSuccessLocalCallbackErrorLogging(self): """ If the last callback on the L{Deferred} returned by C{callRemote} (added by application code calling C{callRemote}) fails, the failure is passed to the sender's C{unhandledError} method. """ self.sender.expectError() callResult = self.dispatcher.callRemote(Hello, hello=b'world') callResult.addCallback(lambda result: 1 // 0) self.dispatcher.ampBoxReceived(amp.AmpBox({ b'hello': b"yay", b'print': b"ignored", b'_answer': b"1"})) self._localCallbackErrorLoggingTest(callResult)
If the last callback on the L{Deferred} returned by C{callRemote} (added by application code calling C{callRemote}) fails, the failure is passed to the sender's C{unhandledError} method.
test_callRemoteSuccessLocalCallbackErrorLogging
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_callRemoteErrorLocalCallbackErrorLogging(self): """ Like L{test_callRemoteSuccessLocalCallbackErrorLogging}, but for the case where the L{Deferred} returned by C{callRemote} fails. """ self.sender.expectError() callResult = self.dispatcher.callRemote(Hello, hello=b'world') callResult.addErrback(lambda result: 1 // 0) self.dispatcher.ampBoxReceived(amp.AmpBox({ b'_error': b'1', b'_error_code': b'bugs', b'_error_description': b'stuff'})) self._localCallbackErrorLoggingTest(callResult)
Like L{test_callRemoteSuccessLocalCallbackErrorLogging}, but for the case where the L{Deferred} returned by C{callRemote} fails.
test_callRemoteErrorLocalCallbackErrorLogging
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 greetingResponder(self, greeting, cookie): """ Return a different cookieplus than L{TestLocator.greetingResponder}. """ self.greetings.append((greeting, cookie)) return dict(cookieplus=cookie + 4)
Return a different cookieplus than L{TestLocator.greetingResponder}.
greetingResponder
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 lookupFunction(self, name): """ Override the deprecated lookupFunction function. """ if name in self.expectations: result = self.expectations[name] return result else: return super(OverrideLocatorAMP, self).lookupFunction(name)
Override the deprecated lookupFunction function.
lookupFunction
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