示例#1
0
 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')
示例#2
0
    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())
示例#3
0
    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_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_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_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_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')
示例#8
0
 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_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_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])
示例#11
0
    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_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')
示例#13
0
 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(), '')
示例#14
0
    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 run_script(self, input="", *, args=("-", ), substfile="xx yy\n"):
        substfilename = support.TESTFN + ".subst"
        with open(substfilename, "w") as file:
            file.write(substfile)
        self.addCleanup(support.unlink, substfilename)

        argv = ["fixcid.py", "-s", substfilename] + list(args)
        script = os.path.join(scriptsdir, "fixcid.py")
        with support.swap_attr(sys, "argv", argv), \
                support.swap_attr(sys, "stdin", StringIO(input)), \
                support.captured_stdout() as output, \
                support.captured_stderr():
            try:
                runpy.run_path(script, run_name="__main__")
            except SystemExit as exit:
                self.assertEqual(exit.code, 0)
        return output.getvalue()
 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")
     # 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")
示例#17
0
 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"))
示例#18
0
    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
                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)
                    self.assertIn("<exception str() failed>", report)
                else:
                    self.assertIn("ValueError", report)
                    self.assertIn("del is broken", report)
                self.assertTrue(report.endswith("\n"))
示例#19
0
    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",
        ])
示例#20
0
 def test_captured_stderr(self):
     with support.captured_stderr() as stderr:
         print("hello", file=sys.stderr)
     self.assertEqual(stderr.getvalue(), "hello\n")
 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_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_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')
示例#24
0
 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()