def test_help_output_redirect(self): # issue 940286, if output is set in Helper, then all output from # Helper.help should be redirected old_pattern = expected_text_pattern getpager_old = pydoc.getpager getpager_new = lambda: (lambda x: x) self.maxDiff = None buf = StringIO() helper = pydoc.Helper(output=buf) unused, doc_loc = get_pydoc_text(pydoc_mod) module = "test.pydoc_mod" help_header = """ Help on module test.pydoc_mod in test: """.lstrip() help_header = textwrap.dedent(help_header) expected_help_pattern = help_header + expected_text_pattern pydoc.getpager = getpager_new try: with captured_output('stdout') as output, \ captured_output('stderr') as err: helper.help(module) result = buf.getvalue().strip() expected_text = expected_help_pattern % ( (doc_loc,) + expected_text_data_docstrings + (inspect.getabsfile(pydoc_mod),)) self.assertEqual('', output.getvalue()) self.assertEqual('', err.getvalue()) self.assertEqual(expected_text, result) finally: pydoc.getpager = getpager_old
def get_report(self, e): e = self.get_exception(e) s = ''.join(traceback.format_exception(type(e), e, e.__traceback__)) with captured_output("stderr") as sio: traceback.print_exception(type(e), e, e.__traceback__) self.assertEqual(sio.getvalue(), s) return s
def test_showwarning_not_callable(self): with original_warnings.catch_warnings(module=self.module): self.module.filterwarnings("always", category=UserWarning) self.module.showwarning = print with support.captured_output('stdout'): self.module.warn('Warning!') self.module.showwarning = 23 self.assertRaises(TypeError, self.module.warn, "Warning!")
def check_traceback_format(self, cleanup_func=None): from _testcapi import traceback_print try: self.some_exception() except KeyError: type_, value, tb = sys.exc_info() if cleanup_func is not None: # Clear the inner frames, not this one cleanup_func(tb.tb_next) traceback_fmt = 'Traceback (most recent call last):\n' + \ ''.join(traceback.format_tb(tb)) file_ = StringIO() traceback_print(tb, file_) python_fmt = file_.getvalue() # Call all _tb and _exc functions with captured_output("stderr") as tbstderr: traceback.print_tb(tb) tbfile = StringIO() traceback.print_tb(tb, file=tbfile) with captured_output("stderr") as excstderr: traceback.print_exc() excfmt = traceback.format_exc() excfile = StringIO() traceback.print_exc(file=excfile) else: raise Error("unable to create test traceback string") # Make sure that Python and the traceback module format the same thing self.assertEqual(traceback_fmt, python_fmt) # Now verify the _tb func output self.assertEqual(tbstderr.getvalue(), tbfile.getvalue()) # Now verify the _exc func output self.assertEqual(excstderr.getvalue(), excfile.getvalue()) self.assertEqual(excfmt, excfile.getvalue()) # Make sure that the traceback is properly indented. tb_lines = python_fmt.splitlines() self.assertEqual(len(tb_lines), 5) banner = tb_lines[0] location, source_line = tb_lines[-2:] self.assertTrue(banner.startswith('Traceback')) self.assertTrue(location.startswith(' File')) self.assertTrue(source_line.startswith(' raise'))
def test_showwarnmsg_missing(self): # Test that _showwarnmsg() missing is okay. text = 'del _showwarnmsg test' with original_warnings.catch_warnings(module=self.module): self.module.filterwarnings("always", category=UserWarning) del self.module._showwarnmsg with support.captured_output('stderr') as stream: self.module.warn(text) result = stream.getvalue() self.assertIn(text, result)
def test_stack_format(self): # Verify _stack functions. Note we have to use _getframe(1) to # compare them without this frame appearing in the output with captured_output("stderr") as ststderr: traceback.print_stack(sys._getframe(1)) stfile = StringIO() traceback.print_stack(sys._getframe(1), file=stfile) self.assertEqual(ststderr.getvalue(), stfile.getvalue()) stfmt = traceback.format_stack(sys._getframe(1)) self.assertEqual(ststderr.getvalue(), "".join(stfmt))
def test_print_stack(self): def prn(): traceback.print_stack() with captured_output("stderr") as stderr: prn() lineno = prn.__code__.co_firstlineno self.assertEqual(stderr.getvalue().splitlines()[-4:], [ ' File "%s", line %d, in test_print_stack' % (__file__, lineno + 3), ' prn()', ' File "%s", line %d, in prn' % (__file__, lineno + 1), ' traceback.print_stack()', ])
def test_save_exception_state_on_error(self): # See issue #14474 def task(): started.release() raise SyntaxError def mywrite(self, *args): try: raise ValueError except ValueError: pass real_write(self, *args) c = thread._count() started = thread.allocate_lock() with support.captured_output("stderr") as stderr: real_write = stderr.write stderr.write = mywrite started.acquire() thread.start_new_thread(task, ()) started.acquire() while thread._count() > c: time.sleep(0.01) self.assertIn("Traceback", stderr.getvalue())
def test_show_warning_output(self): # With showarning() missing, make sure that output is okay. text = 'test show_warning' with original_warnings.catch_warnings(module=self.module): self.module.filterwarnings("always", category=UserWarning) del self.module.showwarning with support.captured_output('stderr') as stream: warning_tests.inner(text) result = stream.getvalue() self.assertEqual(result.count('\n'), 2, "Too many newlines in %r" % result) first_line, second_line = result.split('\n', 1) expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py' first_line_parts = first_line.rsplit(':', 3) path, line, warning_class, message = first_line_parts line = int(line) self.assertEqual(expected_file, path) self.assertEqual(warning_class, ' ' + UserWarning.__name__) self.assertEqual(message, ' ' + text) expected_line = ' ' + linecache.getline(path, line).strip() + '\n' assert expected_line self.assertEqual(second_line, expected_line)
def test_3611(self): # A re-raised exception in a __del__ caused the __context__ # to be cleared class C: def __del__(self): try: 1/0 except: raise def f(): x = C() try: try: x.x except AttributeError: del x raise TypeError except Exception as e: self.assertNotEqual(e.__context__, None) self.assertIsInstance(e.__context__, AttributeError) with support.captured_output("stderr"): f()
def get_report(self, e): from _testcapi import exception_print e = self.get_exception(e) with captured_output("stderr") as s: exception_print(e) return s.getvalue()
def _check_recursive_traceback_display(self, render_exc): # Always show full diffs when this test fails # Note that rearranging things may require adjusting # the relative line numbers in the expected tracebacks self.maxDiff = None # Check hitting the recursion limit def f(): f() with captured_output("stderr") as stderr_f: try: f() except RecursionError as exc: render_exc() else: self.fail("no recursion occurred") lineno_f = f.__code__.co_firstlineno result_f = ( 'Traceback (most recent call last):\n' f' File "{__file__}", line {lineno_f+5}, in _check_recursive_traceback_display\n' ' f()\n' f' File "{__file__}", line {lineno_f+1}, in f\n' ' f()\n' f' File "{__file__}", line {lineno_f+1}, in f\n' ' f()\n' f' File "{__file__}", line {lineno_f+1}, in f\n' ' f()\n' # XXX: The following line changes depending on whether the tests # are run through the interactive interpreter or with -m # It also varies depending on the platform (stack size) # Fortunately, we don't care about exactness here, so we use regex r' \[Previous line repeated (\d+) more times\]' '\n' 'RecursionError: maximum recursion depth exceeded\n') expected = result_f.splitlines() actual = stderr_f.getvalue().splitlines() # Check the output text matches expectations # 2nd last line contains the repetition count self.assertEqual(actual[:-2], expected[:-2]) self.assertRegex(actual[-2], expected[-2]) self.assertEqual(actual[-1], expected[-1]) # Check the recursion count is roughly as expected rec_limit = sys.getrecursionlimit() self.assertIn(int(re.search(r"\d+", actual[-2]).group()), range(rec_limit - 60, rec_limit)) # Check a known (limited) number of recursive invocations def g(count=10): if count: return g(count - 1) raise ValueError with captured_output("stderr") as stderr_g: try: g() except ValueError as exc: render_exc() else: self.fail("no value error was raised") lineno_g = g.__code__.co_firstlineno result_g = (f' File "{__file__}", line {lineno_g+2}, in g\n' ' return g(count-1)\n' f' File "{__file__}", line {lineno_g+2}, in g\n' ' return g(count-1)\n' f' File "{__file__}", line {lineno_g+2}, in g\n' ' return g(count-1)\n' ' [Previous line repeated 6 more times]\n' f' File "{__file__}", line {lineno_g+3}, in g\n' ' raise ValueError\n' 'ValueError\n') tb_line = ( 'Traceback (most recent call last):\n' f' File "{__file__}", line {lineno_g+7}, in _check_recursive_traceback_display\n' ' g()\n') expected = (tb_line + result_g).splitlines() actual = stderr_g.getvalue().splitlines() self.assertEqual(actual, expected) # Check 2 different repetitive sections def h(count=10): if count: return h(count - 1) g() with captured_output("stderr") as stderr_h: try: h() except ValueError as exc: render_exc() else: self.fail("no value error was raised") lineno_h = h.__code__.co_firstlineno result_h = ( 'Traceback (most recent call last):\n' f' File "{__file__}", line {lineno_h+7}, in _check_recursive_traceback_display\n' ' h()\n' f' File "{__file__}", line {lineno_h+2}, in h\n' ' return h(count-1)\n' f' File "{__file__}", line {lineno_h+2}, in h\n' ' return h(count-1)\n' f' File "{__file__}", line {lineno_h+2}, in h\n' ' return h(count-1)\n' ' [Previous line repeated 6 more times]\n' f' File "{__file__}", line {lineno_h+3}, in h\n' ' g()\n') expected = (result_h + result_g).splitlines() actual = stderr_h.getvalue().splitlines() self.assertEqual(actual, expected)
def test_print_function(self): with support.captured_output("stderr") as s: print("foo", file=sys.stderr) self.assertEqual(s.getvalue(), "foo\n")