def test_config_8_ok(self): with captured_stdout() as output: self.apply_config(self.config1) logger = logging.getLogger("compiler.parser") # Both will output a message logger.info(self.next_message()) logger.error(self.next_message()) self.assert_log_lines([ ('INFO', '1'), ('ERROR', '2'), ], stream=output) # Original logger output is empty. self.assert_log_lines([]) with captured_stdout() as output: self.apply_config(self.config8) logger = logging.getLogger("compiler.parser") self.assertFalse(logger.disabled) # Both will output a message logger.info(self.next_message()) logger.error(self.next_message()) logger = logging.getLogger("compiler.lexer") # Both will output a message logger.info(self.next_message()) logger.error(self.next_message()) self.assert_log_lines([ ('INFO', '3'), ('ERROR', '4'), ('INFO', '5'), ('ERROR', '6'), ], stream=output) # Original logger output is empty. self.assert_log_lines([])
def test_debug_flag(self): with captured_stdout() as out: re.compile('foo', re.DEBUG) self.assertEqual(out.getvalue().splitlines(), ['literal 102', 'literal 111', 'literal 111']) # Debug output is output again even a second time (bypassing # the cache -- issue #20426). with captured_stdout() as out: re.compile('foo', re.DEBUG) self.assertEqual(out.getvalue().splitlines(), ['literal 102', 'literal 111', 'literal 111'])
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_debug_print(self): file_list = FileList() with captured_stdout() as stdout: file_list.debug_print("xxx") stdout.seek(0) self.assertEqual(stdout.read(), "") debug.DEBUG = True try: with captured_stdout() as stdout: file_list.debug_print("xxx") stdout.seek(0) self.assertEqual(stdout.read(), "xxx\n") finally: debug.DEBUG = False
def test_tarfile_vs_tar(self): root_dir, base_dir = self._create_files() base_name = os.path.join(self.mkdtemp(), 'archive') tarball = make_archive(base_name, 'gztar', root_dir, base_dir) # check if the compressed tarball was created self.assertEqual(tarball, base_name + '.tar.gz') self.assertTrue(os.path.isfile(tarball)) # now create another tarball using `tar` tarball2 = os.path.join(root_dir, 'archive2.tar') tar_cmd = ['tar', '-cf', 'archive2.tar', base_dir] with support.change_cwd(root_dir), captured_stdout(): spawn(tar_cmd) self.assertTrue(os.path.isfile(tarball2)) # let's compare both tarballs self.assertEqual(self._tarinfo(tarball), self._tarinfo(tarball2)) # trying an uncompressed one tarball = make_archive(base_name, 'tar', root_dir, base_dir) self.assertEqual(tarball, base_name + '.tar') self.assertTrue(os.path.isfile(tarball)) # now for a dry_run tarball = make_archive(base_name, 'tar', root_dir, base_dir, dry_run=True) self.assertEqual(tarball, base_name + '.tar') self.assertTrue(os.path.isfile(tarball))
def test_eval(self): with open(_fname + '.dir', 'w') as stream: stream.write("str(__import__('sys').stdout.write('Hacked!')), 0\n") with test_support.captured_stdout() as stdout: with self.assertRaises(ValueError): dumbdbm.open(_fname).close() self.assertEqual(stdout.getvalue(), '')
def test_module_reuse(self): with util.uncache(u'__hello__'), captured_stdout() as stdout: module1 = machinery.FrozenImporter.load_module(u'__hello__') module2 = machinery.FrozenImporter.load_module(u'__hello__') self.assertTrue(module1 is module2) self.assertEqual(stdout.getvalue(), u'Hello world!\nHello world!\n')
def test_debug_mode(self): 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 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() return lines
def test_main(args=[]): test_classes = [ PingTest, LookupUsersTest, NamespaceTest, BlockChains, Prices, NamesOwnedTest, NameHistoryTest, AuthInternal, BlockChainsInternal, Zonefiles, WalletInternal, NodeInternal ] test_map = {} for t in test_classes: test_map[t.__name__] = t with test_support.captured_stdout() as out: try: test_support.run_unittest(PingTest) except Exception as e: traceback.print_exc(file=sys.stdout) out = out.getvalue() if out[-3:-1] != "OK": print(out) print( "Failure of the ping test means the rest of the unit tests will " + "fail. Is the blockstack api daemon running? (did you run " + "`blockstack api start`)") sys.exit(1) if len(args) == 1 and args[0] == "--list": print("Tests supported: ") for testname in test_map.keys(): print(testname) return test_runner = test_support.run_unittest if "--xunit-path" in args: ainx = args.index("--xunit-path") del args[ainx] from xmlrunner import XMLTestRunner test_runner = XMLTestRunner(output=args[ainx]).run del args[ainx] if "--api_password" in args: ainx = args.index("--api_password") del args[ainx] global API_PASSWORD API_PASSWORD = args[ainx] del args[ainx] if len(args) == 0 or args[0] == "--all": args = [testname for testname in test_map.keys()] test_suite = unittest.TestSuite() for test_name in args: test_suite.addTest(unittest.TestLoader().loadTestsFromTestCase( test_map[test_name])) result = test_runner(test_suite) if result: # test_support.run_unittest returns None if result.wasSuccessful(): sys.exit(0) else: sys.exit(1)
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_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.assertEquals(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.assertEquals(stdout.readlines()[0], wanted)
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_debug_print(self): class MyCCompiler(CCompiler): executables = {} compiler = MyCCompiler() with captured_stdout() as stdout: compiler.debug_print("xxx") stdout.seek(0) self.assertEqual(stdout.read(), "") debug.DEBUG = True try: with captured_stdout() as stdout: compiler.debug_print("xxx") stdout.seek(0) self.assertEqual(stdout.read(), "xxx\n") finally: debug.DEBUG = False
def test_debug_print(self): class MyCCompiler(CCompiler): executables = {} compiler = MyCCompiler() with captured_stdout() as stdout: compiler.debug_print('xxx') stdout.seek(0) self.assertEqual(stdout.read(), '') debug.DEBUG = True try: with captured_stdout() as stdout: compiler.debug_print('xxx') stdout.seek(0) self.assertEqual(stdout.read(), 'xxx\n') finally: debug.DEBUG = False
def test_module(self): with util.uncache(u'__hello__'), captured_stdout() as stdout: module = machinery.FrozenImporter.load_module(u'__hello__') check = {u'__name__': u'__hello__', u'__file__': u'<frozen>', u'__package__': u'', u'__loader__': machinery.FrozenImporter} for attr, value in check.items(): self.assertEqual(getattr(module, attr), value) self.assertEqual(stdout.getvalue(), u'Hello world!\n')
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_namedtuple_public_underscore(self): NT = namedtuple('NT', ['abc', 'def'], rename=True) with captured_stdout() as help_io: help(NT) helptext = help_io.getvalue() self.assertIn('_1', helptext) self.assertIn('_replace', helptext) self.assertIn('_asdict', helptext)
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_tabulate(self): # Test tabulate if sys.version < '2.6': #*fixme* return with test_support.captured_stdout() as s: tabulate(cross((0, 3), (0, 3)) * oneToOne) self.assertEqual(s.getvalue(), '0 \t0\n1 \t1\n2 \t2\n3 \t3\n', 'tabulate malfunctioning')
def test_show_help(self): 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_debug_mode(self): with open(TESTFN, 'w') as f: f.write('[global]\n') f.write('command_packages = foo.bar, splat') files = [TESTFN] sys.argv.append('build') with captured_stdout() as stdout: self.create_distribution(files) stdout.seek(0) self.assertEqual(stdout.read(), '') distutils.dist.DEBUG = True try: with captured_stdout() as stdout: self.create_distribution(files) stdout.seek(0) self.assertEqual(stdout.read(), '') finally: distutils.dist.DEBUG = False
def test_show_formats(self): with captured_stdout() as stdout: show_formats() 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_read_comm_kludge_compname_odd(self): b = 'FORM' + struct.pack('>L', 4) + 'AIFC' b += 'COMM' + struct.pack('>LhlhhLL', 18, 0, 0, 0, 0, 0, 0) b += 'NONE' + struct.pack('B', 3) + 'odd' b += 'SSND' + struct.pack('>L', 8) + '\x00' * 8 with captured_stdout() as s: f = aifc.open(io.BytesIO(b)) self.assertEqual(s.getvalue(), 'Warning: bad COMM chunk size\n') self.assertEqual(f.getcompname(), 'odd')
def test_main(args = []): test_classes = [PingTest, LookupUsersTest, NamespaceTest, BlockChains, Prices, NamesOwnedTest, NameHistoryTest, AuthInternal, BlockChainsInternal, Zonefiles, WalletInternal, NodeInternal] test_map = {} for t in test_classes: test_map[t.__name__] = t with test_support.captured_stdout() as out: try: test_support.run_unittest(PingTest) except Exception as e: traceback.print_exc(file=sys.stdout) out = out.getvalue() if out[-3:-1] != "OK": print(out) print("Failure of the ping test means the rest of the unit tests will " + "fail. Is the blockstack api daemon running? (did you run " + "`blockstack api start`)") sys.exit(1) if len(args) == 1 and args[0] == "--list": print("Tests supported: ") for testname in test_map.keys(): print(testname) return test_runner = test_support.run_unittest if "--xunit-path" in args: ainx = args.index("--xunit-path") del args[ainx] from xmlrunner import XMLTestRunner test_runner = XMLTestRunner(output=args[ainx]).run del args[ainx] if "--api_password" in args: ainx = args.index("--api_password") del args[ainx] global API_PASSWORD API_PASSWORD = args[ainx] del args[ainx] if len(args) == 0 or args[0] == "--all": args = [ testname for testname in test_map.keys() ] test_suite = unittest.TestSuite() for test_name in args: test_suite.addTest( unittest.TestLoader().loadTestsFromTestCase(test_map[test_name]) ) result = test_runner( test_suite ) if result: # test_support.run_unittest returns None if result.wasSuccessful(): sys.exit(0) else: sys.exit(1)
def test_get_code(self): # Make sure that the code object is good. name = u'__hello__' with captured_stdout() as stdout: code = machinery.FrozenImporter.get_code(name) mod = imp.new_module(name) exec(code, mod.__dict__) self.assertTrue(hasattr(mod, u'initialized')) self.assertEqual(stdout.getvalue(), u'Hello world!\n')
def test_coverage(self): tracer = trace.Trace(trace=0, count=1) with captured_stdout() as stdout: self._coverage(tracer) stdout = stdout.getvalue() self.assertTrue("pprint.py" in stdout) self.assertTrue("case.py" in stdout) # from unittest files = os.listdir(TESTFN) self.assertTrue("pprint.cover" in files) self.assertTrue("unittest.case.cover" in files)
def test_read_wrong_marks(self): b = 'FORM' + struct.pack('>L', 4) + 'AIFF' b += 'COMM' + struct.pack('>LhlhhLL', 18, 0, 0, 0, 0, 0, 0) b += 'SSND' + struct.pack('>L', 8) + '\x00' * 8 b += 'MARK' + struct.pack('>LhB', 3, 1, 1) with captured_stdout() as s: f = aifc.open(io.BytesIO(b)) self.assertEqual(s.getvalue(), 'Warning: MARK chunk contains ' 'only 0 markers instead of 1\n') self.assertEqual(f.getmarkers(), None)
def test_debug_mode(self): 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_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_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() as stdout: self.test_record() finally: install_module.DEBUG = False self.assertTrue(len(self.logs) > old_logs_len)
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_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.prefix, sys.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, [])
def test_config1_ok(self, config=config1): # A config file defining a sub-parser as well. with captured_stdout() as output: self.apply_config(config) logger = logging.getLogger("compiler.parser") # Both will output a message logger.info(self.next_message()) logger.error(self.next_message()) self.assert_log_lines([("INFO", "1"), ("ERROR", "2")], stream=output) # Original logger output is empty. self.assert_log_lines([])
def test_show_help(self): # smoke test, just makes sure some help is displayed 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(len(output) > 0)
def test_frozen(self): with captured_stdout() as stdout: try: import __hello__ except ImportError, x: self.fail("import __hello__ failed:" + str(x)) try: import __phello__ except ImportError, x: self.fail("import __phello__ failed:" + str(x))
def test_debug_mode(self): with open(TESTFN, "w") as f: f.write("[global]\n") f.write("command_packages = foo.bar, splat") self.addCleanup(unlink, TESTFN) files = [TESTFN] sys.argv.append("build") with captured_stdout() as stdout: self.create_distribution(files) stdout.seek(0) self.assertEqual(stdout.read(), '') distutils.dist.DEBUG = True try: with captured_stdout() as stdout: self.create_distribution(files) stdout.seek(0) self.assertEqual(stdout.read(), '') finally: distutils.dist.DEBUG = False
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_tarfile_vs_tar(self): tmpdir, tmpdir2, base_name = self._create_files() old_dir = os.getcwd() os.chdir(tmpdir) try: _make_tarball(base_name, 'dist') finally: os.chdir(old_dir) # check if the compressed tarball was created tarball = base_name + '.tar.gz' self.assertTrue(os.path.exists(tarball)) # now create another tarball using `tar` tarball2 = os.path.join(tmpdir, 'archive2.tar.gz') tar_cmd = ['tar', '-cf', 'archive2.tar', 'dist'] gzip_cmd = ['gzip', '-f9', 'archive2.tar'] old_dir = os.getcwd() os.chdir(tmpdir) try: with captured_stdout() as s: spawn(tar_cmd) spawn(gzip_cmd) finally: os.chdir(old_dir) self.assertTrue(os.path.exists(tarball2)) # let's compare both tarballs self.assertEqual(self._tarinfo(tarball), self._tarinfo(tarball2)) # trying an uncompressed one base_name = os.path.join(tmpdir2, 'archive') old_dir = os.getcwd() os.chdir(tmpdir) try: _make_tarball(base_name, 'dist', compress=None) finally: os.chdir(old_dir) tarball = base_name + '.tar' self.assertTrue(os.path.exists(tarball)) # now for a dry_run base_name = os.path.join(tmpdir2, 'archive') old_dir = os.getcwd() os.chdir(tmpdir) try: _make_tarball(base_name, 'dist', compress=None, dry_run=True) finally: os.chdir(old_dir) tarball = base_name + '.tar' self.assertTrue(os.path.exists(tarball))
def test_config4_ok(self): # A config file specifying a custom formatter class. with captured_stdout() as output: self.apply_config(self.config4) logger = logging.getLogger() try: raise RuntimeError() except RuntimeError: logging.exception("just testing") sys.stdout.seek(0) self.assertEquals(output.getvalue(), "ERROR:root:just testing\nGot a [RuntimeError]\n") # Original logger output is empty self.assert_log_lines([])
def test_config1_ok(self, config=config1): # A config file defining a sub-parser as well. with captured_stdout() as output: self.apply_config(config) logger = logging.getLogger("compiler.parser") # Both will output a message logger.info(self.next_message()) logger.error(self.next_message()) self.assert_log_lines([ ('INFO', '1'), ('ERROR', '2'), ], stream=output) # Original logger output is empty. self.assert_log_lines([])
def test_config0_ok(self): # A simple config file which overrides the default settings. with captured_stdout() as output: self.apply_config(self.config0) logger = logging.getLogger() # Won't output anything logger.info(self.next_message()) # Outputs a message logger.error(self.next_message()) self.assert_log_lines([ ('ERROR', '2'), ], stream=output) # Original logger output is empty. self.assert_log_lines([])
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_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(), '')