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()) self._write_field(file, 'Summary', self.get_description()) self._write_field(file, 'Home-page', self.get_url()) self._write_field(file, 'Author', self.get_contact()) self._write_field(file, 'Author-email', self.get_contact_email()) self._write_field(file, 'License', self.get_license()) if self.download_url: self._write_field(file, 'Download-URL', self.download_url) long_desc = rfc822_escape(self.get_long_description()) self._write_field(file, 'Description', long_desc) keywords = ','.join(self.get_keywords()) if keywords: self._write_field(file, 'Keywords', keywords) self._write_list(file, 'Platform', self.get_platforms()) self._write_list(file, 'Classifier', self.get_classifiers()) self._write_list(file, 'Requires', self.get_requires()) self._write_list(file, 'Provides', self.get_provides()) self._write_list(file, 'Obsoletes', self.get_obsoletes())
'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 backslash on DOS/Windows; and colon on Mac OS. If \'anchor\' is true (the default), then the pattern match is more stringent: "*.py" will match "foo.py" but not "foo/bar.py". If \'anchor\' is false, both of these will match. If \'prefix\' is supplied, then only filenames starting with \'prefix\' (itself a pattern) and ending with \'pattern\', with anything in between them, will match. \'anchor\' is ignored in this case. If \'is_regex\' is true, \'anchor\' and \'prefix\' are ignored, and \'pattern\' is assumed to be either a string containing a regex or a regex object -- no translation is done, the regex is just compiled and used as-is. Selected strings will be added to self.files. Return 1 if files are found.'
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): self.debug_print((' adding ' + name)) self.files.append(name) files_found = 1 return files_found
'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((' removing ' + self.files[i])) del self.files[i] files_found = 1 return files_found
'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_mbcs(value) i += 1 return d
'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 original program name, \'exe\'.'
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 original program name, \'exe\'.'
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' % (self.__root, platform)) for base in HKEYS: d = read_values(base, key) if d: if (self.__version >= 7): return string.split(self.__macros.sub(d[path]), ';') else: return string.split(d[path], ';') if (self.__version == 6): for base in HKEYS: if (read_values(base, ('%s\\6.0' % self.__root)) is not None): self.warn('It seems you have Visual Studio 6 installed, but the expected registry settings are not present.\nYou must at least run the Visual Studio GUI once so that these entries are created.') break return []
'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.name, paren) = match.groups() paren = paren.strip() if paren: match = re_paren.match(paren) if (not match): raise ValueError(('expected parenthesized list: %r' % paren)) str = match.groups()[0] self.pred = [splitUp(aPred) for aPred in str.split(',')] if (not self.pred): raise ValueError(('empty parenthesized list in %r' % versionPredicateStr)) else: self.pred = []
'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, opt, self.default_options[opt]) for opt in options.keys(): if (opt not in self.default_options): raise KeyError, ("invalid TextFile option '%s'" % opt) if (file is None): self.open(filename) else: self.filename = filename self.file = file self.current_line = 0 self.linebuf = []
'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 range of physical lines, or an integer for a single physical line.'
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 \'warn()\' after \'readline()\' emits a warning about the physical line(s) just read. Returns None on end-of-file, since the empty string can occur if \'rstrip_ws\' is true but \'strip_blanks\' is not.'
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 (pos == (-1)): pass elif ((pos == 0) or (line[(pos - 1)] != '\\')): eol = (((line[(-1)] == '\n') and '\n') or '') line = (line[0:pos] + eol) if (line.strip() == ''): continue else: line = line.replace('\\#', '#') if (self.join_lines and buildup_line): if (line is None): self.warn('continuation line immediately precedes end-of-file') return buildup_line if self.collapse_join: line = line.lstrip() line = (buildup_line + line) if isinstance(self.current_line, list): self.current_line[1] = (self.current_line[1] + 1) else: self.current_line = [self.current_line, (self.current_line + 1)] else: if (line is None): return None if isinstance(self.current_line, list): self.current_line = (self.current_line[1] + 1) else: self.current_line = (self.current_line + 1) if (self.lstrip_ws and self.rstrip_ws): line = line.strip() elif self.lstrip_ws: line = line.lstrip() elif self.rstrip_ws: line = line.rstrip() if (((line == '') or (line == '\n')) and self.skip_blanks): continue if self.join_lines: if (line[(-1)] == '\\'): buildup_line = line[:(-1)] continue if (line[(-2):] == '\\\n'): buildup_line = (line[0:(-2)] + '\n') continue return line
'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.initialize_options() self._dry_run = None self.verbose = dist.verbose self.force = None self.help = 0 self.finalized = 0
'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 a bunch of "self.foo = None" assignments. This method must be implemented by all command classes.'
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\' from \'bar\' as long as \'foo\' still has the same value it was assigned in \'initialize_options()\'. This method must be implemented by all command classes.'
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 be done by \'run()\'. This method must be implemented by all command classes.'
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)): ok = 0 break else: ok = 0 if (not ok): raise DistutilsOptionError, ("'%s' must be a list of strings (got %r)" % (option, val))
'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()\' for options that depend on some other command rather than another option of the same command. \'src_cmd\' is the other command from which option values will be taken (a command object will be created for it if necessary); the remaining arguments are \'(src_option,dst_option)\' tuples which mean "take the value of \'src_option\' in the \'src_cmd\' command object, and copy it to \'dst_option\' in the current command object".'
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 names.'
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.force\', and it is true, then the command is unconditionally run -- does no timestamp checks.'
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 strings" if (exec_msg is None): exec_msg = ('generating %s from %s' % (outfile, ', '.join(infiles))) if (self.force or dep_util.newer_group(infiles, outfile)): self.execute(func, args, exec_msg, level) else: log.debug(skip_msg)
'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 else: commands += ['backtrace'] args = ['gdb', '--batch', '-nx'] args += [('--eval-command=%s' % cmd) for cmd in commands] args += ['--args', sys.executable] if (not import_site): args += ['-S'] if source: args += ['-c', source] elif script: args += [script] (out, err) = run_gdb(PYTHONHASHSEED='0', *args) errlines = err.splitlines() unexpected_errlines = [] ignore_patterns = (('Function "%s" not defined.' % breakpoint), 'warning: no loadable sections found in added symbol-file system-supplied DSO', "warning: Unable to find libthread_db matching inferior's thread library, thread debugging will not be available.", 'warning: Cannot initialize thread debugging library: Debugger service failed', 'warning: Could not load shared library symbols for linux-vdso.so', 'warning: Could not load shared library symbols for linux-gate.so', 'warning: Could not load shared library symbols for linux-vdso64.so', 'Do you need "set solib-search-path" or "set sysroot"?', 'warning: Source file is more recent than executable.', 'Missing separate debuginfo for ', 'Try: zypper install -C ') for line in errlines: if (not line.startswith(ignore_patterns)): unexpected_errlines.append(line) self.assertEqual(unexpected_errlines, []) return out
'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([')) self.assertTrue(rep.endswith('])')) self.assertEqual(eval(rep), {4, 5}) (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()) 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.assertTrue(rep.startswith('frozenset([')) self.assertTrue(rep.endswith('])')) self.assertEqual(eval(rep), {4, 5})
'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') @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]+ 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'
@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", line 7, in bar\n baz\\(a, b, c\\)\n File ".*gdb_sample.py", line 4, in foo\n bar\\(a, b, c\\)\n File ".*gdb_sample.py", line 12, in <module>\n foo\\(1, 2, 3\\)\n')
'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]+ 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> \\(\\)\n foo\\(1, 2, 3\\)\n')
'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 while 1:\n i += 1\n\nt = {}\nfor i in range(4):\n t[i] = TestThread()\n t[i].start()\n\n# Trigger a breakpoint on the main thread\nprint 42\n\n" gdb_output = self.get_stack_trace(cmd, cmds_after_breakpoint=['thread apply all py-bt']) self.assertIn('Waiting for the GIL', gdb_output) gdb_output = self.get_stack_trace(cmd, cmds_after_breakpoint=['thread apply all py-bt-full']) self.assertIn('Waiting for the GIL', gdb_output)
'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_output = self.get_stack_trace(cmd, cmds_after_breakpoint=['break update_refs', 'continue', 'py-bt-full']) self.assertIn('Garbage-collecting', gdb_output)
'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_output = self.get_stack_trace(cmd, breakpoint='time_gmtime', cmds_after_breakpoint=['py-bt-full']) self.assertIn('#0 <built-in function gmtime', gdb_output)
'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 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