desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'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 = all((isinstance(v, str) for v in val))
else:
ok = False
if (not ok):
... |
'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 ... |
'Test passes if ``first`` and ``second`` are approximately equal.
This test passes if ``first`` and ``second`` are equal to
within ``tol``, an absolute error, or ``rel``, a relative error.
If either ``tol`` or ``rel`` are None or not given, they default to
test attributes of the same name (by default, 0).
The objects m... | def assertApproxEqual(self, first, second, tol=None, rel=None, msg=None):
| if (tol is None):
tol = self.tol
if (rel is None):
rel = self.rel
if (isinstance(first, collections.Sequence) and isinstance(second, collections.Sequence)):
check = self._check_approx_seq
else:
check = self._check_approx_num
check(first, second, tol, rel, msg)
|
'Return substrings we expect to see in error messages.'
| def generate_substrings(self, first, second, tol, rel, idx):
| (abs_err, rel_err) = _calc_errors(first, second)
substrings = [('tol=%r' % tol), ('rel=%r' % rel), ('absolute error = %r' % abs_err), ('relative error = %r' % rel_err)]
if (idx is not None):
substrings.append(('differ at index %d' % idx))
return substrings
|
'Return int data for various tests.'
| def prepare_data(self):
| data = list(range(10))
while (data == sorted(data)):
random.shuffle(data)
return data
|
'Check x is an infinity of the same type and sign as inf.'
| def check_infinity(self, x, inf):
| self.assertTrue(math.isinf(x))
self.assertIs(type(x), type(inf))
self.assertEqual((x > 0), (inf > 0))
assert (x == inf)
|
'Overload method from UnivariateCommonMixin.'
| def prepare_data(self):
| data = super().prepare_data()
if ((len(data) % 2) != 1):
data.append(2)
return data
|
'Overload method from UnivariateCommonMixin.'
| def prepare_data(self):
| return [1, 1, 1, 1, 3, 4, 7, 9, 0, 8, 2]
|
'>>> 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=BREAKPOINT_FN, cmds_after_breakpoint=None, import_site=False):
| commands = ['set breakpoint pending yes', ('break %s' % breakpoint), 'run']
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 += [... |
'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(1000000000000)
self.assertGdbRepr((-1000000000000000))
|
'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'}, "{'foo': 'bar'}")
self.assertGdbRepr({'foo': 'bar', 'douglas': 42}, "{'douglas': 42, 'foo': 'bar'}")
|
'Verify the pretty-printing of lists'
| def test_lists(self):
| self.assertGdbRepr([])
self.assertGdbRepr(list(range(5)))
|
'Verify the pretty-printing of bytes'
| def test_bytes(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 a tab: DCTB this is a slash-N:\n thi... |
'Verify the pretty-printing of unicode strings'
| def test_strings(self):
| encoding = locale.getpreferredencoding()
def check_repr(text):
try:
text.encode(encoding)
printable = True
except UnicodeEncodeError:
self.assertGdbRepr(text, ascii(text))
else:
self.assertGdbRepr(text)
self.assertGdbRepr('')
self.a... |
'Verify the pretty-printing of tuples'
| def test_tuples(self):
| self.assertGdbRepr(tuple(), '()')
self.assertGdbRepr((1,), '(1,)')
self.assertGdbRepr(('foo', 'bar', 'baz'))
|
'Verify the pretty-printing of sets'
| def test_sets(self):
| if ((gdb_major_version, gdb_minor_version) < (7, 3)):
self.skipTest('pretty-printing of sets needs gdb 7.3 or later')
self.assertGdbRepr(set(), 'set()')
self.assertGdbRepr(set(['a', 'b']), "{'a', 'b'}")
self.assertGdbRepr(set([4, 5, 6]), '{4, 5, 6}')
(gdb_repr, ... |
'Verify the pretty-printing of frozensets'
| def test_frozensets(self):
| if ((gdb_major_version, gdb_minor_version) < (7, 3)):
self.skipTest('pretty-printing of frozensets needs gdb 7.3 or later')
self.assertGdbRepr(frozenset(), 'frozenset()')
self.assertGdbRepr(frozenset(['a', 'b']), "frozenset({'a', 'b'})")
self.assertGdbRepr(frozenset([4, 5... |
'Verify the pretty-printing of new-style class instances'
| def test_modern_class(self):
| (gdb_repr, gdb_output) = self.get_gdb_repr('\nclass Foo:\n pass\nfoo = Foo()\nfoo.an_int = 42\nid(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\nid(foo)')
m = re.match('<Foo\\(an_int=42\\) at remote 0x-?[0-9a-f]+>', gdb_repr)
self.assertTrue(m, msg=('Unexpected new-style class... |
'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\nid(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 ... |
'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, exprepr=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 exprepr:
if (gdb_repr == exprepr):
return
pattern = '<.*... |
'Ensure that a NULL PyObject* is handled gracefully'
| def test_NULL_ptr(self):
| (gdb_repr, gdb_output) = self.get_gdb_repr('id(42)', cmds_after_breakpoint=['set variable v=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('id(42)', 'set v->ob_type=0')
|
'Ensure that a PyObject* with a corrupt ob_type is handled gracefully'
| def test_corrupt_ob_type(self):
| self.assertSane('id(42)', 'set v->ob_type=0xDEADBEEF', exprepr='42')
|
'Ensure that a PyObject* with a type with corrupt tp_flags is handled'
| def test_corrupt_tp_flags(self):
| self.assertSane('id(42)', 'set v->ob_type->tp_flags=0x0', exprepr='42')
|
'Ensure that a PyObject* with a type with corrupt tp_name is handled'
| def test_corrupt_tp_name(self):
| self.assertSane('id(42)', 'set v->ob_type->tp_name=0xDEADBEEF', exprepr='42')
|
'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('id(__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) ; id(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) ; id(a)')
self.assertEqu... |
'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 ; id(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('id(list(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, 3... |
'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 id(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-... |
'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 id\\(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\nid(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 ... |
'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 sleep\ndef foo():\n sleep(1)\ndef bar():\n foo()\nbar()\n'
gdb_output = self.get_stack_trace(cmd, breakpoint='time_sleep', cmds_after_breakpoint=['bt', 'py-bt'])
self.assertIn('<built-in method sleep', gdb_output)
gdb_output = se... |
'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
|
'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 Exception
except object_:
pass
except TypeError:
pass
except Exception:
self.fail(('TypeError expected when catching %s' % type(object_)))
try:
try:
raise Exception
except (object_,):
... |
'Test the create function with default arguments.'
| def test_defaults(self):
| shutil.rmtree(self.env_dir)
self.run_with_capture(venv.create, self.env_dir)
self.isdir(self.bindir)
self.isdir(self.include)
self.isdir(*self.lib)
p = self.get_env_file('lib64')
conditions = ((struct.calcsize('P') == 8) and (os.name == 'posix') and (sys.platform != 'darwin'))
if conditi... |
'Test that the prefix values are as expected.'
| @skipInVenv
def test_prefixes(self):
| self.assertEqual(sys.base_prefix, sys.prefix)
self.assertEqual(sys.base_exec_prefix, sys.exec_prefix)
shutil.rmtree(self.env_dir)
self.run_with_capture(venv.create, self.env_dir)
envpy = os.path.join(self.env_dir, self.bindir, self.exe)
cmd = [envpy, '-c', None]
for (prefix, expected) in (('... |
'Create some files in the environment which are unrelated
to the virtual environment.'
| def create_contents(self, paths, filename):
| for subdirs in paths:
d = os.path.join(self.env_dir, *subdirs)
os.mkdir(d)
fn = os.path.join(d, filename)
with open(fn, 'wb') as f:
f.write('Still here?')
|
'Test creating environment in an existing directory.'
| def test_overwrite_existing(self):
| self.create_contents(self.ENV_SUBDIRS, 'foo')
venv.create(self.env_dir)
for subdirs in self.ENV_SUBDIRS:
fn = os.path.join(self.env_dir, *(subdirs + ('foo',)))
self.assertTrue(os.path.exists(fn))
with open(fn, 'rb') as f:
self.assertEqual(f.read(), 'Still here?')
b... |
'Test upgrading an existing environment directory.'
| def test_upgrade(self):
| for upgrade in (False, True):
builder = venv.EnvBuilder(upgrade=upgrade)
self.run_with_capture(builder.create, self.env_dir)
self.isdir(self.bindir)
self.isdir(self.include)
self.isdir(*self.lib)
fn = self.get_env_file(self.bindir, self.exe)
if (not os.path.ex... |
'Test isolation from system site-packages'
| def test_isolation(self):
| for (ssp, s) in ((True, 'true'), (False, 'false')):
builder = venv.EnvBuilder(clear=True, system_site_packages=ssp)
builder.create(self.env_dir)
data = self.get_text_file_contents('pyvenv.cfg')
self.assertIn(('include-system-site-packages = %s\n' % s), data)
|
'Test symlinking works as expected'
| @unittest.skipUnless(can_symlink(), 'Needs symlinks')
def test_symlinking(self):
| for usl in (False, True):
builder = venv.EnvBuilder(clear=True, symlinks=usl)
builder.create(self.env_dir)
fn = self.get_env_file(self.bindir, self.exe)
if usl:
self.assertTrue(os.path.islink(fn))
|
'Test that the sys.executable value is as expected.'
| @skipInVenv
def test_executable(self):
| shutil.rmtree(self.env_dir)
self.run_with_capture(venv.create, self.env_dir)
envpy = os.path.join(os.path.realpath(self.env_dir), self.bindir, self.exe)
cmd = [envpy, '-c', 'import sys; print(sys.executable)']
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(out, ... |
'Test that the sys.executable value is as expected.'
| @unittest.skipUnless(can_symlink(), 'Needs symlinks')
def test_executable_symlinks(self):
| shutil.rmtree(self.env_dir)
builder = venv.EnvBuilder(clear=True, symlinks=True)
builder.create(self.env_dir)
envpy = os.path.join(os.path.realpath(self.env_dir), self.bindir, self.exe)
cmd = [envpy, '-c', 'import sys; print(sys.executable)']
p = subprocess.Popen(cmd, stdout=subprocess.PIP... |
'Mock system environment for InteractiveConsole'
| def mock_sys(self):
| stack = ExitStack()
self.addCleanup(stack.close)
self.infunc = stack.enter_context(mock.patch('code.input', create=True))
self.stdout = stack.enter_context(mock.patch('code.sys.stdout'))
self.stderr = stack.enter_context(mock.patch('code.sys.stderr'))
prepatch = mock.patch('code.sys', wraps=code... |
'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
|
'Check fork() in main thread works while a subthread is doing an import'
| def test_threaded_import_lock_fork(self):
| import_started = threading.Event()
fake_module_name = 'fake test module'
partial_module = 'partial'
complete_module = 'complete'
def importer():
imp.acquire_lock()
sys.modules[fake_module_name] = partial_module
import_started.set()
time.sleep(0.01)
sys.m... |
'Check fork() in main thread works while the main thread is doing an import'
| def test_nested_import_lock_fork(self):
| def fork_with_import_lock(level):
release = 0
in_child = False
try:
try:
for i in range(level):
imp.acquire_lock()
release += 1
pid = os.fork()
in_child = (not pid)
finally:
... |
'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.assertEqual(comparison, strftime_output, ('%s: position within tuple inco... |
'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_out... |
'The Request.headers dictionary is not a documented interface. It
should stay that way, because the complete set of headers are only
accessible through the .get_header(), .has_header(), .header_items()
interface. However, .headers pre-dates those methods, and so real code
will be using the dictionary.
The introductio... | def test_request_headers_dict(self):
| url = 'http://example.com'
self.assertEqual(Request(url, headers={'Spam-eggs': 'blah'}).headers['Spam-eggs'], 'blah')
self.assertEqual(Request(url, headers={'spam-EggS': 'blah'}).headers['Spam-eggs'], 'blah')
|
'Note the case normalization of header names here, to
.capitalize()-case. This should be preserved for
backwards-compatibility. (In the HTTP case, normalization to
.title()-case is done by urllib2 before sending headers to
http.client).
Note that e.g. r.has_header("spam-EggS") is currently False, and
r.get_header("sp... | def test_request_headers_methods(self):
| url = 'http://example.com'
req = Request(url, headers={'Spam-eggs': 'blah'})
self.assertTrue(req.has_header('Spam-eggs'))
self.assertEqual(req.header_items(), [('Spam-eggs', 'blah')])
req.add_header('Foo-Bar', 'baz')
self.assertEqual(sorted(req.header_items()), [('Foo-bar', 'baz'), ('Spam-eggs',... |
'The point to note here is that we can\'t guess the default port if
there\'s no scheme. This applies to both add_password and
find_user_password.'
| def test_password_manager_default_port(self):
| mgr = urllib.request.HTTPPasswordMgr()
add = mgr.add_password
find_user_pass = mgr.find_user_password
add('f', 'http://g.example.com:80', '10', 'j')
add('g', 'http://h.example.com', '11', 'k')
add('h', 'i.example.com:80', '12', 'l')
add('i', 'j.example.com', '13', 'm')
self.assertEqual(f... |
'Test the connection is cleaned up when the response is closed'
| def test_http_closed(self):
| for (transfer, data) in (('Connection: close', 'data'), ('Transfer-Encoding: chunked', '4\r\ndata\r\n0\r\n\r\n'), ('Content-Length: 4', 'data')):
header = 'HTTP/1.1 200 OK\r\n{}\r\n\r\n'.format(transfer)
conn = test_urllib.fakehttp((header.encode() + data))
handler = urllib.re... |
'Test the connection is cleaned up after an invalid response'
| def test_invalid_closed(self):
| conn = test_urllib.fakehttp('')
handler = urllib.request.AbstractHTTPHandler()
req = Request('http://dummy/')
req.timeout = None
with self.assertRaises(http.client.BadStatusLine):
handler.do_open(conn, req)
self.assertTrue(conn.fakesock.closed, 'Connection not closed')
|
'Issue 13211 reveals that HTTPError didn\'t implement the URLError
interface even though HTTPError is a subclass of URLError.'
| def test_HTTPError_interface(self):
| msg = 'something bad happened'
url = code = fp = None
hdrs = 'Content-Length: 42'
err = urllib.error.HTTPError(url, code, msg, hdrs, fp)
self.assertTrue(hasattr(err, 'reason'))
self.assertEqual(err.reason, 'something bad happened')
self.assertTrue(hasattr(err, 'headers'))
... |
'Tests invoking FileInput.__getitem__() with the current
line number'
| def test__getitem__(self):
| t = writeTmp(1, ['line1\n', 'line2\n'])
self.addCleanup(remove_tempfiles, t)
with FileInput(files=[t]) as fi:
retval1 = fi[0]
self.assertEqual(retval1, 'line1\n')
retval2 = fi[1]
self.assertEqual(retval2, 'line2\n')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.