desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Check handling of non-integer ports.'
| def test_attributes_bad_port(self):
| p = urllib.parse.urlsplit('http://www.example.net:foo')
self.assertEqual(p.netloc, 'www.example.net:foo')
self.assertRaises(ValueError, (lambda : p.port))
p = urllib.parse.urlparse('http://www.example.net:foo')
self.assertEqual(p.netloc, 'www.example.net:foo')
self.assertRaises(ValueError, (lamb... |
'Testing the supported limits of the int() base parameter.'
| def test_int_base_limits(self):
| self.assertEqual(int('0', 5), 0)
with self.assertRaises(ValueError):
int('0', 1)
with self.assertRaises(ValueError):
int('0', 37)
with self.assertRaises(ValueError):
int('0', (-909))
with self.assertRaises(ValueError):
int('0', base=(0 - (2 ** 234)))
with self.ass... |
'Not integer types are not valid bases; issue16772.'
| def test_int_base_bad_types(self):
| with self.assertRaises(TypeError):
int('0', 5.5)
with self.assertRaises(TypeError):
int('0', 5.0)
|
'Compare calculation against known value, if available'
| def numeric_tester(self, calc_type, calc_value, data_type, used_locale):
| try:
set_locale = setlocale(LC_NUMERIC)
except Error:
set_locale = '<not able to determine>'
known_value = known_numerics.get(used_locale, ('', ''))[(data_type == 'thousands_sep')]
if (known_value and calc_value):
self.assertEqual(calc_value, known_value, (self.lc_numeri... |
'Test that an iterator is the same after pickling, also when part-consumed'
| def pickletest(self, it, stop=4, take=1, compare=None):
| def expand(it, i=0):
if (i > 10):
raise RuntimeError('infinite recursion encountered')
if isinstance(it, str):
return it
try:
l = list(islice(it, stop))
except TypeError:
return it
return [expand(e, (i + 1)) for e in l]
... |
'Wow, I have no function!'
| def __init__():
| pass
|
'Return say_no()'
| def get_answer(self):
| return self.say_no()
|
'Return self.get_answer()'
| def is_it_true(self):
| return self.get_answer()
|
'Check that compiling code raises SyntaxError with errtext.
errtest is a regular expression that must be present in the
test of the exception raised. If subclass is specified it
is the expected subclass of SyntaxError (e.g. IndentationError).'
| def _check_error(self, code, errtext, filename='<testcase>', mode='exec', subclass=None):
| try:
compile(code, filename, mode)
except SyntaxError as err:
if (subclass and (not isinstance(err, subclass))):
self.fail(('SyntaxError is not a %s' % subclass.__name__))
mo = re.search(errtext, str(err))
if (mo is None):
self.fail(("SyntaxErr... |
'Compare the result of Python\'s builtin correctly rounded
string->float conversion (using float) to a pure Python
correctly rounded string->float implementation. Fail if the
two methods give different results.'
| def check_strtod(self, s):
| try:
fs = float(s)
except OverflowError:
got = ('-inf' if (s[0] == '-') else 'inf')
except MemoryError:
got = 'memory error'
else:
got = fs.hex()
expected = strtod(s)
self.assertEqual(expected, got, 'Incorrectly rounded str->float conversion for ... |
'Issue21291: Popen.wait() needs to be threadsafe for returncode.'
| @unittest.skipIf((threading is None), 'threading required')
def test_threadsafe_wait(self):
| proc = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(12)'])
self.assertEqual(proc.returncode, None)
results = []
def kill_proc_timer_thread():
results.append(('thread-start-poll-result', proc.poll()))
proc.kill()
proc.wait()
results.append(('threa... |
'Test for the fork() failure fd leak reported in issue16327.'
| @unittest.skipUnless(os.path.isdir(('/proc/%d/fd' % os.getpid())), 'Linux specific')
def test_failed_child_execute_fd_leak(self):
| fd_directory = ('/proc/%d/fd' % os.getpid())
fds_before_popen = os.listdir(fd_directory)
with self.assertRaises(PopenTestException):
PopenExecuteChildRaises([sys.executable, '-c', 'pass'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
fds_after_exception = os.listdir(fd_... |
'Test error in the child raised in the parent for a bad cwd.'
| def test_exception_cwd(self):
| desired_exception = self._get_chdir_exception()
try:
p = subprocess.Popen([sys.executable, '-c', ''], cwd=self._nonexistent_dir)
except OSError as e:
self.assertEqual(desired_exception.errno, e.errno)
self.assertEqual(desired_exception.strerror, e.strerror)
else:
self.fai... |
'Test error in the child raised in the parent for a bad executable.'
| def test_exception_bad_executable(self):
| desired_exception = self._get_chdir_exception()
try:
p = subprocess.Popen([sys.executable, '-c', ''], executable=self._nonexistent_dir)
except OSError as e:
self.assertEqual(desired_exception.errno, e.errno)
self.assertEqual(desired_exception.strerror, e.strerror)
else:
s... |
'Test error in the child raised in the parent for a bad args[0].'
| def test_exception_bad_args_0(self):
| desired_exception = self._get_chdir_exception()
try:
p = subprocess.Popen([self._nonexistent_dir, '-c', ''])
except OSError as e:
self.assertEqual(desired_exception.errno, e.errno)
self.assertEqual(desired_exception.strerror, e.strerror)
else:
self.fail(('Expected OSEr... |
'Issue16140: Don\'t double close pipes on preexec error.'
| @unittest.skipIf((not os.path.exists('/dev/zero')), '/dev/zero required.')
def test_preexec_errpipe_does_not_double_close_pipes(self):
| def raise_it():
raise subprocess.SubprocessError('force the _execute_child() errpipe_data path.')
with self.assertRaises(subprocess.SubprocessError):
self._TestExecuteChildPopen(self, [sys.executable, '-c', 'pass'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIP... |
'Issue #15798: Popen should work when stdio fds are available.'
| def test_small_errpipe_write_fd(self):
| new_stdin = os.dup(0)
new_stdout = os.dup(1)
try:
os.close(0)
os.close(1)
subprocess.Popen([sys.executable, '-c', "print('AssertionError:0:CLOEXEC failure.')"]).wait()
finally:
os.dup2(new_stdin, 0)
os.dup2(new_stdout, 1)
os.close(new_stdin)
os.... |
'Confirm that issue21618 is fixed (may fail under valgrind).'
| @unittest.skipIf((sys.platform.startswith('freebsd') and (os.stat('/dev').st_dev == os.stat('/dev/fd').st_dev)), 'Requires fdescfs mounted on /dev/fd on FreeBSD.')
def test_close_fds_when_max_fd_is_lowered(self):
| fd_status = support.findfile('fd_status.py', subdir='subprocessdata')
p = subprocess.Popen([sys.executable, '-c', textwrap.dedent(('\n import os, resource, subprocess, sys, textwrap\n open_fds = set()\n ... |
'Perform TestCase-specific configuration on a function before testing.
By default, this does nothing. Example usage: spinning a function so
that a JIT will optimize it. Subclasses should override this as needed.
Args:
func: function to configure.
*args: any arguments that should be passed to func, if calling it.
Return... | def configure_func(self, func, *args):
| pass
|
'Fail unless floats x and y are identical, in the sense that:
(1) both x and y are nans, or
(2) both x and y are infinities, with the same sign, or
(3) both x and y are zeros, with the same sign, or
(4) x and y are both finite and nonzero, and x == y'
| def assertFloatIdentical(self, x, y):
| msg = 'floats {!r} and {!r} are not identical'
if (math.isnan(x) or math.isnan(y)):
if (math.isnan(x) and math.isnan(y)):
return
elif (x == y):
if (x != 0.0):
return
elif (math.copysign(1.0, x) == math.copysign(1.0, y)):
return
... |
'Fail unless complex numbers x and y have equal values and signs.
In particular, if x and y both have real (or imaginary) part
zero, but the zeros have different signs, this test will fail.'
| def assertComplexIdentical(self, x, y):
| self.assertFloatIdentical(x.real, y.real)
self.assertFloatIdentical(x.imag, y.imag)
|
'Fail if the two floating-point numbers are not almost equal.
Determine whether floating-point values a and b are equal to within
a (small) rounding error. The default values for rel_err and
abs_err are chosen to be suitable for platforms where a float is
represented by an IEEE 754 double. They allow an error of betw... | def rAssertAlmostEqual(self, a, b, rel_err=2e-15, abs_err=5e-323, msg=None):
| if math.isnan(a):
if math.isnan(b):
return
self.fail((msg or '{!r} should be nan'.format(b)))
if math.isinf(a):
if (a == b):
return
self.fail((msg or 'finite result where infinity expected: expected {!r}, got {!r}'.format(a... |
'Verify the module has the expected value for __package__ after
passing through set_package.'
| def verify(self, module, expect):
| fxn = (lambda : module)
wrapped = self.util.set_package(fxn)
with warnings.catch_warnings():
warnings.simplefilter('ignore', DeprecationWarning)
wrapped()
self.assertTrue(hasattr(module, '__package__'))
self.assertEqual(expect, module.__package__)
|
'Abstract out boilerplace for setting up for an import test.'
| def relative_import_test(self, create, globals_, callback):
| uncache_names = []
for name in create:
if (not name.endswith('.__init__')):
uncache_names.append(name)
else:
uncache_names.append(name[:(- len('.__init__'))])
with util.mock_spec(*create) as importer:
with util.import_state(meta_path=[importer]):
f... |
'Look for a module with matching and non-matching sensitivity.'
| def sensitivity_test(self):
| sensitive_pkg = 'sensitive.{0}'.format(self.name)
insensitive_pkg = 'insensitive.{0}'.format(self.name.lower())
context = source_util.create_modules(insensitive_pkg, sensitive_pkg)
with context as mapping:
sensitive_path = os.path.join(mapping['.root'], 'sensitive')
insensitive_path = os... |
'Verify that the module matches against what it should have.'
| def verify(self, module):
| self.assertIsInstance(module, types.ModuleType)
for (attr, value) in self.verification.items():
self.assertEqual(getattr(module, attr), value)
self.assertIn(module.__name__, sys.modules)
|
'Run the specified code in Python (in a new child process) and read the
output from the standard error or from a file (if filename is set).
Return the output lines as a list.
Strip the reference count from the standard error for Python debug
build, and replace "Current thread 0x00007f8d8fbd9700" by "Current
thread XXX"... | def get_output(self, code, filename=None):
| code = dedent(code).strip()
with support.SuppressCrashReport():
process = script_helper.spawn_python('-c', code)
(stdout, stderr) = process.communicate()
exitcode = process.wait()
output = support.strip_python_stderr(stdout)
output = output.decode('ascii', 'backslashreplace')
if file... |
'Check that the fault handler for fatal errors is enabled and check the
traceback from the child process output.
Raise an error if the output doesn\'t match the expected format.'
| def check_fatal_error(self, code, line_number, name_regex, filename=None, all_threads=True, other_regex=None):
| if all_threads:
header = 'Current thread XXX (most recent call first)'
else:
header = 'Stack (most recent call first)'
regex = '\n ^Fatal Python error: {name}\n\n ... |
'Explicitly call dump_traceback() function and check its output.
Raise an error if the output doesn\'t match the expected format.'
| def check_dump_traceback(self, filename):
| code = '\n import faulthandler\n\n def funcB():\n if {has_filename}:\n ... |
'Call explicitly dump_traceback(all_threads=True) and check the output.
Raise an error if the output doesn\'t match the expected format.'
| @unittest.skipIf((not HAVE_THREADS), 'need threads')
def check_dump_traceback_threads(self, filename):
| code = '\n import faulthandler\n from threading import Thread, Event\n import time\n\n def dump():\n ... |
'Check how many times the traceback is written in timeout x 2.5 seconds,
or timeout x 3.5 seconds if cancel is True: 1, 2 or 3 times depending
on repeat and cancel options.
Raise an error if the output doesn\'t match the expect format.'
| def _check_dump_traceback_later(self, repeat, cancel, filename, loops):
| timeout_str = str(datetime.timedelta(seconds=TIMEOUT))
code = '\n import faulthandler\n import time\n\n def func(timeout, repeat, cancel, file, loops)... |
'Register a handler displaying the traceback on a user signal. Raise the
signal and check the written traceback.
If chain is True, check that the previous signal handler is called.
Raise an error if the output doesn\'t match the expected format.'
| @unittest.skipIf((not hasattr(faulthandler, 'register')), 'need faulthandler.register')
def check_register(self, filename=False, all_threads=False, unregister=False, chain=False):
| signum = signal.SIGUSR1
code = '\n import faulthandler\n import os\n import signal\n import sys\n\n ... |
'This method allows the server to explicitly indicate that
it wants the client thread to proceed. This is useful if the
server is about to execute a blocking routine that is
dependent upon the client thread during its setup routine.'
| def serverExplicitReady(self):
| self.server_ready.set()
|
'Bind server socket and set self.serv_addr to its address.'
| def bindServer(self):
| self.bindSock(self.serv)
self.serv_addr = self.serv.getsockname()
|
'Return a new socket for use as client.'
| def newClientSocket(self):
| return self.newSocket()
|
'Bind client socket and set self.cli_addr to its address.'
| def bindClient(self):
| self.bindSock(self.cli)
self.cli_addr = self.cli.getsockname()
|
'Build a CAN frame.'
| @classmethod
def build_can_frame(cls, can_id, data):
| can_dlc = len(data)
data = data.ljust(8, '\x00')
return struct.pack(cls.can_frame_fmt, can_id, can_dlc, data)
|
'Dissect a CAN frame.'
| @classmethod
def dissect_can_frame(cls, frame):
| (can_id, can_dlc, data) = struct.unpack(cls.can_frame_fmt, frame)
return (can_id, can_dlc, data[:can_dlc])
|
'Return a socket which times out on connect'
| @contextlib.contextmanager
def mocked_socket_module(self):
| old_socket = socket.socket
socket.socket = self.MockSocket
try:
(yield)
finally:
socket.socket = old_socket
|
'Test data splitting with posix parser'
| def testSplitPosix(self):
| self.splitTest(self.posix_data, comments=True)
|
'Test compatibility interface'
| def testCompat(self):
| for i in range(len(self.data)):
l = self.oldSplit(self.data[i][0])
self.assertEqual(l, self.data[i][1:], ('%s: %s != %s' % (self.data[i][0], l, self.data[i][1:])))
|
'Add an event to the log.'
| def add_event(self, event, frame=None):
| if (frame is None):
frame = sys._getframe(1)
try:
frameno = self.frames.index(frame)
except ValueError:
frameno = len(self.frames)
self.frames.append(frame)
self.events.append((frameno, event, ident(frame)))
|
'Remove calls to add_event().'
| def get_events(self):
| disallowed = [ident(self.add_event.__func__), ident(ident)]
self.frames = None
return [item for item in self.events if (item[2] not in disallowed)]
|
'Records \'timer\' and returns self as callable timer.'
| def wrap_timer(self, timer):
| self.saved_timer = timer
return self
|
'SF bug #1486663 -- this used to erroneously raise a TypeError'
| def test_keywords_in_subclass(self):
| SetSubclassWithKeywordArgs(newarg=1)
|
'Helper function to make a list of random numbers'
| def randomlist(self, n):
| return [self.gen.random() for i in range(n)]
|
'Set each of the callbacks defined on handler and named in
self.handler_names on the given parser.'
| def _hookup_callbacks(self, parser, handler):
| for name in self.handler_names:
setattr(parser, name, getattr(handler, name))
|
'If UseForeignDTD is passed True and a document without an external
entity reference is parsed, ExternalEntityRefHandler is first called
with None for the public and system ids.'
| def test_use_foreign_dtd(self):
| handler_call_args = []
def resolve_entity(context, base, system_id, public_id):
handler_call_args.append((public_id, system_id))
return 1
parser = expat.ParserCreate()
parser.UseForeignDTD(True)
parser.SetParamEntityParsing(expat.XML_PARAM_ENTITY_PARSING_ALWAYS)
parser.ExternalEn... |
'If UseForeignDTD is passed True and a document with an external
entity reference is parsed, ExternalEntityRefHandler is called with
the public and system ids from the document.'
| def test_ignore_use_foreign_dtd(self):
| handler_call_args = []
def resolve_entity(context, base, system_id, public_id):
handler_call_args.append((public_id, system_id))
return 1
parser = expat.ParserCreate()
parser.UseForeignDTD(True)
parser.SetParamEntityParsing(expat.XML_PARAM_ENTITY_PARSING_ALWAYS)
parser.ExternalEn... |
'Runs a test in the embedded interpreter'
| def run_embedded_interpreter(self, *args):
| cmd = [self.test_exe]
cmd.extend(args)
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(out, err) = p.communicate()
self.assertEqual(p.returncode, 0, ('bad returncode %d, stderr is %r' % (p.returncode, err)))
return (out.decode('latin1'), err.decode('lati... |
'If this test failed, you probably added a new "format unit"
in Python/getargs.c, but neglected to update our poor friend
skipitem() in the same file. (If so, shame on you!)
With a few exceptions**, this function brute-force tests all
printable ASCII*** characters (32 to 126 inclusive) as format units,
checking to see... | def test_skipitem(self):
| empty_tuple = ()
tuple_1 = (0,)
dict_b = {'b': 1}
keywords = ['a', 'b']
for i in range(32, 127):
c = chr(i)
if (c in '()e|$'):
continue
format = (c + 'i')
try:
_testcapi.parse_tuple_and_keywords(tuple_1, dict_b, format.encode('ascii'), keywords... |
'Mocks the select.select() call to raise EINTR for first call'
| @contextlib.contextmanager
def mocked_select_module(self):
| old_select = select.select
class MockSelect:
def __init__(self):
self.called = 0
def __call__(self, *args):
self.called += 1
if (self.called == 1):
raise OSError(errno.EINTR, os.strerror(errno.EINTR))
else:
return ol... |
'Shut down the open object'
| def tearDown(self):
| self.returned_obj.close()
os.remove(support.TESTFN)
|
'Creates a new temporary file containing the specified data,
registers the file for deletion during the test fixture tear down, and
returns the absolute path of the file.'
| def createNewTempFile(self, data=''):
| (newFd, newFilePath) = tempfile.mkstemp()
try:
self.registerFileForCleanUp(newFilePath)
newFile = os.fdopen(newFd, 'wb')
newFile.write(data)
newFile.close()
finally:
try:
newFile.close()
except:
pass
return newFilePath
|
'Helper method for testing different input types.
\'given\' must lead to only the pairs:
* 1st, 1
* 2nd, 2
* 3rd, 3
Test cannot assume anything about order. Docs make no guarantee and
have possible dictionary input.'
| def help_inputtype(self, given, test_type):
| expect_somewhere = ['1st=1', '2nd=2', '3rd=3']
result = urllib.parse.urlencode(given)
for expected in expect_somewhere:
self.assertIn(expected, result, ('testing %s: %s not found in %s' % (test_type, expected, result)))
self.assertEqual(result.count('&'), 2, ("testing %s: ... |
'Some of password examples are not sensible, but it is added to
confirming to RFC2617 and addressing issue4675.'
| def test_splitpasswd(self):
| self.assertEqual(('user', 'ab'), urllib.parse.splitpasswd('user:ab'))
self.assertEqual(('user', 'a\nb'), urllib.parse.splitpasswd('user:a\nb'))
self.assertEqual(('user', 'a DCTB b'), urllib.parse.splitpasswd('user:a DCTB b'))
self.assertEqual(('user', 'a\rb'), urllib.parse.splitpasswd('user:a\rb'))
... |
'Test the urllib.request.thishost utility function returns a tuple'
| def test_thishost(self):
| self.assertIsInstance(urllib.request.thishost(), tuple)
|
'Assert the options are what we expected when parsing arguments.
Otherwise, fail with a nicely formatted message.
Keyword arguments:
args -- A list of arguments to parse with OptionParser.
expected_opts -- The options expected.
expected_positional_args -- The positional arguments expected.
Returns the options and posit... | def assertParseOK(self, args, expected_opts, expected_positional_args):
| (options, positional_args) = self.parser.parse_args(args)
optdict = vars(options)
self.assertEqual(optdict, expected_opts, ('\nOptions are %(optdict)s.\nShould be %(expected_opts)s.\nArgs were %(args)s.' % locals()))
self.assertEqual(positional_args, expected_positional_args, ('\nPosit... |
'Assert that the expected exception is raised when calling a
function, and that the right error message is included with
that exception.
Arguments:
func -- the function to call
args -- positional arguments to `func`
kwargs -- keyword arguments to `func`
expected_exception -- exception that should be raised
expected_mes... | def assertRaises(self, func, args, kwargs, expected_exception, expected_message):
| if (args is None):
args = ()
if (kwargs is None):
kwargs = {}
try:
func(*args, **kwargs)
except expected_exception as err:
actual_message = str(err)
if isinstance(expected_message, retype):
self.assertTrue(expected_message.search(actual_message), ("exp... |
'Assert the parser fails with the expected message. Caller
must ensure that self.parser is an InterceptingOptionParser.'
| def assertParseFail(self, cmdline_args, expected_output):
| try:
self.parser.parse_args(cmdline_args)
except InterceptedError as err:
self.assertEqual(err.error_message, expected_output)
else:
self.assertFalse('expected parse failure')
|
'Assert the parser prints the expected output on stdout.'
| def assertOutput(self, cmdline_args, expected_output, expected_status=0, expected_error=None):
| save_stdout = sys.stdout
try:
try:
sys.stdout = StringIO()
self.parser.parse_args(cmdline_args)
finally:
output = sys.stdout.getvalue()
sys.stdout = save_stdout
except InterceptedError as err:
self.assertTrue(isinstance(output, str), ('... |
'Assert that TypeError is raised when executing func.'
| def assertTypeError(self, func, expected_message, *args):
| self.assertRaises(func, args, None, TypeError, expected_message)
|
'Check for cases where compressed data is larger than original.'
| def test_low_compression(self):
| with zipfile.ZipFile(TESTFN2, 'w', self.compression) as zipfp:
zipfp.writestr('strfile', '12')
with zipfile.ZipFile(TESTFN2, 'r', self.compression) as zipfp:
with zipfp.open('strfile') as openobj:
self.assertEqual(openobj.read(1), '1')
self.assertEqual(openobj.read(1), '2... |
'Test appending to an existing zipfile.'
| def test_append_to_zip_file(self):
| with zipfile.ZipFile(TESTFN2, 'w', zipfile.ZIP_STORED) as zipfp:
zipfp.write(TESTFN, TESTFN)
with zipfile.ZipFile(TESTFN2, 'a', zipfile.ZIP_STORED) as zipfp:
zipfp.writestr('strfile', self.data)
self.assertEqual(zipfp.namelist(), [TESTFN, 'strfile'])
|
'Test appending to an existing file that is not a zipfile.'
| def test_append_to_non_zip_file(self):
| data = ('I am not a ZipFile!' * 10)
with open(TESTFN2, 'wb') as f:
f.write(data)
with zipfile.ZipFile(TESTFN2, 'a', zipfile.ZIP_STORED) as zipfp:
zipfp.write(TESTFN, TESTFN)
with open(TESTFN2, 'rb') as f:
f.seek(len(data))
with zipfile.ZipFile(f, 'r') as zipfp... |
'Check that calling ZipFile.write without arcname specified
produces the expected result.'
| def test_write_default_name(self):
| with zipfile.ZipFile(TESTFN2, 'w') as zipfp:
zipfp.write(TESTFN)
with open(TESTFN, 'rb') as f:
self.assertEqual(zipfp.read(TESTFN), f.read())
|
'Check that trying to call write() on a readonly ZipFile object
raises a RuntimeError.'
| def test_write_to_readonly(self):
| with zipfile.ZipFile(TESTFN2, mode='w') as zipfp:
zipfp.writestr('somefile.txt', 'bogus')
with zipfile.ZipFile(TESTFN2, mode='r') as zipfp:
self.assertRaises(RuntimeError, zipfp.write, TESTFN)
|
'Check that files within a Zip archive can have different
compression options.'
| def test_per_file_compression(self):
| with zipfile.ZipFile(TESTFN2, 'w') as zipfp:
zipfp.write(TESTFN, 'storeme', zipfile.ZIP_STORED)
zipfp.write(TESTFN, 'deflateme', zipfile.ZIP_DEFLATED)
sinfo = zipfp.getinfo('storeme')
dinfo = zipfp.getinfo('deflateme')
self.assertEqual(sinfo.compress_type, zipfile.ZIP_STORED)... |
'Test combination of path fixing and windows name sanitization.'
| @unittest.skipIf((os.path.sep != '\\'), 'Requires \\ as path separator.')
def test_extract_hackers_arcnames_windows_only(self):
| windows_hacknames = [('..\\foo\\bar', 'foo/bar'), ('..\\/foo\\/bar', 'foo/bar'), ('foo/\\..\\/bar', 'foo/bar'), ('foo\\/../\\bar', 'foo/bar'), ('C:foo/bar', 'foo/bar'), ('C:/foo/bar', 'foo/bar'), ('C://foo/bar', 'foo/bar'), ('C:\\foo\\bar', 'foo/bar'), ('//conky/mountpoint/foo/bar', 'foo/bar'), ('\\\\conky\\mountpo... |
'Check that the zipfile is closed after the \'with\' block.'
| def test_close(self):
| with zipfile.ZipFile(TESTFN2, 'w') as zipfp:
for (fpath, fdata) in SMALL_TEST_DATA:
zipfp.writestr(fpath, fdata)
self.assertIsNotNone(zipfp.fp, 'zipfp is not open')
self.assertIsNone(zipfp.fp, 'zipfp is not closed')
with zipfile.ZipFile(TESTFN2, 'r') as zipf... |
'Check that the zipfile is closed if an exception is raised in the
\'with\' block.'
| def test_close_on_exception(self):
| with zipfile.ZipFile(TESTFN2, 'w') as zipfp:
for (fpath, fdata) in SMALL_TEST_DATA:
zipfp.writestr(fpath, fdata)
try:
with zipfile.ZipFile(TESTFN2, 'r') as zipfp2:
raise zipfile.BadZipFile()
except zipfile.BadZipFile:
self.assertIsNone(zipfp2.fp, 'zipfp is ... |
'Check that is_zipfile() correctly identifies non-zip files.'
| def test_is_zip_erroneous_file(self):
| with open(TESTFN, 'w') as fp:
fp.write('this is not a legal zip file\n')
self.assertFalse(zipfile.is_zipfile(TESTFN))
with open(TESTFN, 'rb') as fp:
self.assertFalse(zipfile.is_zipfile(fp))
fp = io.BytesIO()
fp.write('this is not a legal zip file\n... |
'Check that zipfiles with missing bytes at the end raise BadZipFile.'
| def test_damaged_zipfile(self):
| fp = io.BytesIO()
with zipfile.ZipFile(fp, mode='w') as zipf:
zipf.writestr('foo.txt', 'O, for a Muse of Fire!')
zipfiledata = fp.getvalue()
for N in range(len(zipfiledata)):
fp = io.BytesIO(zipfiledata[:N])
self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, fp... |
'Check that is_zipfile() correctly identifies zip files.'
| def test_is_zip_valid_file(self):
| with zipfile.ZipFile(TESTFN, mode='w') as zipf:
zipf.writestr('foo.txt', 'O, for a Muse of Fire!')
self.assertTrue(zipfile.is_zipfile(TESTFN))
with open(TESTFN, 'rb') as fp:
self.assertTrue(zipfile.is_zipfile(fp))
fp.seek(0, 0)
zip_contents = fp.read()
fp =... |
'Verify that testzip() doesn\'t swallow inappropriate exceptions.'
| def test_closed_zip_raises_RuntimeError(self):
| data = io.BytesIO()
with zipfile.ZipFile(data, mode='w') as zipf:
zipf.writestr('foo.txt', 'O, for a Muse of Fire!')
self.assertRaises(RuntimeError, zipf.read, 'foo.txt')
self.assertRaises(RuntimeError, zipf.open, 'foo.txt')
self.assertRaises(RuntimeError, zipf.testzip)
se... |
'Check that bad modes passed to ZipFile constructor are caught.'
| def test_bad_constructor_mode(self):
| self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, 'q')
|
'Check that bad modes passed to ZipFile.open are caught.'
| def test_bad_open_mode(self):
| with zipfile.ZipFile(TESTFN, mode='w') as zipf:
zipf.writestr('foo.txt', 'O, for a Muse of Fire!')
with zipfile.ZipFile(TESTFN, mode='r') as zipf:
zipf.read('foo.txt')
self.assertRaises(RuntimeError, zipf.open, 'foo.txt', 'q')
|
'Check that calling read(0) on a ZipExtFile object returns an empty
string and doesn\'t advance file pointer.'
| def test_read0(self):
| with zipfile.ZipFile(TESTFN, mode='w') as zipf:
zipf.writestr('foo.txt', 'O, for a Muse of Fire!')
with zipf.open('foo.txt') as f:
for i in range(FIXEDTEST_SIZE):
self.assertEqual(f.read(0), '')
self.assertEqual(f.read(), 'O, for a Muse... |
'Check that attempting to call open() for an item that doesn\'t
exist in the archive raises a RuntimeError.'
| def test_open_non_existent_item(self):
| with zipfile.ZipFile(TESTFN, mode='w') as zipf:
self.assertRaises(KeyError, zipf.open, 'foo.txt', 'r')
|
'Check that bad compression methods passed to ZipFile.open are
caught.'
| def test_bad_compression_mode(self):
| self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, 'w', (-1))
|
'Check that a filename containing a null byte is properly
terminated.'
| def test_null_byte_in_filename(self):
| with zipfile.ZipFile(TESTFN, mode='w') as zipf:
zipf.writestr('foo.txt\x00qqq', 'O, for a Muse of Fire!')
self.assertEqual(zipf.namelist(), ['foo.txt'])
|
'Check that ZIP internal structure sizes are calculated correctly.'
| def test_struct_sizes(self):
| self.assertEqual(zipfile.sizeEndCentDir, 22)
self.assertEqual(zipfile.sizeCentralDir, 46)
self.assertEqual(zipfile.sizeEndCentDir64, 56)
self.assertEqual(zipfile.sizeEndCentDir64Locator, 20)
|
'Check that comments on the archive are handled properly.'
| def test_comments(self):
| with zipfile.ZipFile(TESTFN, mode='w') as zipf:
self.assertEqual(zipf.comment, '')
zipf.writestr('foo.txt', 'O, for a Muse of Fire!')
with zipfile.ZipFile(TESTFN, mode='r') as zipfr:
self.assertEqual(zipfr.comment, '')
comment = 'Bravely taking to his feet,... |
'If an extra field in the header is less than 4 bytes, skip it.'
| def test_zipfile_with_short_extra_field(self):
| zipdata = 'PK\x03\x04\x14\x00\x00\x00\x00\x00\x93\x9b\xad@\x8b\x9e\xd9\xd3\x01\x00\x00\x00\x01\x00\x00\x00\x03\x00\x03\x00abc\x00\x00\x00APK\x01\x02\x14\x03\x14\x00\x00\x00\x00\x00\x93\x9b\xad@\x8b\x9e\xd9\xd3\x01\x00\x00\x00\x01\x00\x00\x00\x03\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00abc... |
'Tests that files with bad CRCs return their name from testzip.'
| def test_testzip_with_bad_crc(self):
| zipdata = self.zip_with_bad_crc
with zipfile.ZipFile(io.BytesIO(zipdata), mode='r') as zipf:
self.assertEqual('afile', zipf.testzip())
|
'Tests that files with bad CRCs raise a BadZipFile exception when read.'
| def test_read_with_bad_crc(self):
| zipdata = self.zip_with_bad_crc
with zipfile.ZipFile(io.BytesIO(zipdata), mode='r') as zipf:
self.assertRaises(zipfile.BadZipFile, zipf.read, 'afile')
with zipfile.ZipFile(io.BytesIO(zipdata), mode='r') as zipf:
with zipf.open('afile', 'r') as corrupt_file:
self.assertRaises(zipf... |
'A context manager to use around all finalization tests.'
| @classmethod
@contextlib.contextmanager
def test(cls):
| with support.disable_gc():
cls.del_calls.clear()
cls.tp_del_calls.clear()
NonGCSimpleBase._cleaning = False
try:
(yield)
if cls.errors:
raise cls.errors[0]
finally:
NonGCSimpleBase._cleaning = True
cls._cleanup()... |
'PEP 442 finalizer. Record that this was called, check the
object is in a sane state, and invoke a side effect.'
| def __del__(self):
| try:
if (not self._cleaning):
self.del_calls.append(id(self))
self.check_sanity()
self.side_effect()
except Exception as e:
self.errors.append(e)
|
'Resurrect self by storing self in a class-wide list.'
| def side_effect(self):
| self.survivors.append(self)
|
'Explicitly break the reference cycle.'
| def side_effect(self):
| self.ref = None
|
'Explicitly break the reference cycle.'
| def side_effect(self):
| self.suicided = True
self.left = None
self.right = None
|
'Legacy (pre-PEP 442) finalizer, mapped to a tp_del slot.'
| def __tp_del__(self):
| try:
if (not self._cleaning):
self.tp_del_calls.append(id(self))
self.check_sanity()
self.side_effect()
except Exception as e:
self.errors.append(e)
|
'Resurrect self by storing self in a class-wide list.'
| def side_effect(self):
| self.survivors.append(self)
|
'Create a new DocTest containing the given examples. The
DocTest\'s globals are initialized with a copy of `globs`.'
| def __init__(self, examples, globs, name, filename, lineno, docstring):
| assert (not isinstance(examples, str)), 'DocTest no longer accepts str; use DocTestParser instead'
self.examples = examples
self.docstring = docstring
self.globs = globs.copy()
self.name = name
self.filename = filename
self.lineno = lineno
|
'Divide the given string into examples and intervening text,
and return them as a list of alternating Examples and strings.
Line numbers for the Examples are 0-based. The optional
argument `name` is a name identifying this string, and is only
used for error messages.'
| def parse(self, string, name='<string>'):
| string = string.expandtabs()
min_indent = self._min_indent(string)
if (min_indent > 0):
string = '\n'.join([l[min_indent:] for l in string.split('\n')])
output = []
(charno, lineno) = (0, 0)
for m in self._EXAMPLE_RE.finditer(string):
output.append(string[charno:m.start()])
... |
'Extract all doctest examples from the given string, and
collect them into a `DocTest` object.
`globs`, `name`, `filename`, and `lineno` are attributes for
the new `DocTest` object. See the documentation for `DocTest`
for more information.'
| def get_doctest(self, string, globs, name, filename, lineno):
| return DocTest(self.get_examples(string, name), globs, name, filename, lineno, string)
|
'Extract all doctest examples from the given string, and return
them as a list of `Example` objects. Line numbers are
0-based, because it\'s most common in doctests that nothing
interesting appears on the same line as opening triple-quote,
and so the first interesting line is called "line 1" then.
The optional argumen... | def get_examples(self, string, name='<string>'):
| return [x for x in self.parse(string, name) if isinstance(x, Example)]
|
'Given a regular expression match from `_EXAMPLE_RE` (`m`),
return a pair `(source, want)`, where `source` is the matched
example\'s source code (with prompts and indentation stripped);
and `want` is the example\'s expected output (with indentation
stripped).
`name` is the string\'s name, and `lineno` is the line numbe... | def _parse_example(self, m, name, lineno):
| indent = len(m.group('indent'))
source_lines = m.group('source').split('\n')
self._check_prompt_blank(source_lines, indent, name, lineno)
self._check_prefix(source_lines[1:], ((' ' * indent) + '.'), name, lineno)
source = '\n'.join([sl[(indent + 4):] for sl in source_lines])
want = m.group('w... |
'Return a dictionary containing option overrides extracted from
option directives in the given source string.
`name` is the string\'s name, and `lineno` is the line number
where the example starts; both are used for error messages.'
| def _find_options(self, source, name, lineno):
| options = {}
for m in self._OPTION_DIRECTIVE_RE.finditer(source):
option_strings = m.group(1).replace(',', ' ').split()
for option in option_strings:
if ((option[0] not in '+-') or (option[1:] not in OPTIONFLAGS_BY_NAME)):
raise ValueError(('line %r of the... |
'Return the minimum indentation of any non-blank line in `s`'
| def _min_indent(self, s):
| indents = [len(indent) for indent in self._INDENT_RE.findall(s)]
if (len(indents) > 0):
return min(indents)
else:
return 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.