def test_issue31285(self): # warn_explicit() should neither raise a SystemError nor cause an # assertion failure, in case the return value of get_source() has a # bad splitlines() method. def get_bad_loader(splitlines_ret_val): class BadLoader: def get_source(self, fullname): class BadSource(str): def splitlines(self): return splitlines_ret_val return BadSource('spam') return BadLoader() wmod = self.module with original_warnings.catch_warnings(module=wmod): wmod.filterwarnings('default', category=UserWarning) with support.captured_stderr() as stderr: wmod.warn_explicit( 'foo', UserWarning, 'bar', 1, module_globals={'__loader__': get_bad_loader(42), '__name__': 'foobar'}) self.assertIn('UserWarning: foo', stderr.getvalue()) show = wmod._showwarnmsg try: del wmod._showwarnmsg with support.captured_stderr() as stderr: wmod.warn_explicit( 'eggs', UserWarning, 'bar', 1, module_globals={'__loader__': get_bad_loader([42]), '__name__': 'foobar'}) self.assertIn('UserWarning: eggs', stderr.getvalue()) finally: wmod._showwarnmsg = show
def test_warn(self): Equal = self.assertEqual config._warned = set() with captured_stderr() as stderr: config._warn('warning', 'key') Equal(config._warned, {('warning','key')}) Equal(stderr.getvalue(), 'warning'+'\n') with captured_stderr() as stderr: config._warn('warning', 'key') Equal(stderr.getvalue(), '') with captured_stderr() as stderr: config._warn('warn2', 'yek') Equal(config._warned, {('warning','key'), ('warn2','yek')}) Equal(stderr.getvalue(), 'warn2'+'\n')
def test_warnings_on_cleanup(self) -> None: # Two kinds of warning on shutdown # Issue 10888: may write to stderr if modules are nulled out # ResourceWarning will be triggered by __del__ with self.do_create() as dir: if os.sep != '\\': # Embed a backslash in order to make sure string escaping # in the displayed error message is dealt with correctly suffix = '\\check_backslash_handling' else: suffix = '' d = self.do_create(dir=dir, suf=suffix) #Check for the Issue 10888 message modules = [os, os.path] if has_stat: modules.append(stat) with support.captured_stderr() as err: with NulledModules(*modules): d.cleanup() message = err.getvalue().replace('\\\\', '\\') self.assertIn("while cleaning up", message) self.assertIn(d.name, message) # Check for the resource warning with support.check_warnings(('Implicitly', ResourceWarning), quiet=False): warnings.filterwarnings("always", category=ResourceWarning) d.__del__() self.assertFalse(os.path.exists(d.name), "TemporaryDirectory %s exists after __del__" % d.name)
def test_unraisable(self): # Issue #22836: PyErr_WriteUnraisable() should give sensible reports class BrokenDel: def __del__(self): exc = ValueError("del is broken") # The following line is included in the traceback report: raise exc class BrokenExceptionDel: def __del__(self): exc = BrokenStrException() # The following line is included in the traceback report: raise exc for test_class in (BrokenDel, BrokenExceptionDel): with self.subTest(test_class): obj = test_class() with captured_stderr() as stderr: del obj report = stderr.getvalue() self.assertIn("Exception ignored", report) self.assertIn(test_class.__del__.__qualname__, report) self.assertIn("test_exceptions.py", report) self.assertIn("raise exc", report) if test_class is BrokenExceptionDel: self.assertIn("BrokenStrException", report) self.assertIn("<exception str() failed>", report) else: self.assertIn("ValueError", report) self.assertIn("del is broken", report) self.assertTrue(report.endswith("\n"))
def test_badisinstance(self): # Bug #2542: if issubclass(e, MyException) raises an exception, # it should be ignored class Meta(type): def __subclasscheck__(cls, subclass): raise ValueError() class MyException(Exception, metaclass=Meta): pass with captured_stderr() as stderr: try: raise KeyError() except MyException as e: self.fail("exception should not be a MyException") except KeyError: pass except: self.fail("Should have raised KeyError") else: self.fail("Should have raised KeyError") def g(): try: return g() except RecursionError: return sys.exc_info() e, v, tb = g() self.assertTrue(isinstance(v, RecursionError), type(v)) self.assertIn("maximum recursion depth exceeded", str(v))
def test_broken_getattr_handling(self): """ Test subiterator with a broken getattr implementation """ class Broken: def __iter__(self): return self def __next__(self): return 1 def __getattr__(self, attr): 1/0 def g(): yield from Broken() with self.assertRaises(ZeroDivisionError): gi = g() self.assertEqual(next(gi), 1) gi.send(1) with self.assertRaises(ZeroDivisionError): gi = g() self.assertEqual(next(gi), 1) gi.throw(AttributeError) with captured_stderr() as output: gi = g() self.assertEqual(next(gi), 1) gi.close() self.assertIn('ZeroDivisionError', output.getvalue())
def test_fatal_coro_warning(self): # Issue 27811 async def func(): pass with warnings.catch_warnings(), support.captured_stderr() as stderr: warnings.filterwarnings("error") func() support.gc_collect() self.assertIn("was never awaited", stderr.getvalue())
def test_cannot_insert_duplicate_row(self): """Inserting a duplicate rows shouldn't work.""" self.model_class.objects.create(f1='a', f2='b') self.ut.field_defs = (self.f1, self.f2) with captured_stderr(): with self.assertRaises(IntegrityError): with transaction.atomic(): self.model_class.objects.create(f1='a', f2='b')
def test_cannot_create_unique(self): """Creating a unique key on a table with duplicate rows shouldn't work""" self.model_class.objects.create(f1='a', f2='b') self.model_class.objects.create(f1='a', f2='b') with captured_stderr(): with self.assertRaises(IntegrityError): with transaction.atomic(): self.ut.field_defs = (self.f1, self.f2)
def test_addpackage_import_bad_pth_file(self): # Issue 5258 pth_dir, pth_fn = self.make_pth("abc\x00def\n") with captured_stderr() as err_out: self.assertFalse(site.addpackage(pth_dir, pth_fn, set())) self.assertEqual(err_out.getvalue(), "") for path in sys.path: if isinstance(path, str): self.assertNotIn("abc\x00def", path)
def test_get(self): self.con = http.client.HTTPConnection(self.HOST, self.PORT) self.con.connect() with support.captured_stderr() as err: self.con.request("GET", "/") self.con.getresponse() self.assertTrue(err.getvalue().endswith('"GET / HTTP/1.1" 200 -\n'))
def test_debuglevel(self): mock_socket.reply_with(b"220 Hello world") smtp = smtplib.SMTP() smtp.set_debuglevel(1) with support.captured_stderr() as stderr: smtp.connect(HOST, self.port) smtp.close() expected = re.compile(r"^connect:", re.MULTILINE) self.assertRegex(stderr.getvalue(), expected)
def test_command_line_handling_do_discovery_too_many_arguments(self): program = TestableTestProgram() program.testLoader = None with support.captured_stderr() as stderr, self.assertRaises(SystemExit) as cm: # too many args program._do_discovery(["one", "two", "three", "four"]) self.assertEqual(cm.exception.args, (2,)) self.assertIn("usage:", stderr.getvalue())
def test_unicode_args(self): e = RuntimeError("Drink \u2615") # coffee emoji # Can take the repr of any object self.assertEqual(repr(e), "RuntimeError(u'Drink \\u2615',)") # Cannot of course turn a non-ascii Unicode object into a str, even if it's an exception object with self.assertRaises(UnicodeEncodeError) as cm: str(e) self.assertEqual( str(cm.exception), "'ascii' codec can't encode character u'\\u2615' in position 6: ordinal not in range(128)") # But the exception hook, via Py#displayException, does not fail when attempting to __str__ the exception args with support.captured_stderr() as s: sys.excepthook(RuntimeError, "Drink \u2615", None) self.assertEqual(s.getvalue(), "RuntimeError\n") # It is fine with ascii values, of course with support.captured_stderr() as s: sys.excepthook(RuntimeError, "Drink java", None) self.assertEqual(s.getvalue(), "RuntimeError: Drink java\n")
def test_platforms_invalid_types(self): attrs = {'name': 'Monty', 'version': '1.0', 'platforms': ('GNU/Linux', 'Some Evil Platform')} with captured_stderr() as error: d = Distribution(attrs) # should have warning about passing a non-list self.assertIn('should be a list', error.getvalue()) # should be converted to a list self.assertIsInstance(d.metadata.platforms, list) self.assertEqual(d.metadata.platforms, list(attrs['platforms']))
def test_keywords_invalid_type(self): attrs = {'name': 'Monty', 'version': '1.0', 'keywords': ('spam', 'eggs', 'life of brian')} with captured_stderr() as error: d = Distribution(attrs) # should have warning about passing a non-list self.assertIn('should be a list', error.getvalue()) # should be converted to a list self.assertIsInstance(d.metadata.keywords, list) self.assertEqual(d.metadata.keywords, list(attrs['keywords']))
def test_cannot_remove_unique(self): """Removing a unique constraint that cause duplicate rows shouldn't work.""" self.ut.field_defs = (self.f1, self.f2) self.model_class.objects.create(f1='a', f2='b') self.model_class.objects.create(f1='a', f2='c') with captured_stderr(): with self.assertRaises(IntegrityError): with transaction.atomic(): self.ut.field_defs.remove(self.f2)
def test_apropos_with_bad_package(self): # Issue 7425 - pydoc -k failed when bad package on path pkgdir = os.path.join(TESTFN, "syntaxerr") os.mkdir(pkgdir) badsyntax = os.path.join(pkgdir, "__init__") + os.extsep + "py" with open(badsyntax, "w") as f: f.write("invalid python syntax = $1\n") with self.restrict_walk_packages(path=[TESTFN]): with captured_stdout() as out: with captured_stderr() as err: pydoc.apropos("xyzzy") # No result, no error self.assertEqual(out.getvalue(), "") self.assertEqual(err.getvalue(), "") # The package name is still matched with captured_stdout() as out: with captured_stderr() as err: pydoc.apropos("syntaxerr") self.assertEqual(out.getvalue().strip(), "syntaxerr") self.assertEqual(err.getvalue(), "")
def test_addpackage_import_bad_exec(self): # Issue 10642 pth_dir, pth_fn = self.make_pth("randompath\nimport nosuchmodule\n") with captured_stderr() as err_out: site.addpackage(pth_dir, pth_fn, set()) self.assertRegex(err_out.getvalue(), "line 2") self.assertRegex(err_out.getvalue(), re.escape(os.path.join(pth_dir, pth_fn))) # XXX: ditto previous XXX comment. self.assertRegex(err_out.getvalue(), 'Traceback') self.assertRegex(err_out.getvalue(), 'ModuleNotFoundError')
def test_addpackage_import_bad_pth_file(self): # Issue 5258 pth_dir, pth_fn = self.make_pth("abc\x00def\n") with captured_stderr() as err_out: site.addpackage(pth_dir, pth_fn, set()) self.assertRegex(err_out.getvalue(), "line 1") self.assertRegex(err_out.getvalue(), re.escape(os.path.join(pth_dir, pth_fn))) # XXX: ditto previous XXX comment. self.assertRegex(err_out.getvalue(), 'Traceback') self.assertRegex(err_out.getvalue(), 'ValueError')
def test_falls_back_to_stdin(self): with mock.patch('os.open') as os_open, \ mock.patch('sys.stdin', spec=StringIO) as stdin: os_open.side_effect = IOError stdin.fileno.side_effect = AttributeError with support.captured_stderr() as stderr: with self.assertWarns(getpass.GetPassWarning): getpass.unix_getpass() stdin.readline.assert_called_once_with() self.assertIn('Warning', stderr.getvalue()) self.assertIn('Password:', stderr.getvalue())
def test_docutils_safe(self): """ Make sure docutils' file inclusion directives are disabled by default. """ with captured_stderr() as self.docutils_stderr: entry = Entry.objects.create( pub_date=self.now, is_active=True, headline='active', content_format='reST', body='.. raw:: html\n :file: somefile\n', slug='a', ) self.assertIn('<p>"raw" directive disabled.</p>', entry.body_html) self.assertIn('.. raw:: html\n :file: somefile', entry.body_html)
def test_err(self): self.con = http.client.HTTPConnection(self.HOST, self.PORT) self.con.connect() with support.captured_stderr() as err: self.con.request('ERROR', '/') self.con.getresponse() lines = err.getvalue().split('\n') self.assertTrue(lines[0].endswith('code 404, message File not found')) self.assertTrue(lines[1].endswith('"ERROR / HTTP/1.1" 404 -'))
def test_classifier_invalid_type(self): attrs = {'name': 'Boa', 'version': '3.0', 'classifiers': ('Programming Language :: Python :: 3',)} with captured_stderr() as error: d = Distribution(attrs) # should have warning about passing a non-list self.assertIn('should be a list', error.getvalue()) # should be converted to a list self.assertIsInstance(d.metadata.classifiers, list) self.assertEqual(d.metadata.classifiers, list(attrs['classifiers']))
def verify_tabnanny_check(self, dir_or_file, out="", err=""): """Common verification for tabnanny.check(). Use this method to assert expected values of `stdout` and `stderr` after running tabnanny.check() on given `dir` or `file` path. Because tabnanny.check() captures exceptions and writes to `stdout` and `stderr`, asserting standard outputs is the only way. """ with captured_stdout() as stdout, captured_stderr() as stderr: tabnanny.check(dir_or_file) self.assertEqual(stdout.getvalue(), out) self.assertEqual(stderr.getvalue(), err)
def test_log(self): d = asyncore.dispatcher() # capture output of dispatcher.log() (to stderr) l1 = "Lovely spam! Wonderful spam!" l2 = "I don't like spam!" with support.captured_stderr() as stderr: d.log(l1) d.log(l2) lines = stderr.getvalue().splitlines() self.assertEqual(lines, ['log: %s' % l1, 'log: %s' % l2])
def testBufferCatchFailfast(self): program = self.program for arg, attr in (('buffer', 'buffer'), ('failfast', 'failfast'), ('catch', 'catchbreak')): if attr == 'catch' and not hasInstallHandler: continue setattr(program, attr, None) program.parseArgs([None]) self.assertIs(getattr(program, attr), False) false = [] setattr(program, attr, false) program.parseArgs([None]) self.assertIs(getattr(program, attr), false) true = [42] setattr(program, attr, true) program.parseArgs([None]) self.assertIs(getattr(program, attr), true) short_opt = '-%s' % arg[0] long_opt = '--%s' % arg for opt in short_opt, long_opt: setattr(program, attr, None) program.parseArgs([None, opt]) self.assertIs(getattr(program, attr), True) setattr(program, attr, False) with support.captured_stderr() as stderr, \ self.assertRaises(SystemExit) as cm: program.parseArgs([None, opt]) self.assertEqual(cm.exception.args, (2,)) setattr(program, attr, True) with support.captured_stderr() as stderr, \ self.assertRaises(SystemExit) as cm: program.parseArgs([None, opt]) self.assertEqual(cm.exception.args, (2,))
def test_apropos_with_unreadable_dir(self): # Issue 7367 - pydoc -k failed when unreadable dir on path self.unreadable_dir = os.path.join(TESTFN, "unreadable") os.mkdir(self.unreadable_dir, 0) self.addCleanup(os.rmdir, self.unreadable_dir) # Note, on Windows the directory appears to be still # readable so this is not really testing the issue there with self.restrict_walk_packages(path=[TESTFN]): with captured_stdout() as out: with captured_stderr() as err: pydoc.apropos("SOMEKEY") # No result, no error self.assertEqual(out.getvalue(), "") self.assertEqual(err.getvalue(), "")
def test_errprint(self): """Asserting result of `tabnanny.errprint()` by giving sample inputs.""" tests = [ (['first', 'second'], 'first second\n'), (['first'], 'first\n'), ([1, 2, 3], '1 2 3\n'), ([], '\n') ] for args, expected in tests: with self.subTest(arguments=args, expected=expected): with captured_stderr() as stderr: tabnanny.errprint(*args) self.assertEqual(stderr.getvalue() , expected)
def test_addpackage_import_bad_syntax(self): # Issue 10642 pth_dir, pth_fn = self.make_pth("import bad)syntax\n") with captured_stderr() as err_out: site.addpackage(pth_dir, pth_fn, set()) self.assertRegex(err_out.getvalue(), "line 1") self.assertRegex(err_out.getvalue(), re.escape(os.path.join(pth_dir, pth_fn))) # XXX: the previous two should be independent checks so that the # order doesn't matter. The next three could be a single check # but my regex foo isn't good enough to write it. self.assertRegex(err_out.getvalue(), 'Traceback') self.assertRegex(err_out.getvalue(), r'import bad\)syntax') self.assertRegex(err_out.getvalue(), 'SyntaxError')
def test_error_after_default(self): with original_warnings.catch_warnings(module=self.module) as w: self.module.resetwarnings() message = "FilterTests.test_ignore_after_default" def f(): self.module.warn(message, UserWarning) with support.captured_stderr() as stderr: f() stderr = stderr.getvalue() self.assertIn("UserWarning: FilterTests.test_ignore_after_default", stderr) self.assertIn("self.module.warn(message, UserWarning)", stderr) self.module.filterwarnings("error", category=UserWarning) self.assertRaises(UserWarning, f)
def test_unraisable(self): # Issue #22836: PyErr_WriteUnraisable() should give sensible reports class BrokenDel: def __del__(self): exc = ValueError("del is broken") # The following line is included in the traceback report: raise exc class BrokenRepr(BrokenDel): def __repr__(self): raise AttributeError("repr() is broken") class BrokenExceptionDel: def __del__(self): exc = BrokenStrException() # The following line is included in the traceback report: raise exc for test_class in (BrokenDel, BrokenRepr, BrokenExceptionDel): with self.subTest(test_class): obj = test_class() with captured_stderr() as stderr: del obj gc_collect() report = stderr.getvalue() self.assertIn("Exception ignored", report) if test_class is BrokenRepr: self.assertIn("<object repr() failed>", report) else: self.assertIn(test_class.__del__.__qualname__, report) self.assertIn("test_exceptions.py", report) self.assertIn("raise exc", report) if test_class is BrokenExceptionDel: self.assertIn("BrokenStrException", report) if check_impl_detail(pypy=False): self.assertIn("<exception str() failed>", report) else: # pypy: this is what lib-python's traceback.py gives self.assertRegex( report, ".*BrokenStrException: <unprintable" " BrokenStrException object>\n") else: self.assertIn("ValueError", report) self.assertIn("del is broken", report) self.assertTrue(report.endswith("\n"))
def test_unhandled(self): for exc_type in (ValueError, BrokenStrException): with self.subTest(exc_type): try: exc = exc_type('test message') raise exc except exc_type: with captured_stderr() as stderr: sys.__excepthook__(*sys.exc_info()) report = stderr.getvalue() self.assertIn('test_exceptions.py', report) self.assertIn('raise exc', report) self.assertIn(exc_type.__name__, report) if exc_type is BrokenStrException: self.assertIn('<exception str() failed>', report) else: self.assertIn('test message', report) self.assertTrue(report.endswith('\n'))
def test_main_with_time_unit(self): unit_sec = self.run_main(seconds_per_increment=0.002, switches=[ '-u', 'sec']) self.assertEqual(unit_sec, '1000 loops, best of 3: 0.002 sec per loop\n') unit_msec = self.run_main(seconds_per_increment=0.002, switches=[ '-u', 'msec']) self.assertEqual(unit_msec, '1000 loops, best of 3: 2 msec per loop\n') unit_usec = self.run_main(seconds_per_increment=0.002, switches=[ '-u', 'usec']) self.assertEqual(unit_usec, '1000 loops, best of 3: 2e+03 usec per loop\n') with captured_stderr() as error_stringio: invalid = self.run_main(seconds_per_increment=0.002, switches=[ '-u', 'parsec']) self.assertEqual(error_stringio.getvalue(), """Unrecognized unit. Please select usec, msec, or sec. """)
def _check_args(self, args, expected=None): """ The expected parameter is for cases when the behavior of the new parse_args differs from the old (but deliberately so). """ if expected is None: try: expected = old_parse_args(args) except getopt.GetoptError: # Suppress usage string output when an argparse.ArgumentError # error is raised. with support.captured_stderr(): self.assertRaises(SystemExit, self._parse_args, args) return # The new parse_args() sorts by long option string. expected[0].sort() actual = self._parse_args(args) self.assertEqual(actual, expected)
def test_main_with_time_unit(self): unit_sec = self.run_main(seconds_per_increment=0.003, switches=['-u', 'sec']) self.assertEqual(unit_sec, "100 loops, best of 5: 0.003 sec per loop\n") unit_msec = self.run_main(seconds_per_increment=0.003, switches=['-u', 'msec']) self.assertEqual(unit_msec, "100 loops, best of 5: 3 msec per loop\n") unit_usec = self.run_main(seconds_per_increment=0.003, switches=['-u', 'usec']) self.assertEqual(unit_usec, "100 loops, best of 5: 3e+03 usec per loop\n") # Test invalid unit input with captured_stderr() as error_stringio: invalid = self.run_main(seconds_per_increment=0.003, switches=['-u', 'parsec']) self.assertEqual(error_stringio.getvalue(), "Unrecognized unit. Please select nsec, usec, msec, or sec.\n")
def test_get_multiple_message(self, mock): d = self.data data2 = ((d[0], d[1]), (d[1], d[2]), (d[2], d[0])) subtests = 0 for (code1, exc1, msg1), (code2, exc2, msg2) in data2: with self.subTest(codes=(code1, code2)): try: eval(compile(code1, '', 'eval')) except exc1: try: eval(compile(code2, '', 'eval')) except exc2: with captured_stderr() as output: run.print_exception() actual = output.getvalue() self.assertIn(msg1, actual) self.assertIn(msg2, actual) subtests += 1 self.assertEqual(subtests, len(data2)) # All subtests ran?
def test_delegation_of_close_to_non_generator(self): """ Test delegation of close() to non-generator """ trace = [] def g(): try: trace.append('starting g') yield from range(3) trace.append('g should not be here') finally: trace.append('finishing g') gi = g() next(gi) with captured_stderr() as output: gi.close() self.assertEqual(output.getvalue(), '') self.assertEqual(trace, ['starting g', 'finishing g'])
def test_traceback(self): # We want ensure that the traceback from the child process is # contained in the traceback raised in the main process. future = self.executor.submit(self._test_traceback) with self.assertRaises(Exception) as cm: future.result() exc = cm.exception self.assertIs(type(exc), RuntimeError) self.assertEqual(exc.args, (123, )) cause = exc.__cause__ self.assertIs(type(cause), futures.process._RemoteTraceback) self.assertIn('raise RuntimeError(123) # some comment', cause.tb) with support.captured_stderr() as f1: try: raise exc except RuntimeError: sys.excepthook(*sys.exc_info()) self.assertIn('raise RuntimeError(123) # some comment', f1.getvalue())
def test_main_with_time_unit(self): unit_sec = self.run_main(seconds_per_increment=0.002, switches=['-u', 'sec']) self.assertIn("100 loops, average of 7: 0.002", unit_sec) self.assertIn("sec per loop", unit_sec) unit_msec = self.run_main(seconds_per_increment=0.002, switches=['-u', 'msec']) self.assertIn("100 loops, average of 7: 2", unit_msec) self.assertIn("msec per loop", unit_msec) unit_usec = self.run_main(seconds_per_increment=0.002, switches=['-u', 'usec']) self.assertIn("100 loops, average of 7: 2e+03", unit_usec) self.assertIn("usec per loop", unit_usec) # Test invalid unit input with captured_stderr() as error_stringio: invalid = self.run_main(seconds_per_increment=0.002, switches=['-u', 'parsec']) self.assertEqual( error_stringio.getvalue(), "Unrecognized unit. Please select usec, msec, or sec.\n")
def test_unhandled(self): # Check for sensible reporting of unhandled exceptions for exc_type in (ValueError, BrokenStrException): with self.subTest(exc_type): try: exc = exc_type("test message") # The following line is included in the traceback report: raise exc except exc_type: with captured_stderr() as stderr: sys.__excepthook__(*sys.exc_info()) report = stderr.getvalue() self.assertIn("test_exceptions.py", report) self.assertIn("raise exc", report) self.assertIn(exc_type.__name__, report) if exc_type is BrokenStrException: self.assertIn("<exception str() failed>", report) else: self.assertIn("test message", report) self.assertTrue(report.endswith("\n"))
def test_done_callback_raises(self): with support.captured_stderr() as stderr: raising_was_called = False fn_was_called = False def raising_fn(callback_future): nonlocal raising_was_called raising_was_called = True raise Exception('doh!') def fn(callback_future): nonlocal fn_was_called fn_was_called = True f = Future() f.add_done_callback(raising_fn) f.add_done_callback(fn) f.set_result(5) self.assertTrue(raising_was_called) self.assertTrue(fn_was_called) self.assertIn('Exception: doh!', stderr.getvalue())
def test_badisinstance(self): # Bug #2542: if issubclass(e, MyException) raises an exception, # it should be ignored class Meta(type): def __subclasscheck__(cls, subclass): raise ValueError() class MyException(Exception, metaclass=Meta): pass with captured_stderr() as stderr: try: raise KeyError() except MyException as e: self.fail("exception should not be a MyException") except KeyError: pass except: self.fail("Should have raised KeyError") else: self.fail("Should have raised KeyError")
def test_print_exception_unhashable(self): class UnhashableException(Exception): def __eq__(self, other): return True ex1 = UnhashableException('ex1') ex2 = UnhashableException('ex2') try: raise ex2 from ex1 except UnhashableException: try: raise ex1 except UnhashableException: with captured_stderr() as output: with mock.patch.object(run, 'cleanup_traceback') as ct: ct.side_effect = lambda t, e: t run.print_exception() tb = output.getvalue().strip().splitlines() self.assertEqual(11, len(tb)) self.assertIn('UnhashableException: ex2', tb[3]) self.assertIn('UnhashableException: ex1', tb[10])
def test_del_on_shutdown(self): # A TemporaryDirectory may be cleaned up during shutdown # Make sure it works with the relevant modules nulled out with self.do_create() as dir: d = self.do_create(dir=dir) # Mimic the nulling out of modules that # occurs during system shutdown modules = [os, os.path] if has_stat: modules.append(stat) # Currently broken, so suppress the warning # that is otherwise emitted on stdout with support.captured_stderr() as err: with NulledModules(*modules): d.cleanup() # Currently broken, so stop spurious exception by # indicating the object has already been closed d._closed = True # And this assert will fail, as expected by the # unittest decorator... self.assertFalse(os.path.exists(d.name), "TemporaryDirectory %s exists after cleanup" % d.name)
def test_correct_directory_verbose(self): """Directory containing few error free python source code files. Because order of files returned by `os.lsdir()` is not fixed, verify the existence of each output lines at `stdout` using `in` operator. `verbose` mode of `tabnanny.verbose` asserts `stdout`. """ with tempfile.TemporaryDirectory() as tmp_dir: lines = [f"{tmp_dir!r}: listing directory\n",] file1 = TemporaryPyFile(SOURCE_CODES["error_free"], directory=tmp_dir) file2 = TemporaryPyFile(SOURCE_CODES["error_free"], directory=tmp_dir) with file1 as file1_path, file2 as file2_path: for file_path in (file1_path, file2_path): lines.append(f"{file_path!r}: Clean bill of health.\n") tabnanny.verbose = 1 with captured_stdout() as stdout, captured_stderr() as stderr: tabnanny.check(tmp_dir) stdout = stdout.getvalue() for line in lines: with self.subTest(line=line): self.assertIn(line, stdout) self.assertEqual(stderr.getvalue(), "")
def checkError(self, args, msg): with support.captured_stderr() as err, self.assertRaises(SystemExit): libregrtest._parse_args(args) self.assertIn(msg, err.getvalue())
def test_run_show(self): with captured_stderr() as f: run.idle_showwarning_subproc('Test', UserWarning, 'test_warning.py', 99, f, 'Line of code') self.assertEqual(idlemsg.splitlines(), f.getvalue().splitlines())
def test_empty(self): """test method for empty line""" cli = self.create() with captured_stdout() as stdout, captured_stderr() as stderr: self.assertFalse(cli.onecmd("")) self.assertEqual("", stdout.getvalue())
def test_shell_show(self): with captured_stderr() as f: shell.idle_showwarning( 'Test', UserWarning, 'test_warning.py', 99, f, 'Line of code') self.assertEqual(shellmsg.splitlines(), f.getvalue().splitlines())
def test_all_error(self): """test method for do_all method errors""" cli = self.create() with captured_stdout() as stdout, captured_stderr() as stderr: self.assertFalse(cli.onecmd("all PeterPans")) self.assertEqual(TestConsole.no_class, stdout.getvalue())
def test_bad_coding(self): bad_coding = os.path.join(os.path.dirname(__file__), 'bad_coding2.py') with support.captured_stderr(): self.assertIsNone(py_compile.compile(bad_coding, doraise=False)) self.assertFalse( os.path.exists(importlib.util.cache_from_source(bad_coding)))
def test_run_show(self): with captured_stderr() as f: run.idle_showwarning_subproc( 'Test', UserWarning, 'test_warning.py', 99, f, 'Line of code') # The following uses .splitlines to erase line-ending differences self.assertEqual(idlemsg.splitlines(), f.getvalue().splitlines())
def test_main_exception_fixed_reps(self): with captured_stderr() as error_stringio: s = self.run_main(switches=['-n1', '1/0']) self.assert_exc_string(error_stringio.getvalue(), 'ZeroDivisionError')
def run_with_capture(self, func, *args, **kwargs): with captured_stdout() as output: with captured_stderr() as error: func(*args, **kwargs) return output.getvalue(), error.getvalue()
def test_captured_stderr(self): with support.captured_stderr() as stderr: print("hello", file=sys.stderr) self.assertEqual(stderr.getvalue(), "hello\n")
def get_print_exception_result_as_str(value): # Trying with traceback with captured_stderr() as output: traceback.print_exception(value) return output.getvalue().splitlines()[-1]