desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Write the PKG-INFO file into the release tree.'
def write_pkg_info(self, base_dir):
pkg_info = open(os.path.join(base_dir, 'PKG-INFO'), 'w') try: self.write_pkg_file(pkg_info) finally: pkg_info.close()
'Write the PKG-INFO format data to a file object.'
def write_pkg_file(self, file):
version = '1.0' if (self.provides or self.requires or self.obsoletes or self.classifiers or self.download_url): version = '1.1' self._write_field(file, 'Metadata-Version', version) self._write_field(file, 'Name', self.get_name()) self._write_field(file, 'Version', self.get_version()) sel...
'Print \'msg\' to stdout if the global DEBUG (taken from the DISTUTILS_DEBUG environment variable) flag is true.'
def debug_print(self, msg):
from distutils.debug import DEBUG if DEBUG: print msg
'Select strings (presumably filenames) from \'self.files\' that match \'pattern\', a Unix-style wildcard (glob) pattern. Patterns are not quite the same as implemented by the \'fnmatch\' module: \'*\' and \'?\' match non-special characters, where "special" is platform-dependent: slash on Unix; colon, slash, and backsl...
def include_pattern(self, pattern, anchor=1, prefix=None, is_regex=0):
files_found = 0 pattern_re = translate_pattern(pattern, anchor, prefix, is_regex) self.debug_print(("include_pattern: applying regex r'%s'" % pattern_re.pattern)) if (self.allfiles is None): self.findall() for name in self.allfiles: if pattern_re.search(name): se...
'Remove strings (presumably filenames) from \'files\' that match \'pattern\'. Other parameters are the same as for \'include_pattern()\', above. The list \'self.files\' is modified in place. Return 1 if files are found.'
def exclude_pattern(self, pattern, anchor=1, prefix=None, is_regex=0):
files_found = 0 pattern_re = translate_pattern(pattern, anchor, prefix, is_regex) self.debug_print(("exclude_pattern: applying regex r'%s'" % pattern_re.pattern)) for i in range((len(self.files) - 1), (-1), (-1)): if pattern_re.search(self.files[i]): self.debug_print((' r...
'Return list of registry keys.'
def read_keys(cls, base, key):
try: handle = RegOpenKeyEx(base, key) except RegError: return None L = [] i = 0 while True: try: k = RegEnumKey(handle, i) except RegError: break L.append(k) i += 1 return L
'Return dict of registry keys and values. All names are converted to lowercase.'
def read_values(cls, base, key):
try: handle = RegOpenKeyEx(base, key) except RegError: return None d = {} i = 0 while True: try: (name, value, type) = RegEnumValue(handle, i) except RegError: break name = name.lower() d[cls.convert_mbcs(name)] = cls.convert_mb...
'Return path to an MSVC executable program. Tries to find the program in several places: first, one of the MSVC program search paths from the registry; next, the directories in the PATH environment variable. If any of those work, return an absolute path that is known to exist. If none of them work, just return the or...
def find_exe(self, exe):
for p in self.__paths: fn = os.path.join(os.path.abspath(p), exe) if os.path.isfile(fn): return fn for p in os.environ['Path'].split(';'): fn = os.path.join(os.path.abspath(p), exe) if os.path.isfile(fn): return fn return exe
'Return path to an MSVC executable program. Tries to find the program in several places: first, one of the MSVC program search paths from the registry; next, the directories in the PATH environment variable. If any of those work, return an absolute path that is known to exist. If none of them work, just return the or...
def find_exe(self, exe):
for p in self.__paths: fn = os.path.join(os.path.abspath(p), exe) if os.path.isfile(fn): return fn for p in string.split(os.environ['Path'], ';'): fn = os.path.join(os.path.abspath(p), exe) if os.path.isfile(fn): return fn return exe
'Get a list of devstudio directories (include, lib or path). Return a list of strings. The list will be empty if unable to access the registry or appropriate registry keys not found.'
def get_msvc_paths(self, path, platform='x86'):
if (not _can_read_reg): return [] path = (path + ' dirs') if (self.__version >= 7): key = ('%s\\%0.1f\\VC\\VC_OBJECTS_PLATFORM_INFO\\Win32\\Directories' % (self.__root, self.__version)) else: key = ('%s\\6.0\\Build System\\Components\\Platforms\\Win32 (%s)\\Directories' ...
'Set environment variable \'name\' to an MSVC path type value. This is equivalent to a SET command prior to execution of spawned commands.'
def set_path_env_var(self, name):
if (name == 'lib'): p = self.get_msvc_paths('library') else: p = self.get_msvc_paths(name) if p: os.environ[name] = string.join(p, ';')
'Parse a version predicate string.'
def __init__(self, versionPredicateStr):
versionPredicateStr = versionPredicateStr.strip() if (not versionPredicateStr): raise ValueError('empty package restriction') match = re_validPackage.match(versionPredicateStr) if (not match): raise ValueError(('bad package name in %r' % versionPredicateStr)) (self....
'True if version is compatible with all the predicates in self. The parameter version must be acceptable to the StrictVersion constructor. It may be either a string or StrictVersion.'
def satisfied_by(self, version):
for (cond, ver) in self.pred: if (not compmap[cond](version, ver)): return False return True
'Construct a new TextFile object. At least one of \'filename\' (a string) and \'file\' (a file-like object) must be supplied. They keyword argument options are described above and affect the values returned by \'readline()\'.'
def __init__(self, filename=None, file=None, **options):
if ((filename is None) and (file is None)): raise RuntimeError, "you must supply either or both of 'filename' and 'file'" for opt in self.default_options.keys(): if (opt in options): setattr(self, opt, options[opt]) else: setattr(self, o...
'Open a new file named \'filename\'. This overrides both the \'filename\' and \'file\' arguments to the constructor.'
def open(self, filename):
self.filename = filename self.file = open(self.filename, 'r') self.current_line = 0
'Close the current file and forget everything we know about it (filename, current line number).'
def close(self):
file = self.file self.file = None self.filename = None self.current_line = None file.close()
'Print (to stderr) a warning message tied to the current logical line in the current file. If the current logical line in the file spans multiple physical lines, the warning refers to the whole range, eg. "lines 3-5". If \'line\' supplied, it overrides the current line number; it may be a list or tuple to indicate a ...
def warn(self, msg, line=None):
sys.stderr.write((('warning: ' + self.gen_error(msg, line)) + '\n'))
'Read and return a single logical line from the current file (or from an internal buffer if lines have previously been "unread" with \'unreadline()\'). If the \'join_lines\' option is true, this may involve reading multiple physical lines concatenated into a single string. Updates the current line number, so calling ...
def readline(self):
if self.linebuf: line = self.linebuf[(-1)] del self.linebuf[(-1)] return line buildup_line = '' while 1: line = self.file.readline() if (line == ''): line = None if (self.strip_comments and line): pos = line.find('#') if (po...
'Read and return the list of all logical lines remaining in the current file.'
def readlines(self):
lines = [] while 1: line = self.readline() if (line is None): return lines lines.append(line)
'Push \'line\' (a string) onto an internal buffer that will be checked by future \'readline()\' calls. Handy for implementing a parser with line-at-a-time lookahead.'
def unreadline(self, line):
self.linebuf.append(line)
'Create and initialize a new Command object. Most importantly, invokes the \'initialize_options()\' method, which is the real initializer and depends on the actual command being instantiated.'
def __init__(self, dist):
from distutils.dist import Distribution if (not isinstance(dist, Distribution)): raise TypeError, 'dist must be a Distribution instance' if (self.__class__ is Command): raise RuntimeError, 'Command is an abstract class' self.distribution = dist self.initial...
'Set default values for all the options that this command supports. Note that these defaults may be overridden by other commands, by the setup script, by config files, or by the command-line. Thus, this is not the place to code dependencies between options; generally, \'initialize_options()\' implementations are just...
def initialize_options(self):
raise RuntimeError, ('abstract method -- subclass %s must override' % self.__class__)
'Set final values for all the options that this command supports. This is always called as late as possible, ie. after any option assignments from the command-line or from other commands have been done. Thus, this is the place to code option dependencies: if \'foo\' depends on \'bar\', then it is safe to set \'foo\' ...
def finalize_options(self):
raise RuntimeError, ('abstract method -- subclass %s must override' % self.__class__)
'A command\'s raison d\'etre: carry out the action it exists to perform, controlled by the options initialized in \'initialize_options()\', customized by other commands, the setup script, the command-line, and config files, and finalized in \'finalize_options()\'. All terminal output and filesystem interaction should ...
def run(self):
raise RuntimeError, ('abstract method -- subclass %s must override' % self.__class__)
'If the current verbosity level is of greater than or equal to \'level\' print \'msg\' to stdout.'
def announce(self, msg, level=1):
log.log(level, msg)
'Print \'msg\' to stdout if the global DEBUG (taken from the DISTUTILS_DEBUG environment variable) flag is true.'
def debug_print(self, msg):
from distutils.debug import DEBUG if DEBUG: print msg sys.stdout.flush()
'Ensure that \'option\' is a string; if not defined, set it to \'default\'.'
def ensure_string(self, option, default=None):
self._ensure_stringlike(option, 'string', default)
'Ensure that \'option\' is a list of strings. If \'option\' is currently a string, we split it either on /,\s*/ or /\s+/, so "foo bar baz", "foo,bar,baz", and "foo, bar baz" all become ["foo", "bar", "baz"].'
def ensure_string_list(self, option):
val = getattr(self, option) if (val is None): return elif isinstance(val, str): setattr(self, option, re.split(',\\s*|\\s+', val)) else: if isinstance(val, list): ok = 1 for element in val: if (not isinstance(element, str)): ...
'Ensure that \'option\' is the name of an existing file.'
def ensure_filename(self, option):
self._ensure_tested_string(option, os.path.isfile, 'filename', "'%s' does not exist or is not a file")
'Set the values of any "undefined" options from corresponding option values in some other command object. "Undefined" here means "is None", which is the convention used to indicate that an option has not been changed between \'initialize_options()\' and \'finalize_options()\'. Usually called from \'finalize_options()...
def set_undefined_options(self, src_cmd, *option_pairs):
src_cmd_obj = self.distribution.get_command_obj(src_cmd) src_cmd_obj.ensure_finalized() for (src_option, dst_option) in option_pairs: if (getattr(self, dst_option) is None): setattr(self, dst_option, getattr(src_cmd_obj, src_option))
'Wrapper around Distribution\'s \'get_command_obj()\' method: find (create if necessary and \'create\' is true) the command object for \'command\', call its \'ensure_finalized()\' method, and return the finalized command object.'
def get_finalized_command(self, command, create=1):
cmd_obj = self.distribution.get_command_obj(command, create) cmd_obj.ensure_finalized() return cmd_obj
'Run some other command: uses the \'run_command()\' method of Distribution, which creates and finalizes the command object if necessary and then invokes its \'run()\' method.'
def run_command(self, command):
self.distribution.run_command(command)
'Determine the sub-commands that are relevant in the current distribution (ie., that need to be run). This is based on the \'sub_commands\' class attribute: each tuple in that list may include a method that we call to determine if the subcommand needs to be run for the current distribution. Return a list of command n...
def get_sub_commands(self):
commands = [] for (cmd_name, method) in self.sub_commands: if ((method is None) or method(self)): commands.append(cmd_name) return commands
'Copy a file respecting verbose, dry-run and force flags. (The former two default to whatever is in the Distribution object, and the latter defaults to false for commands that don\'t define it.)'
def copy_file(self, infile, outfile, preserve_mode=1, preserve_times=1, link=None, level=1):
return file_util.copy_file(infile, outfile, preserve_mode, preserve_times, (not self.force), link, dry_run=self.dry_run)
'Copy an entire directory tree respecting verbose, dry-run, and force flags.'
def copy_tree(self, infile, outfile, preserve_mode=1, preserve_times=1, preserve_symlinks=0, level=1):
return dir_util.copy_tree(infile, outfile, preserve_mode, preserve_times, preserve_symlinks, (not self.force), dry_run=self.dry_run)
'Move a file respecting dry-run flag.'
def move_file(self, src, dst, level=1):
return file_util.move_file(src, dst, dry_run=self.dry_run)
'Spawn an external command respecting dry-run flag.'
def spawn(self, cmd, search_path=1, level=1):
from distutils.spawn import spawn spawn(cmd, search_path, dry_run=self.dry_run)
'Special case of \'execute()\' for operations that process one or more input files and generate one output file. Works just like \'execute()\', except the operation is skipped and a different message printed if \'outfile\' already exists and is newer than all files listed in \'infiles\'. If the command defined \'self...
def make_file(self, infiles, outfile, func, args, exec_msg=None, skip_msg=None, level=1):
if (skip_msg is None): skip_msg = ('skipping %s (inputs unchanged)' % outfile) if isinstance(infiles, str): infiles = (infiles,) elif (not isinstance(infiles, (list, tuple))): raise TypeError, "'infiles' must be a string, or a list or tuple of ...
'Return an HTTP request made via transport_class.'
def issue_request(self, transport_class):
transport = transport_class() proxy = xmlrpclib.ServerProxy('http://example.com/', transport=transport) try: proxy.pow(6, 8) except RuntimeError: return transport.fake_socket.getvalue() return None
'>>> print SampleClass(12).get() 12'
def __init__(self, val):
self.val = val
'>>> print SampleClass(12).double().get() 24'
def double(self):
return SampleClass((self.val + self.val))
'>>> print SampleClass(-5).get() -5'
def get(self):
return self.val
'>>> print SampleClass.a_staticmethod(10) 11'
def a_staticmethod(v):
return (v + 1)
'>>> print SampleClass.a_classmethod(10) 12 >>> print SampleClass(0).a_classmethod(10) 12'
def a_classmethod(cls, v):
return (v + 2)
'>>> print SampleClass.NestedClass().get() 0'
def __init__(self, val=0):
self.val = val
'>>> print SampleNewStyleClass(12).get() 12'
def __init__(self, val):
self.val = val
'>>> print SampleNewStyleClass(12).double().get() 24'
def double(self):
return SampleNewStyleClass((self.val + self.val))
'>>> print SampleNewStyleClass(-5).get() -5'
def get(self):
return self.val
'Run \'python -c SOURCE\' under gdb with a breakpoint. Support injecting commands after the breakpoint is reached Returns the stdout from gdb cmds_after_breakpoint: if provided, a list of strings: gdb commands'
def get_stack_trace(self, source=None, script=None, breakpoint='PyObject_Print', cmds_after_breakpoint=None, import_site=False):
commands = ['set breakpoint pending yes', ('break %s' % breakpoint), 'set print address off', 'run'] if ((gdb_major_version, gdb_minor_version) >= (7, 4)): commands += ['set print entry-values no'] if cmds_after_breakpoint: commands += cmds_after_breakpoint ...
'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()) rep = self.get_gdb_repr("print set(['a', 'b'])")[0] self.assertTrue(rep.startswith('set([')) self.assertTrue(rep.endswith('])')) self.assertEqual(eval(rep), {'a', 'b'}) rep = self.get_gdb_repr('print set([4, 5])')[0] self.assertTrue(rep.startswith('set([...
'Verify the pretty-printing of frozensets'
def test_frozensets(self):
self.assertGdbRepr(frozenset()) rep = self.get_gdb_repr("print frozenset(['a', 'b'])")[0] self.assertTrue(rep.startswith('frozenset([')) self.assertTrue(rep.endswith('])')) self.assertEqual(eval(rep), {'a', 'b'}) rep = self.get_gdb_repr('print frozenset([4, 5])')[0] self.assertTr...
'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' % gd...
'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 cl...
'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 renderi...
'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 exp...
'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...
'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...
'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 ...
'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') @unittest.skipIf(python_is_optimized(), 'Python was compiled with optimizations') 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') @unittest.skipIf(python_is_optimized(), 'Python was compiled with optimizations') 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]...
'Verify that the "py-bt" command works'
@unittest.skipIf(python_is_optimized(), 'Python was compiled with optimizations') def test_bt(self):
bt = self.get_stack_trace(script=self.get_sample_script(), cmds_after_breakpoint=['py-bt']) self.assertMultilineMatches(bt, '^.*\nTraceback \\(most recent call first\\):\n File ".*gdb_sample.py", line 10, in baz\n print\\(42\\)\n File ".*gdb_sample.py",...
'Verify that the "py-bt-full" command works'
@unittest.skipIf(python_is_optimized(), 'Python was compiled with optimizations') def test_bt_full(self):
bt = self.get_stack_trace(script=self.get_sample_script(), cmds_after_breakpoint=['py-bt-full']) 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]+ ...
'Verify that "py-bt" indicates threads that are waiting for the GIL'
@unittest.skipUnless(thread, 'Python was compiled without thread support') def test_threads(self):
cmd = "\nfrom threading import Thread\n\nclass TestThread(Thread):\n # These threads would run forever, but we'll interrupt things with the\n # debugger\n def run(self):\n i = 0\n ...
'Verify that "py-bt" indicates if a thread is garbage-collecting'
@unittest.skipIf(python_is_optimized(), 'Python was compiled with optimizations') @unittest.skipUnless(thread, 'Python was compiled without thread support') def test_gc(self):
cmd = 'from gc import collect\nprint 42\ndef foo():\n collect()\ndef bar():\n foo()\nbar()\n' gdb_output = self.get_stack_trace(cmd, cmds_after_breakpoint=['break update_refs', 'continue', 'py-bt']) self.assertIn('Garbage-collecting', gdb_output) gdb_ou...
'Verify that "py-bt" displays invocations of PyCFunction instances'
@unittest.skipIf(python_is_optimized(), 'Python was compiled with optimizations') @unittest.skipUnless(thread, 'Python was compiled without thread support') def test_pycfunction(self):
cmd = 'from time import gmtime\ndef foo():\n gmtime(1)\ndef bar():\n foo()\nbar()\n' gdb_output = self.get_stack_trace(cmd, breakpoint='time_gmtime', cmds_after_breakpoint=['bt', 'py-bt']) self.assertIn('<built-in function gmtime', gdb_output) gdb_outpu...
'Verify that the "py-print" command works'
@unittest.skipIf(python_is_optimized(), 'Python was compiled with optimizations') 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 option...
'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_...
'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))...
'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