desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Ensure that the given "actual" string ends with "exp_end"'
def assertEndsWith(self, actual, exp_end):
self.assertTrue(actual.endswith(exp_end), msg=('%r did not end with %r' % (actual, exp_end)))
'Verify the pretty-printing of various "int" values'
def test_int(self):
self.assertGdbRepr(42) self.assertGdbRepr(0) self.assertGdbRepr((-7)) self.assertGdbRepr(sys.maxint) self.assertGdbRepr((- sys.maxint))
'Verify the pretty-printing of various "long" values'
def test_long(self):
self.assertGdbRepr(0L) self.assertGdbRepr(1000000000000L) self.assertGdbRepr((-1L)) self.assertGdbRepr((-1000000000000000L))
'Verify the pretty-printing of True, False and None'
def test_singletons(self):
self.assertGdbRepr(True) self.assertGdbRepr(False) self.assertGdbRepr(None)
'Verify the pretty-printing of dictionaries'
def test_dicts(self):
self.assertGdbRepr({}) self.assertGdbRepr({'foo': 'bar'}) self.assertGdbRepr({'foo': 'bar', 'douglas': 42})
'Verify the pretty-printing of lists'
def test_lists(self):
self.assertGdbRepr([]) self.assertGdbRepr(range(5))
'Verify the pretty-printing of strings'
def test_strings(self):
self.assertGdbRepr('') self.assertGdbRepr('And now for something hopefully the same') self.assertGdbRepr('string with embedded NUL here \x00 and then some more text') self.assertGdbRepr('this is byte 255:\xff and byte 128:\x80')
'Verify the pretty-printing of tuples'
def test_tuples(self):
self.assertGdbRepr(tuple()) self.assertGdbRepr((1,)) self.assertGdbRepr(('foo', 'bar', 'baz'))
'Verify the pretty-printing of unicode values'
def test_unicode(self):
self.assertGdbRepr(u'') self.assertGdbRepr(u'hello world') self.assertGdbRepr(u'\u2620') self.assertGdbRepr(u'\u6587\u5b57\u5316\u3051') self.assertGdbRepr(u'\U0001d121')
'Verify the pretty-printing of sets'
def test_sets(self):
self.assertGdbRepr(set()) self.assertGdbRepr(set(['a', 'b'])) self.assertGdbRepr(set([4, 5, 6])) (gdb_repr, gdb_output) = self.get_gdb_repr("s = set(['a','b'])\ns.pop()\nprint s") self.assertEqual(gdb_repr, "set(['b'])")
'Verify the pretty-printing of frozensets'
def test_frozensets(self):
self.assertGdbRepr(frozenset()) self.assertGdbRepr(frozenset(['a', 'b'])) self.assertGdbRepr(frozenset([4, 5, 6]))
'Verify the pretty-printing of classic class instances'
def test_classic_class(self):
(gdb_repr, gdb_output) = self.get_gdb_repr('\nclass Foo:\n pass\nfoo = Foo()\nfoo.an_int = 42\nprint foo') m = re.match('<Foo\\(an_int=42\\) at remote 0x[0-9a-f]+>', gdb_repr) self.assertTrue(m, msg=('Unexpected classic-class rendering %r' % gdb_repr))
'Verify the pretty-printing of new-style class instances'
def test_modern_class(self):
(gdb_repr, gdb_output) = self.get_gdb_repr('\nclass Foo(object):\n pass\nfoo = Foo()\nfoo.an_int = 42\nprint foo') m = re.match('<Foo\\(an_int=42\\) at remote 0x[0-9a-f]+>', gdb_repr) self.assertTrue(m, msg=('Unexpected new-style class rendering %r' % gdb_repr))
'Verify the pretty-printing of an instance of a list subclass'
def test_subclassing_list(self):
(gdb_repr, gdb_output) = self.get_gdb_repr('\nclass Foo(list):\n pass\nfoo = Foo()\nfoo += [1, 2, 3]\nfoo.an_int = 42\nprint foo') m = re.match('<Foo\\(an_int=42\\) at remote 0x[0-9a-f]+>', gdb_repr) self.assertTrue(m, msg=('Unexpected new-style class rendering %r' % gdb_repr))
'Verify the pretty-printing of an instance of a tuple subclass'
def test_subclassing_tuple(self):
(gdb_repr, gdb_output) = self.get_gdb_repr('\nclass Foo(tuple):\n pass\nfoo = Foo((1, 2, 3))\nfoo.an_int = 42\nprint foo') m = re.match('<Foo\\(an_int=42\\) at remote 0x[0-9a-f]+>', gdb_repr) self.assertTrue(m, msg=('Unexpected new-style class rendering %r' % gdb_repr))
'Run Python under gdb, corrupting variables in the inferior process immediately before taking a backtrace. Verify that the variable\'s representation is the expected failsafe representation'
def assertSane(self, source, corruption, expvalue=None, exptype=None):
if corruption: cmds_after_breakpoint = [corruption, 'backtrace'] else: cmds_after_breakpoint = ['backtrace'] (gdb_repr, gdb_output) = self.get_gdb_repr(source, cmds_after_breakpoint=cmds_after_breakpoint) if expvalue: if (gdb_repr == repr(expvalue)): return if exptype: pattern = (('<' + exptype) + ' at remote 0x[0-9a-f]+>') else: pattern = '<.* at remote 0x[0-9a-f]+>' m = re.match(pattern, gdb_repr) if (not m): self.fail(('Unexpected gdb representation: %r\n%s' % (gdb_repr, gdb_output)))
'Ensure that a NULL PyObject* is handled gracefully'
def test_NULL_ptr(self):
(gdb_repr, gdb_output) = self.get_gdb_repr('print 42', cmds_after_breakpoint=['set variable op=0', 'backtrace']) self.assertEqual(gdb_repr, '0x0')
'Ensure that a PyObject* with NULL ob_type is handled gracefully'
def test_NULL_ob_type(self):
self.assertSane('print 42', 'set op->ob_type=0')
'Ensure that a PyObject* with a corrupt ob_type is handled gracefully'
def test_corrupt_ob_type(self):
self.assertSane('print 42', 'set op->ob_type=0xDEADBEEF', expvalue=42)
'Ensure that a PyObject* with a type with corrupt tp_flags is handled'
def test_corrupt_tp_flags(self):
self.assertSane('print 42', 'set op->ob_type->tp_flags=0x0', expvalue=42)
'Ensure that a PyObject* with a type with corrupt tp_name is handled'
def test_corrupt_tp_name(self):
self.assertSane('print 42', 'set op->ob_type->tp_name=0xDEADBEEF', expvalue=42)
'Ensure that a PyInstanceObject with with a NULL in_dict is handled'
def test_NULL_instance_dict(self):
self.assertSane('\nclass Foo:\n pass\nfoo = Foo()\nfoo.an_int = 42\nprint foo', 'set ((PyInstanceObject*)op)->in_dict = 0', exptype='Foo')
'Ensure that the new-style class _Helper in site.py can be handled'
def test_builtins_help(self):
(gdb_repr, gdb_output) = self.get_gdb_repr('print __builtins__.help', import_site=True) m = re.match('<_Helper at remote 0x[0-9a-f]+>', gdb_repr) self.assertTrue(m, msg=('Unexpected rendering %r' % gdb_repr))
'Ensure that a reference loop involving a list doesn\'t lead proxyval into an infinite loop:'
def test_selfreferential_list(self):
(gdb_repr, gdb_output) = self.get_gdb_repr('a = [3, 4, 5] ; a.append(a) ; print a') self.assertEqual(gdb_repr, '[3, 4, 5, [...]]') (gdb_repr, gdb_output) = self.get_gdb_repr('a = [3, 4, 5] ; b = [a] ; a.append(b) ; print a') self.assertEqual(gdb_repr, '[3, 4, 5, [[...]]]')
'Ensure that a reference loop involving a dict doesn\'t lead proxyval into an infinite loop:'
def test_selfreferential_dict(self):
(gdb_repr, gdb_output) = self.get_gdb_repr("a = {} ; b = {'bar':a} ; a['foo'] = b ; print a") self.assertEqual(gdb_repr, "{'foo': {'bar': {...}}}")
'Verify that very long output is truncated'
def test_truncation(self):
(gdb_repr, gdb_output) = self.get_gdb_repr('print range(1000)') self.assertEqual(gdb_repr, '[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226...(truncated)') self.assertEqual(len(gdb_repr), (1024 + len('...(truncated)')))
'Verify that the "py-list" command works'
def test_basic_command(self):
bt = self.get_stack_trace(script=self.get_sample_script(), cmds_after_breakpoint=['py-list']) self.assertListing(' 5 \n 6 def bar(a, b, c):\n 7 baz(a, b, c)\n 8 \n 9 def baz(*args):\n >10 print(42)\n 11 \n 12 foo(1, 2, 3)\n', bt)
'Verify the "py-list" command with one absolute argument'
def test_one_abs_arg(self):
bt = self.get_stack_trace(script=self.get_sample_script(), cmds_after_breakpoint=['py-list 9']) self.assertListing(' 9 def baz(*args):\n >10 print(42)\n 11 \n 12 foo(1, 2, 3)\n', bt)
'Verify the "py-list" command with two absolute arguments'
def test_two_abs_args(self):
bt = self.get_stack_trace(script=self.get_sample_script(), cmds_after_breakpoint=['py-list 1,3']) self.assertListing(' 1 # Sample script for use by test_gdb.py\n 2 \n 3 def foo(a, b, c):\n', bt)
'Verify that the "py-up" command works'
@unittest.skipUnless(HAS_PYUP_PYDOWN, 'test requires py-up/py-down commands') def test_pyup_command(self):
bt = self.get_stack_trace(script=self.get_sample_script(), cmds_after_breakpoint=['py-up']) self.assertMultilineMatches(bt, '^.*\n#[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 7, in bar \\(a=1, b=2, c=3\\)\n baz\\(a, b, c\\)\n$')
'Verify handling of "py-down" at the bottom of the stack'
@unittest.skipUnless(HAS_PYUP_PYDOWN, 'test requires py-up/py-down commands') def test_down_at_bottom(self):
bt = self.get_stack_trace(script=self.get_sample_script(), cmds_after_breakpoint=['py-down']) self.assertEndsWith(bt, 'Unable to find a newer python frame\n')
'Verify handling of "py-up" at the top of the stack'
@unittest.skipUnless(HAS_PYUP_PYDOWN, 'test requires py-up/py-down commands') def test_up_at_top(self):
bt = self.get_stack_trace(script=self.get_sample_script(), cmds_after_breakpoint=(['py-up'] * 4)) self.assertEndsWith(bt, 'Unable to find an older python frame\n')
'Verify "py-up" followed by "py-down"'
@unittest.skipUnless(HAS_PYUP_PYDOWN, 'test requires py-up/py-down commands') def test_up_then_down(self):
bt = self.get_stack_trace(script=self.get_sample_script(), cmds_after_breakpoint=['py-up', 'py-down']) self.assertMultilineMatches(bt, '^.*\n#[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 7, in bar \\(a=1, b=2, c=3\\)\n baz\\(a, b, c\\)\n#[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 10, in baz \\(args=\\(1, 2, 3\\)\\)\n print\\(42\\)\n$')
'Verify that the "py-bt" command works'
def test_basic_command(self):
bt = self.get_stack_trace(script=self.get_sample_script(), cmds_after_breakpoint=['py-bt']) self.assertMultilineMatches(bt, '^.*\n#[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 7, in bar \\(a=1, b=2, c=3\\)\n baz\\(a, b, c\\)\n#[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 4, in foo \\(a=1, b=2, c=3\\)\n bar\\(a, b, c\\)\n#[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 12, in <module> \\(\\)\nfoo\\(1, 2, 3\\)\n')
'Verify that the "py-print" command works'
def test_basic_command(self):
bt = self.get_stack_trace(script=self.get_sample_script(), cmds_after_breakpoint=['py-print args']) self.assertMultilineMatches(bt, ".*\\nlocal 'args' = \\(1, 2, 3\\)\\n.*")
'Return a dictionary of values which are invariant by storage in the object under test.'
def _reference(self):
return {1: 2, 'key1': 'value1', 'key2': (1, 2, 3)}
'Return an empty mapping object'
def _empty_mapping(self):
return self.type2test()
'Return a mapping object with the value contained in data dictionary'
def _full_mapping(self, data):
x = self._empty_mapping() for (key, value) in data.items(): x[key] = value return x
'If type_ is a subclass of self.exc and value has attributes matching self.attrs, raise ResourceDenied. Otherwise let the exception propagate (if any).'
def __exit__(self, type_=None, value=None, traceback=None):
if ((type_ is not None) and issubclass(self.exc, type_)): for (attr, attr_value) in self.attrs.iteritems(): if (not hasattr(value, attr)): break if (getattr(value, attr) != attr_value): break else: raise ResourceDenied('an optional resource is not available')
'Make sure that raising \'object_\' triggers a TypeError.'
def raise_fails(self, object_):
try: raise object_ except TypeError: return self.fail(('TypeError expected for raising %s' % type(object_)))
'Catching \'object_\' should raise a TypeError.'
def catch_fails(self, object_):
try: try: raise StandardError except object_: pass except TypeError: pass except StandardError: self.fail(('TypeError expected when catching %s' % type(object_))) try: try: raise StandardError except (object_,): pass except TypeError: return except StandardError: self.fail(('TypeError expected when catching %s as specified in a tuple' % type(object_)))
'test issue1202 compliance: signed crc32, adler32 in 2.x'
def test_abcdefghijklmnop(self):
foo = 'abcdefghijklmnop' self.assertEqual(zlib.crc32(foo), (-1808088941)) self.assertEqual(zlib.crc32('spam'), 1138425661) self.assertEqual(zlib.adler32((foo + foo)), (-721416943)) self.assertEqual(zlib.adler32('spam'), 72286642)
'Verify that the result of a/b is correctly rounded, by comparing it with a pure Python implementation of correctly rounded division. b should be nonzero.'
def check_truediv(self, a, b, skip_small=True):
(a, b) = (long(a), long(b)) if (skip_small and (max(abs(a), abs(b)) < (2 ** DBL_MANT_DIG))): return try: expected = repr(truediv(a, b)) except OverflowError: expected = 'overflow' except ZeroDivisionError: expected = 'zerodivision' try: got = repr((a / b)) except OverflowError: got = 'overflow' except ZeroDivisionError: got = 'zerodivision' self.assertEqual(expected, got, 'Incorrectly rounded division {}/{}: expected {}, got {}'.format(a, b, expected, got))
'BaseClass.getter'
@property def spam(self):
return self._spam
'SubClass.getter'
@BaseClass.spam.getter def spam(self):
raise PropertyGet(self._spam)
'The decorator does not use this doc string'
@PropertyDocBase.spam.getter def spam(self):
return self._spam
'new docstring'
@BaseClass.spam.getter def spam(self):
return 5
'original docstring'
@property def spam(self):
return 1
'new docstring'
@spam.getter def spam(self):
return 8
'Create time tuple based on current time.'
def setUp(self):
self.time_tuple = time.localtime() self.LT_ins = _strptime.LocaleTime()
'Helper method that tests testing against directive based on the tuple_position of time_tuple. Uses error_msg as error message.'
def compare_against_time(self, testing, directive, tuple_position, error_msg):
strftime_output = time.strftime(directive, self.time_tuple).lower() comparison = testing[self.time_tuple[tuple_position]] self.assertIn(strftime_output, testing, ('%s: not found in tuple' % error_msg)) self.assertTrue((comparison == strftime_output), ('%s: position within tuple incorrect; %s != %s' % (error_msg, comparison, strftime_output)))
'Construct generic TimeRE object.'
def setUp(self):
self.time_re = _strptime.TimeRE() self.locale_time = _strptime.LocaleTime()
'Create testing time tuple.'
def setUp(self):
self.time_tuple = time.gmtime()
'Helper fxn in testing.'
def helper(self, directive, position):
strf_output = time.strftime(('%' + directive), self.time_tuple) strp_output = _strptime._strptime_time(strf_output, ('%' + directive)) self.assertTrue((strp_output[position] == self.time_tuple[position]), ("testing of '%s' directive failed; '%s' -> %s != %s" % (directive, strf_output, strp_output[position], self.time_tuple[position])))
'Asserts that both the types and values are the same.'
def assertTypedEquals(self, expected, actual):
self.assertEqual(type(expected), type(actual)) self.assertEqual(expected, actual)
'Asserts that callable(*args, **kwargs) raises exc_type(message).'
def assertRaisesMessage(self, exc_type, message, callable, *args, **kwargs):
try: callable(*args, **kwargs) except exc_type as e: self.assertEqual(message, str(e)) else: self.fail(('%s not raised' % exc_type.__name__))
'Test an empty maildir mailbox'
def test_empty_maildir(self):
self.mbox = mailbox.Maildir(test_support.TESTFN) self.assertTrue((len(self.mbox) == 0)) self.assertTrue((self.mbox.next() is None)) self.assertTrue((self.mbox.next() is None))
'Check that compileall recreates bytecode when the new metadata is used.'
def recreation_check(self, metadata):
if (not hasattr(os, 'stat')): return py_compile.compile(self.source_path) self.assertEqual(*self.data()) with open(self.bc_path, 'rb') as file: bc = file.read()[len(metadata):] with open(self.bc_path, 'wb') as file: file.write(metadata) file.write(bc) self.assertNotEqual(*self.data()) compileall.compile_dir(self.directory, force=False, quiet=True) self.assertTrue(*self.data())
'Setup the default logging stream to an internal StringIO instance, so that we can examine log output as we want.'
def setUp(self):
logger_dict = logging.getLogger().manager.loggerDict logging._acquireLock() try: self.saved_handlers = logging._handlers.copy() self.saved_handler_list = logging._handlerList[:] self.saved_loggers = logger_dict.copy() self.saved_level_names = logging._levelNames.copy() finally: logging._releaseLock() logging.getLogger('\xab\xd7\xbb') logging.getLogger(u'\u013f\xd6G') self.root_logger = logging.getLogger('') self.original_logging_level = self.root_logger.getEffectiveLevel() self.stream = cStringIO.StringIO() self.root_logger.setLevel(logging.DEBUG) self.root_hdlr = logging.StreamHandler(self.stream) self.root_formatter = logging.Formatter(self.log_format) self.root_hdlr.setFormatter(self.root_formatter) self.root_logger.addHandler(self.root_hdlr)
'Remove our logging stream, and restore the original logging level.'
def tearDown(self):
self.stream.close() self.root_logger.removeHandler(self.root_hdlr) while self.root_logger.handlers: h = self.root_logger.handlers[0] self.root_logger.removeHandler(h) h.close() self.root_logger.setLevel(self.original_logging_level) logging._acquireLock() try: logging._levelNames.clear() logging._levelNames.update(self.saved_level_names) logging._handlers.clear() logging._handlers.update(self.saved_handlers) logging._handlerList[:] = self.saved_handler_list loggerDict = logging.getLogger().manager.loggerDict loggerDict.clear() loggerDict.update(self.saved_loggers) finally: logging._releaseLock()
'Match the collected log lines against the regular expression self.expected_log_pat, and compare the extracted group values to the expected_values list of tuples.'
def assert_log_lines(self, expected_values, stream=None):
stream = (stream or self.stream) pat = re.compile(self.expected_log_pat) try: stream.reset() actual_lines = stream.readlines() except AttributeError: actual_lines = stream.getvalue().splitlines() self.assertEqual(len(actual_lines), len(expected_values)) for (actual, expected) in zip(actual_lines, expected_values): match = pat.search(actual) if (not match): self.fail(('Log line does not match expected pattern:\n' + actual)) self.assertEqual(tuple(match.groups()), expected) s = stream.read() if s: self.fail(('Remaining output at end of log stream:\n' + s))
'Generate a message consisting solely of an auto-incrementing integer.'
def next_message(self):
self.message_num += 1 return ('%d' % self.message_num)
'Handle multiple requests - each expected to be of 4-byte length, followed by the LogRecord in pickle format. Logs the record according to whatever policy is configured locally.'
def handle(self):
while True: chunk = self.connection.recv(4) if (len(chunk) < 4): break slen = struct.unpack('>L', chunk)[0] chunk = self.connection.recv(slen) while (len(chunk) < slen): chunk = (chunk + self.connection.recv((slen - len(chunk)))) obj = self.unpickle(chunk) record = logging.makeLogRecord(obj) self.handle_log_record(record)
'Set up a TCP server to receive log messages, and a SocketHandler pointing to that server\'s address and port.'
def setUp(self):
BaseTest.setUp(self) self.tcpserver = LogRecordSocketReceiver(port=0) self.port = self.tcpserver.socket.getsockname()[1] self.threads = [threading.Thread(target=self.tcpserver.serve_until_stopped)] for thread in self.threads: thread.start() self.sock_hdlr = logging.handlers.SocketHandler('localhost', self.port) self.sock_hdlr.setFormatter(self.root_formatter) self.root_logger.removeHandler(self.root_logger.handlers[0]) self.root_logger.addHandler(self.sock_hdlr)
'Shutdown the TCP server.'
def tearDown(self):
try: self.tcpserver.abort = True del self.tcpserver self.root_logger.removeHandler(self.sock_hdlr) self.sock_hdlr.close() for thread in self.threads: thread.join(2.0) finally: BaseTest.tearDown(self)
'Get the log output as received by the TCP server.'
def get_output(self):
self.root_logger.critical(LogRecordStreamHandler.TCP_LOG_END) self.tcpserver.finished.wait(2.0) return self.tcpserver.log_output
'Create a dict to remember potentially destroyed objects.'
def setUp(self):
BaseTest.setUp(self) self._survivors = {}
'Watch the given objects for survival, by creating weakrefs to them.'
def _watch_for_survival(self, *args):
for obj in args: key = (id(obj), repr(obj)) self._survivors[key] = weakref.ref(obj)
'Assert that all objects watched for survival have survived.'
def _assertTruesurvival(self):
gc.collect() dead = [] for ((id_, repr_), ref) in self._survivors.items(): if (ref() is None): dead.append(repr_) if dead: self.fail(('%d objects should have survived but have been destroyed: %s' % (len(dead), ', '.join(dead))))
'Another docstring containing tabs'
def abuse(self, a, b, c):
self.argue(a, b, c)
'Test that lambda functionality stays the same. The output produced currently is, I suspect invalid because of the unencoded brackets in the HTML, "<lambda>". The subtraction lambda method is tested.'
def test_lambda(self):
self.client.request('GET', '/') response = self.client.getresponse() self.assertIn('<dl><dt><a name="-&lt;lambda&gt;"><strong>&lt;lambda&gt;</strong></a>(x, y)</dt></dl>', response.read())
'Test that the server correctly automatically wraps references to PEPS and RFCs with links, and that it linkifies text starting with http or ftp protocol prefixes. The documentation for the "add" method contains the test material.'
@make_request_and_skipIf((sys.flags.optimize >= 2), 'Docstrings are omitted with -O2 and above') def test_autolinking(self):
self.client.request('GET', '/') response = self.client.getresponse() self.assertIn('<dl><dt><a name="-add"><strong>add</strong></a>(x, y)</dt><dd><tt>Add&nbsp;two&nbsp;instances&nbsp;together.&nbsp;This&nbsp;follows&nbsp;<a href="http://www.python.org/dev/peps/pep-0008/">PEP008</a>,&nbsp;but&nbsp;has&nbsp;nothing<br>\nto&nbsp;do&nbsp;with&nbsp;<a href="http://www.rfc-editor.org/rfc/rfc1952.txt">RFC1952</a>.&nbsp;Case&nbsp;should&nbsp;matter:&nbsp;pEp008&nbsp;and&nbsp;rFC1952.&nbsp;&nbsp;Things<br>\nthat&nbsp;start&nbsp;with&nbsp;http&nbsp;and&nbsp;ftp&nbsp;should&nbsp;be&nbsp;auto-linked,&nbsp;too:<br>\n<a href="http://google.com">http://google.com</a>.</tt></dd></dl>', response.read())
'Test the precense of three consecutive system.* methods. This also tests their use of parameter type recognition and the systems related to that process.'
@make_request_and_skipIf((sys.flags.optimize >= 2), 'Docstrings are omitted with -O2 and above') def test_system_methods(self):
self.client.request('GET', '/') response = self.client.getresponse() self.assertIn('<dl><dt><a name="-system.listMethods"><strong>system.listMethods</strong></a>()</dt><dd><tt><a href="#-system.listMethods">system.listMethods</a>()&nbsp;=&gt;&nbsp;[\'add\',&nbsp;\'subtract\',&nbsp;\'multiple\']<br>\n&nbsp;<br>\nReturns&nbsp;a&nbsp;list&nbsp;of&nbsp;the&nbsp;methods&nbsp;supported&nbsp;by&nbsp;the&nbsp;server.</tt></dd></dl>\n <dl><dt><a name="-system.methodHelp"><strong>system.methodHelp</strong></a>(method_name)</dt><dd><tt><a href="#-system.methodHelp">system.methodHelp</a>(\'add\')&nbsp;=&gt;&nbsp;"Adds&nbsp;two&nbsp;integers&nbsp;together"<br>\n&nbsp;<br>\nReturns&nbsp;a&nbsp;string&nbsp;containing&nbsp;documentation&nbsp;for&nbsp;the&nbsp;specified&nbsp;method.</tt></dd></dl>\n <dl><dt><a name="-system.methodSignature"><strong>system.methodSignature</strong></a>(method_name)</dt><dd><tt><a href="#-system.methodSignature">system.methodSignature</a>(\'add\')&nbsp;=&gt;&nbsp;[double,&nbsp;int,&nbsp;int]<br>\n&nbsp;<br>\nReturns&nbsp;a&nbsp;list&nbsp;describing&nbsp;the&nbsp;signature&nbsp;of&nbsp;the&nbsp;method.&nbsp;In&nbsp;the<br>\nabove&nbsp;example,&nbsp;the&nbsp;add&nbsp;method&nbsp;takes&nbsp;two&nbsp;integers&nbsp;as&nbsp;arguments<br>\nand&nbsp;returns&nbsp;a&nbsp;double&nbsp;result.<br>\n&nbsp;<br>\nThis&nbsp;server&nbsp;does&nbsp;NOT&nbsp;support&nbsp;system.methodSignature.</tt></dd></dl>', response.read())
'Test that selfdot values are made strong automatically in the documentation.'
def test_autolink_dotted_methods(self):
self.client.request('GET', '/') response = self.client.getresponse() self.assertIn('Try&nbsp;self.<strong>add</strong>,&nbsp;too.', response.read())
'Return true iff floats x and y "are close"'
def assertCloseAbs(self, x, y, eps=1e-09):
if (abs(x) > abs(y)): (x, y) = (y, x) if (y == 0): return (abs(x) < eps) if (x == 0): return (abs(y) < eps) self.assertTrue((abs(((x - y) / y)) < eps))
'assert that floats x and y are identical, in the sense that: (1) both x and y are nans, or (2) both x and y are infinities, with the same sign, or (3) both x and y are zeros, with the same sign, or (4) x and y are both finite and nonzero, and x == y'
def assertFloatsAreIdentical(self, x, y):
msg = 'floats {!r} and {!r} are not identical' if (isnan(x) or isnan(y)): if (isnan(x) and isnan(y)): return elif (x == y): if (x != 0.0): return elif (copysign(1.0, x) == copysign(1.0, y)): return else: msg += ': zeros have different signs' self.fail(msg.format(x, y))
'Return true iff complexes x and y "are close"'
def assertClose(self, x, y, eps=1e-09):
self.assertCloseAbs(x.real, y.real, eps) self.assertCloseAbs(x.imag, y.imag, eps)
'Compute complex z=x*y, and check that z/x==y and z/y==x.'
def check_div(self, x, y):
z = (x * y) if (x != 0): q = (z / x) self.assertClose(q, y) q = z.__div__(x) self.assertClose(q, y) q = z.__truediv__(x) self.assertClose(q, y) if (y != 0): q = (z / y) self.assertClose(q, x) q = z.__div__(y) self.assertClose(q, x) q = z.__truediv__(y) self.assertClose(q, x)
'Common code for chown, fchown and lchown tests.'
def _test_all_chown_common(self, chown_func, first_param):
if (os.getuid() == 0): try: ent = pwd.getpwnam('nfsnobody') chown_func(first_param, ent.pw_uid, ent.pw_gid) except KeyError: pass else: self.assertRaises(OSError, chown_func, first_param, 0, 0) chown_func(first_param, os.getuid(), os.getgid())
'Check addresses and the date.'
def check(self, msg, results):
m = self.create_message(msg) i = 0 for (n, a) in (m.getaddrlist('to') + m.getaddrlist('cc')): try: (mn, ma) = (results[i][0], results[i][1]) except IndexError: print 'extra parsed address:', repr(n), repr(a) continue i = (i + 1) self.assertEqual(mn, n, ('Un-expected name: %r != %r' % (mn, n))) self.assertEqual(ma, a, ('Un-expected address: %r != %r' % (ma, a))) if ((mn == n) and (ma == a)): pass else: print 'not found:', repr(n), repr(a) out = m.getdate('date') if out: self.assertEqual(out, (1999, 1, 13, 23, 57, 35, 0, 1, 0), 'date conversion failed')
'Construct a bunch of `n` threads running the same function `f`. If `wait_before_exit` is True, the threads won\'t terminate until do_finish() is called.'
def __init__(self, f, n, wait_before_exit=False):
self.f = f self.n = n self.started = [] self.finished = [] self._can_exit = (not wait_before_exit) def task(): tid = get_ident() self.started.append(tid) try: f() finally: self.finished.append(tid) while (not self._can_exit): _wait() for i in range(n): start_new_thread(task, ())
'Helper function that checks if str(exc) == unicode(exc) == msg'
def check_same_msg(self, exc, msg):
self.assertEqual(str(exc), msg) self.assertEqual(str(exc), unicode(exc))
'Check same msg for built-in exceptions'
def test_builtin_exceptions(self):
exceptions = [SyntaxError('invalid syntax', ('<string>', 1, 3, '2+*3')), IOError(2, 'No such file or directory'), KeyError('both should have the same quotes'), UnicodeDecodeError('ascii', '\xc3\xa0', 0, 1, 'ordinal not in range(128)'), UnicodeEncodeError('ascii', u'\u1234', 0, 1, 'ordinal not in range(128)')] for exception in exceptions: self.assertEqual(str(exception), unicode(exception))
'Check same msg for Exception with 0 args'
def test_0_args(self):
self.check_same_msg(Exception(), '')
'Check same msg for exceptions with 0 args and overridden __str__'
def test_0_args_with_overridden___str__(self):
for msg in ('foo', u'foo'): self.check_same_msg(ExcWithOverriddenStr(msg=msg), msg) e = ExcWithOverriddenStr(msg=u'f\xf6\xf6') self.assertRaises(UnicodeEncodeError, str, e) self.assertEqual(unicode(e), u'f\xf6\xf6')
'Check same msg for Exceptions with 1 arg'
def test_1_arg(self):
for arg in ('foo', u'foo'): self.check_same_msg(Exception(arg), arg) e = Exception(u'f\xf6\xf6') self.assertRaises(UnicodeEncodeError, str, e) self.assertEqual(unicode(e), u'f\xf6\xf6')
'Check same msg for exceptions with overridden __str__ and 1 arg'
def test_1_arg_with_overridden___str__(self):
for msg in ('foo', u'foo'): self.check_same_msg(ExcWithOverriddenStr('arg', msg=msg), msg) e = ExcWithOverriddenStr('arg', msg=u'f\xf6\xf6') self.assertRaises(UnicodeEncodeError, str, e) self.assertEqual(unicode(e), u'f\xf6\xf6')
'Check same msg for Exceptions with many args'
def test_many_args(self):
argslist = [(3, 'foo'), (1, u'foo', 'bar'), (4, u'f\xf6\xf6', u'bar', 'baz')] for args in argslist: self.check_same_msg(Exception(*args), repr(args))
'Check same msg for exceptions with overridden __str__ and many args'
def test_many_args_with_overridden___str__(self):
for msg in ('foo', u'foo'): e = ExcWithOverriddenStr('arg1', u'arg2', u'f\xf6\xf6', msg=msg) self.check_same_msg(e, msg) e = ExcWithOverriddenStr('arg1', u'f\xf6\xf6', u'arg3', msg=u'f\xf6\xf6') self.assertRaises(UnicodeEncodeError, str, e) self.assertEqual(unicode(e), u'f\xf6\xf6')
'Return true iff _ExpectedSkips knows about the current platform.'
def isvalid(self):
return self.valid
'Return set of test names we expect to skip on current platform. self.isvalid() must be true.'
def getexpected(self):
assert self.isvalid() return self.expected
'Wait for child to finish, ignoring EINTR.'
def wait(self, child):
while True: try: child.wait() return except OSError as e: if (e.errno != errno.EINTR): raise
'Install a no-op signal handler that can be set to allow interrupts or not, and arrange for the original signal handler to be re-installed when the test is finished.'
def setUp(self):
self.signum = signal.SIGUSR1 oldhandler = signal.signal(self.signum, (lambda x, y: None)) self.addCleanup(signal.signal, self.signum, oldhandler)
'Perform a read during which a signal will arrive. Return True if the read is interrupted by the signal and raises an exception. Return False if it returns normally.'
def readpipe_interrupted(self):
(r, w) = os.pipe() self.addCleanup(os.close, r) ppid = os.getpid() pid = os.fork() if (pid == 0): try: time.sleep(0.2) os.kill(ppid, self.signum) time.sleep(0.2) finally: exit_subprocess() else: self.addCleanup(os.waitpid, pid, 0) os.close(w) try: d = os.read(r, 1) return False except OSError as err: if (err.errno != errno.EINTR): raise return True
'If a signal handler is installed and siginterrupt is not called at all, when that signal arrives, it interrupts a syscall that\'s in progress.'
def test_without_siginterrupt(self):
i = self.readpipe_interrupted() self.assertTrue(i) i = self.readpipe_interrupted() self.assertTrue(i)
'If a signal handler is installed and siginterrupt is called with a true value for the second argument, when that signal arrives, it interrupts a syscall that\'s in progress.'
def test_siginterrupt_on(self):
signal.siginterrupt(self.signum, 1) i = self.readpipe_interrupted() self.assertTrue(i) i = self.readpipe_interrupted() self.assertTrue(i)
'If a signal handler is installed and siginterrupt is called with a false value for the second argument, when that signal arrives, it does not interrupt a syscall that\'s in progress.'
def test_siginterrupt_off(self):
signal.siginterrupt(self.signum, 0) i = self.readpipe_interrupted() self.assertFalse(i) i = self.readpipe_interrupted() self.assertFalse(i)
'Implement isinstance(inst, cls).'
def __instancecheck__(cls, inst):
return any((cls.__subclasscheck__(c) for c in set([type(inst), inst.__class__])))
'Implement issubclass(sub, cls).'
def __subclasscheck__(cls, sub):
candidates = (cls.__dict__.get('__subclass__', set()) | set([cls])) return any(((c in candidates) for c in sub.mro()))
'headers: list of RFC822-style \'Key: value\' strings'
def __init__(self, headers=[], url=None):
import mimetools, StringIO f = StringIO.StringIO('\n'.join(headers)) self._headers = mimetools.Message(f) self._url = url