desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'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')
|
'Tests invoking FileInput.__getitem__() with an index unequal to
the line number'
| def test__getitem__invalid_key(self):
| t = writeTmp(1, ['line1\n', 'line2\n'])
self.addCleanup(remove_tempfiles, t)
with FileInput(files=[t]) as fi:
with self.assertRaises(RuntimeError) as cm:
fi[1]
self.assertEqual(cm.exception.args, ('accessing lines out of order',))
|
'Tests invoking FileInput.__getitem__() with the line number but at
end-of-input'
| def test__getitem__eof(self):
| t = writeTmp(1, [])
self.addCleanup(remove_tempfiles, t)
with FileInput(files=[t]) as fi:
with self.assertRaises(IndexError) as cm:
fi[0]
self.assertEqual(cm.exception.args, ('end of input reached',))
|
'Tests invoking FileInput.nextfile() when the attempt to delete
the backup file would raise OSError. This error is expected to be
silently ignored'
| def test_nextfile_oserror_deleting_backup(self):
| os_unlink_orig = os.unlink
os_unlink_replacement = UnconditionallyRaise(OSError)
try:
t = writeTmp(1, ['\n'])
self.addCleanup(remove_tempfiles, t)
with FileInput(files=[t], inplace=True) as fi:
next(fi)
os.unlink = os_unlink_replacement
fi.nextfile... |
'Tests invoking FileInput.readline() when os.fstat() raises OSError.
This exception should be silently discarded.'
| def test_readline_os_fstat_raises_OSError(self):
| os_fstat_orig = os.fstat
os_fstat_replacement = UnconditionallyRaise(OSError)
try:
t = writeTmp(1, ['\n'])
self.addCleanup(remove_tempfiles, t)
with FileInput(files=[t], inplace=True) as fi:
os.fstat = os_fstat_replacement
fi.readline()
finally:
os... |
'Tests invoking FileInput.readline() when os.chmod() raises OSError.
This exception should be silently discarded.'
| @unittest.skipIf((not hasattr(os, 'chmod')), 'os.chmod does not exist')
def test_readline_os_chmod_raises_OSError(self):
| os_chmod_orig = os.chmod
os_chmod_replacement = UnconditionallyRaise(OSError)
try:
t = writeTmp(1, ['\n'])
self.addCleanup(remove_tempfiles, t)
with FileInput(files=[t], inplace=True) as fi:
os.chmod = os_chmod_replacement
fi.readline()
finally:
os... |
'Tests invoking fileinput.input() when fileinput._state is not None
and its _file attribute is also not None. Expect RuntimeError to
be raised with a meaningful error message and for fileinput._state
to *not* be modified.'
| def test_state_is_not_None_and_state_file_is_not_None(self):
| instance = MockFileInput()
instance._file = object()
fileinput._state = instance
with self.assertRaises(RuntimeError) as cm:
fileinput.input()
self.assertEqual(('input() already active',), cm.exception.args)
self.assertIs(instance, fileinput._state, 'fileinput._state')
|
'Tests invoking fileinput.input() when fileinput._state is not None
but its _file attribute *is* None. Expect it to create and return
a new fileinput.FileInput object with all method parameters passed
explicitly to the __init__() method; also ensure that
fileinput._state is set to the returned instance.'
| def test_state_is_not_None_and_state_file_is_None(self):
| instance = MockFileInput()
instance._file = None
fileinput._state = instance
self.do_test_call_input()
|
'Tests invoking fileinput.input() when fileinput._state is None
Expect it to create and return a new fileinput.FileInput object
with all method parameters passed explicitly to the __init__()
method; also ensure that fileinput._state is set to the returned
instance.'
| def test_state_is_None(self):
| fileinput._state = None
self.do_test_call_input()
|
'Tests that fileinput.input() creates a new fileinput.FileInput
object, passing the given parameters unmodified to
fileinput.FileInput.__init__(). Note that this test depends on the
monkey patching of fileinput.FileInput done by setUp().'
| def do_test_call_input(self):
| files = object()
inplace = object()
backup = object()
bufsize = object()
mode = object()
openhook = object()
result = fileinput.input(files=files, inplace=inplace, backup=backup, bufsize=bufsize, mode=mode, openhook=openhook)
self.assertIs(result, fileinput._state, 'fileinput._state')
... |
'Tests that fileinput.close() does nothing if fileinput._state
is None'
| def test_state_is_None(self):
| fileinput._state = None
fileinput.close()
self.assertIsNone(fileinput._state)
|
'Tests that fileinput.close() invokes close() on fileinput._state
and sets _state=None'
| def test_state_is_not_None(self):
| instance = MockFileInput()
fileinput._state = instance
fileinput.close()
self.assertExactlyOneInvocation(instance, 'close')
self.assertIsNone(fileinput._state)
|
'Tests fileinput.nextfile() when fileinput._state is None.
Ensure that it raises RuntimeError with a meaningful error message
and does not modify fileinput._state'
| def test_state_is_None(self):
| fileinput._state = None
with self.assertRaises(RuntimeError) as cm:
fileinput.nextfile()
self.assertEqual(('no active input()',), cm.exception.args)
self.assertIsNone(fileinput._state)
|
'Tests fileinput.nextfile() when fileinput._state is not None.
Ensure that it invokes fileinput._state.nextfile() exactly once,
returns whatever it returns, and does not modify fileinput._state
to point to a different object.'
| def test_state_is_not_None(self):
| nextfile_retval = object()
instance = MockFileInput()
instance.return_values['nextfile'] = nextfile_retval
fileinput._state = instance
retval = fileinput.nextfile()
self.assertExactlyOneInvocation(instance, 'nextfile')
self.assertIs(retval, nextfile_retval)
self.assertIs(fileinput._state... |
'Tests fileinput.filename() when fileinput._state is None.
Ensure that it raises RuntimeError with a meaningful error message
and does not modify fileinput._state'
| def test_state_is_None(self):
| fileinput._state = None
with self.assertRaises(RuntimeError) as cm:
fileinput.filename()
self.assertEqual(('no active input()',), cm.exception.args)
self.assertIsNone(fileinput._state)
|
'Tests fileinput.filename() when fileinput._state is not None.
Ensure that it invokes fileinput._state.filename() exactly once,
returns whatever it returns, and does not modify fileinput._state
to point to a different object.'
| def test_state_is_not_None(self):
| filename_retval = object()
instance = MockFileInput()
instance.return_values['filename'] = filename_retval
fileinput._state = instance
retval = fileinput.filename()
self.assertExactlyOneInvocation(instance, 'filename')
self.assertIs(retval, filename_retval)
self.assertIs(fileinput._state... |
'Tests fileinput.lineno() when fileinput._state is None.
Ensure that it raises RuntimeError with a meaningful error message
and does not modify fileinput._state'
| def test_state_is_None(self):
| fileinput._state = None
with self.assertRaises(RuntimeError) as cm:
fileinput.lineno()
self.assertEqual(('no active input()',), cm.exception.args)
self.assertIsNone(fileinput._state)
|
'Tests fileinput.lineno() when fileinput._state is not None.
Ensure that it invokes fileinput._state.lineno() exactly once,
returns whatever it returns, and does not modify fileinput._state
to point to a different object.'
| def test_state_is_not_None(self):
| lineno_retval = object()
instance = MockFileInput()
instance.return_values['lineno'] = lineno_retval
fileinput._state = instance
retval = fileinput.lineno()
self.assertExactlyOneInvocation(instance, 'lineno')
self.assertIs(retval, lineno_retval)
self.assertIs(fileinput._state, instance)
|
'Tests fileinput.filelineno() when fileinput._state is None.
Ensure that it raises RuntimeError with a meaningful error message
and does not modify fileinput._state'
| def test_state_is_None(self):
| fileinput._state = None
with self.assertRaises(RuntimeError) as cm:
fileinput.filelineno()
self.assertEqual(('no active input()',), cm.exception.args)
self.assertIsNone(fileinput._state)
|
'Tests fileinput.filelineno() when fileinput._state is not None.
Ensure that it invokes fileinput._state.filelineno() exactly once,
returns whatever it returns, and does not modify fileinput._state
to point to a different object.'
| def test_state_is_not_None(self):
| filelineno_retval = object()
instance = MockFileInput()
instance.return_values['filelineno'] = filelineno_retval
fileinput._state = instance
retval = fileinput.filelineno()
self.assertExactlyOneInvocation(instance, 'filelineno')
self.assertIs(retval, filelineno_retval)
self.assertIs(file... |
'Tests fileinput.fileno() when fileinput._state is None.
Ensure that it raises RuntimeError with a meaningful error message
and does not modify fileinput._state'
| def test_state_is_None(self):
| fileinput._state = None
with self.assertRaises(RuntimeError) as cm:
fileinput.fileno()
self.assertEqual(('no active input()',), cm.exception.args)
self.assertIsNone(fileinput._state)
|
'Tests fileinput.fileno() when fileinput._state is not None.
Ensure that it invokes fileinput._state.fileno() exactly once,
returns whatever it returns, and does not modify fileinput._state
to point to a different object.'
| def test_state_is_not_None(self):
| fileno_retval = object()
instance = MockFileInput()
instance.return_values['fileno'] = fileno_retval
instance.fileno_retval = fileno_retval
fileinput._state = instance
retval = fileinput.fileno()
self.assertExactlyOneInvocation(instance, 'fileno')
self.assertIs(retval, fileno_retval)
... |
'Tests fileinput.isfirstline() when fileinput._state is None.
Ensure that it raises RuntimeError with a meaningful error message
and does not modify fileinput._state'
| def test_state_is_None(self):
| fileinput._state = None
with self.assertRaises(RuntimeError) as cm:
fileinput.isfirstline()
self.assertEqual(('no active input()',), cm.exception.args)
self.assertIsNone(fileinput._state)
|
'Tests fileinput.isfirstline() when fileinput._state is not None.
Ensure that it invokes fileinput._state.isfirstline() exactly once,
returns whatever it returns, and does not modify fileinput._state
to point to a different object.'
| def test_state_is_not_None(self):
| isfirstline_retval = object()
instance = MockFileInput()
instance.return_values['isfirstline'] = isfirstline_retval
fileinput._state = instance
retval = fileinput.isfirstline()
self.assertExactlyOneInvocation(instance, 'isfirstline')
self.assertIs(retval, isfirstline_retval)
self.assertI... |
'Tests fileinput.isstdin() when fileinput._state is None.
Ensure that it raises RuntimeError with a meaningful error message
and does not modify fileinput._state'
| def test_state_is_None(self):
| fileinput._state = None
with self.assertRaises(RuntimeError) as cm:
fileinput.isstdin()
self.assertEqual(('no active input()',), cm.exception.args)
self.assertIsNone(fileinput._state)
|
'Tests fileinput.isstdin() when fileinput._state is not None.
Ensure that it invokes fileinput._state.isstdin() exactly once,
returns whatever it returns, and does not modify fileinput._state
to point to a different object.'
| def test_state_is_not_None(self):
| isstdin_retval = object()
instance = MockFileInput()
instance.return_values['isstdin'] = isstdin_retval
fileinput._state = instance
retval = fileinput.isstdin()
self.assertExactlyOneInvocation(instance, 'isstdin')
self.assertIs(retval, isstdin_retval)
self.assertIs(fileinput._state, inst... |
'Asserts that both the types and values are the same.'
| def assertTypedEquals(self, expected, actual):
| self.assertEqual(type(expected), type(actual))
self.assertEqual(expected, actual)
|
'Asserts that callable(*args, **kwargs) raises exc_type(message).'
| def assertRaisesMessage(self, exc_type, message, callable, *args, **kwargs):
| try:
callable(*args, **kwargs)
except exc_type as e:
self.assertEqual(message, str(e))
else:
self.fail(('%s not raised' % exc_type.__name__))
|
'Returns instr if op is found, otherwise throws AssertionError'
| def assertInBytecode(self, x, opname, argval=_UNSPECIFIED):
| for instr in dis.get_instructions(x):
if (instr.opname == opname):
if ((argval is _UNSPECIFIED) or (instr.argval == argval)):
return instr
disassembly = self.get_disassembly_as_string(x)
if (argval is _UNSPECIFIED):
msg = ('%s not found in bytecode:\n%... |
'Throws AssertionError if op is found'
| def assertNotInBytecode(self, x, opname, argval=_UNSPECIFIED):
| for instr in dis.get_instructions(x):
if (instr.opname == opname):
disassembly = self.get_disassembly_as_string(co)
if (opargval is _UNSPECIFIED):
msg = ('%s occurs in bytecode:\n%s' % (opname, disassembly))
elif (instr.argval == argval):
... |
'Check that compileall recreates bytecode when the new metadata is
used.'
| @unittest.skipUnless(hasattr(os, 'stat'), 'test needs os.stat()')
def recreation_check(self, metadata):
| py_compile.compile(self.source_path)
self.assertEqual(*self.data())
with open(self.bc_path, 'rb') as file:
bc = file.read()[len(metadata):]
with open(self.bc_path, 'wb') as file:
file.write(metadata)
file.write(bc)
self.assertNotEqual(*self.data())
compileall.compile_dir(... |
'Another
docstring
containing
tabs'
| def abuse(self, a, b, c):
| self.argue(a, b, c)
|
'Common code for chown, fchown and lchown tests.'
| def _test_all_chown_common(self, chown_func, first_param, stat_func):
| def check_stat(uid, gid):
if (stat_func is not None):
stat = stat_func(first_param)
self.assertEqual(stat.st_uid, uid)
self.assertEqual(stat.st_gid, gid)
uid = os.getuid()
gid = os.getgid()
chown_func(first_param, uid, gid)
check_stat(uid, gid)
chown_f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.