def test_debug_print(self): file_list = FileList() with captured_stdout() as stdout: file_list.debug_print('xxx') self.assertEqual(stdout.getvalue(), '') debug.DEBUG = True try: with captured_stdout() as stdout: file_list.debug_print('xxx') self.assertEqual(stdout.getvalue(), 'xxx\n') finally: debug.DEBUG = False
def test_debug_print(self): cmd = self.cmd with captured_stdout() as stdout: cmd.debug_print('xxx') stdout.seek(0) self.assertEqual(stdout.read(), '') debug.DEBUG = True try: with captured_stdout() as stdout: cmd.debug_print('xxx') stdout.seek(0) self.assertEqual(stdout.read(), 'xxx\n') finally: debug.DEBUG = False
def test_compile_dir_pathlike(self): self.assertFalse(os.path.isfile(self.bc_path)) with support.captured_stdout() as stdout: compileall.compile_dir(pathlib.Path(self.directory)) line = stdout.getvalue().splitlines()[0] self.assertRegex(line, r'Listing ([^WindowsPath|PosixPath].*)') self.assertTrue(os.path.isfile(self.bc_path))
def test_resolve_false(self): # Issue #23008: pydoc enum.{,Int}Enum failed # because bool(enum.Enum) is False. with captured_stdout() as help_io: pydoc.help('enum.Enum') helptext = help_io.getvalue() self.assertIn('class Enum', helptext)
def report(self, pat): grep.engine._pat = pat with captured_stdout() as s: grep.grep_it(re.compile(pat), __file__) lines = s.getvalue().split('\n') lines.pop() # remove bogus '' after last \n return lines
def test_module_repr(self): with util.uncache('__hello__'), captured_stdout(): with warnings.catch_warnings(): warnings.simplefilter('ignore', DeprecationWarning) module = self.machinery.FrozenImporter.load_module('__hello__') repr_str = self.machinery.FrozenImporter.module_repr(module) self.assertEqual(repr_str, "<module '__hello__' (frozen)>")
def test_debug_mode(self): # this covers the code called when DEBUG is set sys.argv = ['setup.py', '--name'] with captured_stdout() as stdout: distutils.core.setup(name='bar') stdout.seek(0) self.assertEqual(stdout.read(), 'bar\n') distutils.core.DEBUG = True try: with captured_stdout() as stdout: distutils.core.setup(name='bar') finally: distutils.core.DEBUG = False stdout.seek(0) wanted = "options (after parsing config files):\n" self.assertEqual(stdout.readlines()[0], wanted)
def test_namedtuple_public_underscore(self): NT = namedtuple('NT', ['abc', 'def'], rename=True) with captured_stdout() as help_io: pydoc.help(NT) helptext = help_io.getvalue() self.assertIn('_1', helptext) self.assertIn('_replace', helptext) self.assertIn('_asdict', helptext)
def test_eval(self): with open(_fname + '.dir', 'w') as stream: stream.write("str(print('Hacked!')), 0\n") with support.captured_stdout() as stdout: with self.assertRaises(ValueError): with dumbdbm.open(_fname) as f: pass self.assertEqual(stdout.getvalue(), '')
def test_compile_file_pathlike(self): self.assertFalse(os.path.isfile(self.bc_path)) # we should also test the output with support.captured_stdout() as stdout: self.assertTrue( compileall.compile_file(pathlib.Path(self.source_path))) self.assertRegex(stdout.getvalue(), r'Compiling ([^WindowsPath|PosixPath].*)') self.assertTrue(os.path.isfile(self.bc_path))
def test_get_code(self): # Make sure that the code object is good. name = '__hello__' with captured_stdout() as stdout: code = self.machinery.FrozenImporter.get_code(name) mod = types.ModuleType(name) exec(code, mod.__dict__) self.assertTrue(hasattr(mod, 'initialized')) self.assertEqual(stdout.getvalue(), 'Hello world!\n')
def test_module_reuse(self): with util.uncache('__hello__'), captured_stdout() as stdout: with warnings.catch_warnings(): warnings.simplefilter('ignore', DeprecationWarning) module1 = self.machinery.FrozenImporter.load_module( '__hello__') module2 = self.machinery.FrozenImporter.load_module( '__hello__') self.assertIs(module1, module2) self.assertEqual(stdout.getvalue(), 'Hello world!\nHello world!\n')
def test_debug_mode(self): # this covers the code called when DEBUG is set old_logs_len = len(self.logs) install_module.DEBUG = True try: with captured_stdout(): self.test_record() finally: install_module.DEBUG = False self.assertGreater(len(self.logs), old_logs_len)
def test_modules_search_builtin(self): expected = 'gc - ' output = StringIO() helper = pydoc.Helper(output=output) with captured_stdout() as help_io: helper('modules garbage') result = help_io.getvalue() self.assertTrue(result.startswith(expected))
def test_replace_paths(self): old_path = os.path.join(TEST_DIR, 'a', 'module.py') new_path = os.path.join(TEST_DIR, 'a', 'spam.py') with support.captured_stdout() as output: self._do_test(maybe_test, debug=2, replace_paths=[(old_path, new_path)]) output = output.getvalue() expected = "co_filename %r changed to %r" % (old_path, new_path) self.assertIn(expected, output)
def test_coverage(self): tracer = trace.Trace(trace=0, count=1) with captured_stdout() as stdout: self._coverage(tracer) stdout = stdout.getvalue() self.assertIn("pprint.py", stdout) self.assertIn("case.py", stdout) # from unittest files = os.listdir(TESTFN) self.assertIn("pprint.cover", files) self.assertIn("unittest.case.cover", files)
def test_modules_search(self): # See Helper.listmodules(). expected = 'pydoc - ' output = StringIO() helper = pydoc.Helper(output=output) with captured_stdout() as help_io: helper('modules pydoc') result = help_io.getvalue() self.assertIn(expected, result)
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_show_formats(self): with captured_stdout() as stdout: show_formats() # the output should be a header line + one line per format num_formats = len(ARCHIVE_FORMATS.keys()) output = [ line for line in stdout.getvalue().split('\n') if line.strip().startswith('--formats=') ] self.assertEqual(len(output), num_formats)
def test_autorange_with_callback(self): def callback(a, b): print("{} {:.3f}".format(a, b)) with captured_stdout() as s: num_loops, time_taken = self.autorange(callback) self.assertEqual(num_loops, 1000) self.assertEqual(time_taken, 1.0) expected = ('10 0.010\n' '100 0.100\n' '1000 1.000\n') self.assertEqual(s.getvalue(), expected)
def test_coverage_ignore(self): # Ignore all files, nothing should be traced nor printed libpath = os.path.normpath(os.path.dirname(os.__file__)) # sys.prefix does not work when running from a checkout tracer = trace.Trace( ignoredirs=[sys.base_prefix, sys.base_exec_prefix, libpath], trace=0, count=1) with captured_stdout() as stdout: self._coverage(tracer) if os.path.exists(TESTFN): files = os.listdir(TESTFN) self.assertEqual(files, ['_importlib.cover']) # Ignore __import__
def test_show_help(self): # smoke test, just makes sure some help is displayed self.addCleanup(log.set_threshold, log._global_log.threshold) dist = Distribution() sys.argv = [] dist.help = 1 dist.script_name = 'setup.py' with captured_stdout() as s: dist.parse_command_line() output = [ line for line in s.getvalue().split('\n') if line.strip() != '' ] self.assertTrue(output)
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_module(self): with util.uncache('__hello__'), captured_stdout() as stdout: with warnings.catch_warnings(): warnings.simplefilter('ignore', DeprecationWarning) module = self.machinery.FrozenImporter.load_module('__hello__') check = { '__name__': '__hello__', '__package__': '', '__loader__': self.machinery.FrozenImporter, } for attr, value in check.items(): self.assertEqual(getattr(module, attr), value) self.assertEqual(stdout.getvalue(), 'Hello world!\n') self.assertFalse(hasattr(module, '__file__'))
def run_main(self, seconds_per_increment=1.0, switches=None, timer=None): if timer is None: timer = FakeTimer(seconds_per_increment=seconds_per_increment) if switches is None: args = [] else: args = switches[:] args.append(self.fake_stmt) # timeit.main() modifies sys.path, so save and restore it. orig_sys_path = sys.path[:] with captured_stdout() as s: timeit.main(args=args, _wrap_timer=timer.wrap_timer) sys.path[:] = orig_sys_path[:] return s.getvalue()
def test_log_info(self): d = asyncore.dispatcher() # capture output of dispatcher.log_info() (to stdout via print) l1 = "Have you got anything without spam?" l2 = "Why can't she have egg bacon spam and sausage?" l3 = "THAT'S got spam in it!" with support.captured_stdout() as stdout: d.log_info(l1, 'EGGS') d.log_info(l2) d.log_info(l3, 'SPAM') lines = stdout.getvalue().splitlines() expected = ['EGGS: %s' % l1, 'info: %s' % l2, 'SPAM: %s' % l3] self.assertEqual(lines, expected)
def test_apropos_empty_doc(self): pkgdir = os.path.join(TESTFN, 'walkpkg') os.mkdir(pkgdir) self.addCleanup(rmtree, pkgdir) init_path = os.path.join(pkgdir, '__init__.py') with open(init_path, 'w') as fobj: fobj.write("foo = 1") current_mode = stat.S_IMODE(os.stat(pkgdir).st_mode) try: os.chmod(pkgdir, current_mode & ~stat.S_IEXEC) with self.restrict_walk_packages(path=[TESTFN]), captured_stdout() as stdout: pydoc.apropos('') self.assertIn('walkpkg', stdout.getvalue()) finally: os.chmod(pkgdir, current_mode)
def exec_module(self, name): with util.uncache(name), captured_stdout() as stdout: spec = self.machinery.ModuleSpec( name, self.machinery.FrozenImporter, origin='frozen', is_package=self.machinery.FrozenImporter.is_package(name)) module = types.ModuleType(name) module.__spec__ = spec assert not hasattr(module, 'initialized') self.machinery.FrozenImporter.exec_module(module) self.assertTrue(module.initialized) self.assertTrue(hasattr(module, '__spec__')) self.assertEqual(module.__spec__.origin, 'frozen') return module, stdout.getvalue()
def test_process_message_with_decode_data_false(self): server = smtpd.DebuggingServer((support.HOST, 0), ('b', 0)) conn, addr = server.accept() channel = smtpd.SMTPChannel(server, conn, addr) with support.captured_stdout() as s: self.send_data(channel, b'From: test\n\nh\xc3\xa9llo\xff\n') stdout = s.getvalue() self.assertEqual(stdout, textwrap.dedent("""\ ---------- MESSAGE FOLLOWS ---------- b'From: test' b'X-Peer: peer-address' b'' b'h\\xc3\\xa9llo\\xff' ------------ END MESSAGE ------------ """))
def test_process_message_with_decode_data_true(self): server = smtpd.DebuggingServer((support.HOST, 0), ('b', 0), decode_data=True) conn, addr = server.accept() channel = smtpd.SMTPChannel(server, conn, addr, decode_data=True) with support.captured_stdout() as s: self.send_data(channel, b'From: test\n\nhello\n') stdout = s.getvalue() self.assertEqual(stdout, textwrap.dedent("""\ ---------- MESSAGE FOLLOWS ---------- From: test X-Peer: peer-address hello ------------ END MESSAGE ------------ """))