desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Check that a buffered read, when it gets interrupted (either returning a partial result or EINTR), properly invokes the signal handler and retries if the latter returned successfully.'
def check_interrupted_read_retry(self, decode, **fdopen_kwargs):
(r, w) = os.pipe() fdopen_kwargs['closefd'] = False def alarm_handler(sig, frame): os.write(w, 'bar') signal.signal(signal.SIGALRM, alarm_handler) try: rio = self.io.open(r, **fdopen_kwargs) os.write(w, 'foo') signal.alarm(1) self.assertEqual(decode(rio.read(6...
'Check that a buffered write, when it gets interrupted (either returning a partial result or EINTR), properly invokes the signal handler and retries if the latter returned successfully.'
@unittest.skipUnless(threading, 'Threading required for this test.') def check_interrupted_write_retry(self, item, **fdopen_kwargs):
select = support.import_module('select') N = support.PIPE_MAX_SIZE (r, w) = os.pipe() fdopen_kwargs['closefd'] = False read_results = [] write_finished = False def _read(): while (not write_finished): while (r in select.select([r], [], [], 1.0)[0]): s = os...
'Minimal test of DOMEventStream.parse()'
def test_parse(self):
handler = pulldom.parse(tstfile) self.addCleanup(handler.stream.close) list(handler) with open(tstfile, 'rb') as fin: list(pulldom.parse(fin))
'Test DOMEventStream parsing semantics.'
def test_parse_semantics(self):
items = pulldom.parseString(SMALL_SAMPLE) (evt, node) = next(items) self.assertTrue(hasattr(node, 'createElement')) self.assertEqual(pulldom.START_DOCUMENT, evt) (evt, node) = next(items) self.assertEqual(pulldom.START_ELEMENT, evt) self.assertEqual('html', node.tagName) self.assertEqual...
'Ensure expandItem works as expected.'
def test_expandItem(self):
items = pulldom.parseString(SMALL_SAMPLE) for (evt, item) in items: if ((evt == pulldom.START_ELEMENT) and (item.tagName == 'title')): items.expandNode(item) self.assertEqual(1, len(item.childNodes)) break else: self.fail('No "title" element detec...
'PullDOM does not receive "comment" events.'
@unittest.expectedFailure def test_comment(self):
items = pulldom.parseString(SMALL_SAMPLE) for (evt, _) in items: if (evt == pulldom.COMMENT): break else: self.fail('No comment was encountered')
'PullDOM does not receive "end-document" events.'
@unittest.expectedFailure def test_end_document(self):
items = pulldom.parseString(SMALL_SAMPLE) for (evt, node) in items: if ((evt == pulldom.END_ELEMENT) and (node.tagName == 'html')): break try: (evt, node) = next(items) self.assertEqual(pulldom.END_DOCUMENT, evt) except StopIteration: self.fail('Ran out ...
'Test some of the hard-to-reach parts of PullDOM.'
def test_thorough_parse(self):
self._test_thorough(pulldom.parse(None, parser=SAXExerciser()))
'SAX2DOM can"t handle a PI before the root element.'
@unittest.expectedFailure def test_sax2dom_fail(self):
pd = SAX2DOMTestHelper(None, SAXExerciser(), 12) self._test_thorough(pd)
'Test some of the hard-to-reach parts of SAX2DOM.'
def test_thorough_sax2dom(self):
pd = SAX2DOMTestHelper(None, SAX2DOMExerciser(), 12) self._test_thorough(pd, False)
'Test some of the hard-to-reach parts of the parser, using a mock parser.'
def _test_thorough(self, pd, before_root=True):
(evt, node) = next(pd) self.assertEqual(pulldom.START_DOCUMENT, evt) self.assertTrue(hasattr(node, 'createElement')) if before_root: (evt, node) = next(pd) self.assertEqual(pulldom.COMMENT, evt) self.assertEqual('a comment', node.data) (evt, node) = next(pd) se...
'Stub method. Does nothing.'
def stub(self, *args, **kwargs):
pass
'Ensure SAX2DOM can parse from a stream.'
def test_basic(self):
with io.StringIO(SMALL_SAMPLE) as fin: sd = SAX2DOMTestHelper(fin, xml.sax.make_parser(), len(SMALL_SAMPLE)) for (evt, node) in sd: if ((evt == pulldom.START_ELEMENT) and (node.tagName == 'html')): break self.assertGreater(len(node.childNodes), 0)
'Ensure SAX2DOM expands nodes as expected.'
def testSAX2DOM(self):
sax2dom = pulldom.SAX2DOM() sax2dom.startDocument() sax2dom.startElement('doc', {}) sax2dom.characters('text') sax2dom.startElement('subelm', {}) sax2dom.characters('text') sax2dom.endElement('subelm') sax2dom.characters('text') sax2dom.endElement('doc') sax2dom.endDocument() ...
'Returns the infile = ... line of code for the reader process. subclasseses should override this to test different IO objects.'
def _generate_infile_setup_code(self):
return 'import _io ;infile = _io.FileIO(sys.stdin.fileno(), "rb")'
'A common way to cleanup and fail with useful debug output. Kills the process if it is still running, collects remaining output and fails the test with an error message including the output. Args: why: Text to go after "Error from IO process" in the message. stdout, stderr: standard output and error from the process so...
def fail_with_process_info(self, why, stdout='', stderr='', communicate=True):
if (self._process.poll() is None): time.sleep(0.1) try: self._process.terminate() except OSError: pass if communicate: (stdout_end, stderr_end) = self._process.communicate() stdout += stdout_end stderr += stderr_end self.fail(('Error ...
'Generic buffered read method test harness to validate EINTR behavior. Also validates that Python signal handlers are run during the read. Args: data_to_write: String to write to the child process for reading before sending it a signal, confirming the signal was handled, writing a final newline and closing the infile p...
def _test_reading(self, data_to_write, read_and_verify_code):
infile_setup_code = self._generate_infile_setup_code() assert (len(data_to_write) < 512), 'data_to_write must fit in pipe buf.' self._process = subprocess.Popen([sys.executable, '-u', '-c', (((((('import signal, sys ;signal.signal(signal.SIGINT, lambda s, f: sys.stderr.wr...
'readline() must handle signals and not lose data.'
def test_readline(self):
self._test_reading(data_to_write='hello, world!', read_and_verify_code=self._READING_CODE_TEMPLATE.format(read_method_name='readline', expected='hello, world!\n'))
'readlines() must handle signals and not lose data.'
def test_readlines(self):
self._test_reading(data_to_write='hello\nworld!', read_and_verify_code=self._READING_CODE_TEMPLATE.format(read_method_name='readlines', expected=['hello\n', 'world!\n']))
'readall() must handle signals and not lose data.'
def test_readall(self):
self._test_reading(data_to_write='hello\nworld!', read_and_verify_code=self._READING_CODE_TEMPLATE.format(read_method_name='readall', expected='hello\nworld!\n')) self._test_reading(data_to_write='hello\nworld!', read_and_verify_code=self._READING_CODE_TEMPLATE.format(read_method_name='read', expected='hello\nw...
'Returns the infile = ... line of code to make a BufferedReader.'
def _generate_infile_setup_code(self):
return 'infile = open(sys.stdin.fileno(), "rb") ;import _io ;assert isinstance(infile, _io.BufferedReader)'
'BufferedReader.read() must handle signals and not lose data.'
def test_readall(self):
self._test_reading(data_to_write='hello\nworld!', read_and_verify_code=self._READING_CODE_TEMPLATE.format(read_method_name='read', expected='hello\nworld!\n'))
'Returns the infile = ... line of code to make a TextIOWrapper.'
def _generate_infile_setup_code(self):
return 'infile = open(sys.stdin.fileno(), "rt", newline=None) ;import _io ;assert isinstance(infile, _io.TextIOWrapper)'
'readline() must handle signals and not lose data.'
def test_readline(self):
self._test_reading(data_to_write='hello, world!', read_and_verify_code=self._READING_CODE_TEMPLATE.format(read_method_name='readline', expected='hello, world!\n'))
'readlines() must handle signals and not lose data.'
def test_readlines(self):
self._test_reading(data_to_write='hello\r\nworld!', read_and_verify_code=self._READING_CODE_TEMPLATE.format(read_method_name='readlines', expected=['hello\n', 'world!\n']))
'read() must handle signals and not lose data.'
def test_readall(self):
self._test_reading(data_to_write='hello\nworld!', read_and_verify_code=self._READING_CODE_TEMPLATE.format(read_method_name='read', expected='hello\nworld!\n'))
'Test an empty maildir mailbox'
def test_empty_maildir(self):
self.mbox = mailbox.Maildir(support.TESTFN) self.assertIsNone(self.mbox.next()) self.assertIsNone(self.mbox.next())
'Import a module and return a reference to it or None on failure.'
def _conditional_import_module(self, module_name):
try: exec ('import ' + module_name) except ImportError as error: if self._warn_on_extension_import: warnings.warn(('Did a C extension fail to compile? %s' % error)) return locals().get(module_name)
'succeed iff str is a valid piece of code'
def assertValid(self, str, symbol='single'):
if is_jython: code = compile_command(str, '<input>', symbol) self.assertTrue(code) if (symbol == 'single'): (d, r) = ({}, {}) saved_stdout = sys.stdout sys.stdout = io.StringIO() try: exec code in d exec compile(...
'succeed iff str is the start of a valid piece of code'
def assertIncomplete(self, str, symbol='single'):
self.assertEqual(compile_command(str, symbol=symbol), None)
'succeed iff str is the start of an invalid piece of code'
def assertInvalid(self, str, symbol='single', is_syntax=1):
try: compile_command(str, symbol=symbol) self.fail('No exception raised for invalid code') except SyntaxError: self.assertTrue(is_syntax) except OverflowError: self.assertTrue((not is_syntax))
'The testcase fails if no exception is raised when a filename parameter provided to binhex.binhex() is too long, or if the exception raised in binhex.binhex() is not an instance of binhex.Error.'
def test_binhex_error_on_long_filename(self):
f3 = open(self.fname3, 'wb') f3.close() self.assertRaises(binhex.Error, binhex.binhex, self.fname3, self.fname2)
'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)...