Exemplo n.º 1
0
    def test_unraisable(self):
        # Issue #22836: PyErr_WriteUnraisable() should give sensible reports
        class BrokenDel:
            def __del__(self):
                exc = ValueError("del is broken")
                # In Python 3, the following line would be in the report:
                raise exc

        class BrokenRepr(BrokenDel):
            def __repr__(self):
                raise AttributeError("repr() is broken")

        class BrokenExceptionDel:
            def __del__(self):
                exc = BrokenStrException()
                # In Python 3, the following line would be in the report:
                raise exc

        for test_class in (BrokenDel, BrokenRepr, BrokenExceptionDel):
            obj = test_class()
            with captured_stderr() as stderr:
                del obj
            report = stderr.getvalue()
            self.assertRegexpMatches(report, "Exception.* ignored")
            if test_class is BrokenRepr:
                self.assertIn("<object repr() failed>", report)
            else:
                self.assertIn("__del__", report)
            if test_class is BrokenExceptionDel:
                self.assertIn("BrokenStrException", report)
                self.assertIn("<exception repr() failed>", report)
            else:
                self.assertIn("ValueError", report)
                self.assertIn("del is broken", report)
            self.assertTrue(report.endswith("\n"))
Exemplo n.º 2
0
 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):
             self.model_class.objects.create(f1='a', f2='b')
Exemplo n.º 3
0
 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):
             self.model_class.objects.create(f1='a', f2='b')
Exemplo n.º 4
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()
Exemplo n.º 5
0
    def test_issue31285(self):
        # warn_explicit() shouldn't raise a SystemError in case the return
        # value of get_source() has a bad splitlines() method.
        class BadLoader:
            def get_source(self, fullname):
                class BadSource(str):
                    def splitlines(self):
                        return 42

                return BadSource('spam')

        wmod = self.module
        with original_warnings.catch_warnings(module=wmod):
            wmod.filterwarnings('default', category=UserWarning)

            with test_support.captured_stderr() as stderr:
                wmod.warn_explicit('foo',
                                   UserWarning,
                                   'bar',
                                   1,
                                   module_globals={
                                       '__loader__': BadLoader(),
                                       '__name__': 'foobar'
                                   })
            self.assertIn('UserWarning: foo', stderr.getvalue())
Exemplo n.º 6
0
    def test_unraisable(self):
        # Issue #22836: PyErr_WriteUnraisable() should give sensible reports
        class BrokenDel:
            def __del__(self):
                exc = ValueError("del is broken")
                # In Python 3, the following line would be in the report:
                raise exc

        class BrokenRepr(BrokenDel):
            def __repr__(self):
                raise AttributeError("repr() is broken")

        class BrokenExceptionDel:
            def __del__(self):
                exc = BrokenStrException()
                # In Python 3, the following line would be in the report:
                raise exc

        for test_class in (BrokenDel, BrokenRepr, BrokenExceptionDel):
            obj = test_class()
            with captured_stderr() as stderr:
                del obj
            report = stderr.getvalue()
            self.assertRegexpMatches(report, "Exception.* ignored")
            if test_class is BrokenRepr:
                self.assertIn("<object repr() failed>", report)
            else:
                self.assertIn("__del__", report)
            if test_class is BrokenExceptionDel:
                self.assertIn("BrokenStrException", report)
                self.assertIn("<exception repr() failed>", report)
            else:
                self.assertIn("ValueError", report)
                self.assertIn("del is broken", report)
            self.assertTrue(report.endswith("\n"))
Exemplo n.º 7
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()
 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())
Exemplo n.º 9
0
 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):
             self.ut.field_defs = (self.f1, self.f2)
Exemplo n.º 10
0
 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):
             self.ut.field_defs = (self.f1, self.f2)
Exemplo n.º 11
0
 def test_unicode_args(self):
     e = RuntimeError(u"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 test_support.captured_stderr() as s:
         sys.excepthook(RuntimeError, u"Drink \u2615", None)
     self.assertEqual(s.getvalue(), "RuntimeError\n")
     # It is fine with ascii values, of course
     with test_support.captured_stderr() as s:
         sys.excepthook(RuntimeError, u"Drink java", None)
     self.assertEqual(s.getvalue(), "RuntimeError: Drink java\n")
Exemplo n.º 12
0
 def test_invalid_args(self):
     # Popen() called with invalid arguments should raise TypeError
     # but Popen.__del__ should not complain (issue #12085)
     with test_support.captured_stderr() as s:
         self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
         argcount = subprocess.Popen.__init__.__code__.co_argcount
         too_many_args = [0] * (argcount + 1)
         self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
     self.assertEqual(s.getvalue(), "")
Exemplo n.º 13
0
 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):
             self.ut.field_defs.remove(self.f2)
Exemplo n.º 14
0
 def test_unicode_args(self):
     e = RuntimeError(u"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 test_support.captured_stderr() as s:
         sys.excepthook(RuntimeError, u"Drink \u2615", None)
     self.assertEqual(s.getvalue(), "RuntimeError\n")  
     # It is fine with ascii values, of course
     with test_support.captured_stderr() as s:
         sys.excepthook(RuntimeError, u"Drink java", None)
     self.assertEqual(s.getvalue(), "RuntimeError: Drink java\n")  
Exemplo n.º 15
0
 def test_invalid_args(self):
     # Popen() called with invalid arguments should raise TypeError
     # but Popen.__del__ should not complain (issue #12085)
     with test_support.captured_stderr() as s:
         self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
         argcount = subprocess.Popen.__init__.__code__.co_argcount
         too_many_args = [0] * (argcount + 1)
         self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
     self.assertEqual(s.getvalue(), '')
Exemplo n.º 16
0
 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):
             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(), '')
Exemplo n.º 18
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(), '')
Exemplo n.º 19
0
    def _test_suggest(self, code, exc_typ, globals=None):
        if globals is None: globals = {}

        sporktools._World.interp.create_link = mock_idle.Func("LINK")

        with self.assertRaises(exc_typ) as cm:
            exec code in globals
        tb = sys.exc_traceback
        import traceback
        filename = traceback.extract_tb(tb)[-1][0]
        with captured_stderr() as err:
            Suggest.exception_suggest(exc_typ, cm.exception, tb, code, filename)
        return err.getvalue().strip()
Exemplo n.º 20
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(), '')
 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(), '')
Exemplo n.º 22
0
 def test_directory(self):
     os.mkdir(test_support.TESTFN)
     self.addCleanup(test_support.rmtree, test_support.TESTFN)
     c_filename = os.path.join(test_support.TESTFN, "file.c")
     with open(c_filename, "w") as file:
         file.write("int xx;\n")
     with open(os.path.join(test_support.TESTFN, "file.py"), "w") as file:
         file.write("xx = 'unaltered'\n")
     script = os.path.join(scriptsdir, "fixcid.py")
     # ignore dbg() messages
     with test_support.captured_stderr() as stderr:
         output = self.run_script(args=(test_support.TESTFN, ))
     self.assertMultiLineEqual(
         output, "{}:\n"
         "1\n"
         '< int xx;\n'
         '> int yy;\n'.format(c_filename), "stderr: %s" % stderr.getvalue())
Exemplo n.º 23
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, e:
                self.fail("exception should not be a MyException")
            except KeyError:
                pass
    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, e:
                self.fail("exception should not be a MyException")
            except KeyError:
                pass
Exemplo n.º 25
0
 def test_unhandled(self):
     # Check for sensible reporting of unhandled exceptions
     for exc_type in (ValueError, BrokenStrException):
         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"))
Exemplo n.º 26
0
 def test_unhandled(self):
     # Check for sensible reporting of unhandled exceptions
     for exc_type in (ValueError, BrokenStrException):
         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"))
Exemplo n.º 27
0
    def test_issue31285(self):
        # warn_explicit() shouldn't raise a SystemError in case the return
        # value of get_source() has a bad splitlines() method.
        class BadLoader:
            def get_source(self, fullname):
                class BadSource(str):
                    def splitlines(self):
                        return 42
                return BadSource('spam')

        wmod = self.module
        with original_warnings.catch_warnings(module=wmod):
            wmod.filterwarnings('default', category=UserWarning)

            with test_support.captured_stderr() as stderr:
                wmod.warn_explicit(
                    'foo', UserWarning, 'bar', 1,
                    module_globals={'__loader__': BadLoader(),
                                    '__name__': 'foobar'})
            self.assertIn('UserWarning: foo', stderr.getvalue())
Exemplo n.º 28
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",
     ])
    def testInfiniteRecursion(self):
        def f():
            return f()
        self.assertRaises(RuntimeError, f)

        def g():
            try:
                return g()
            except ValueError:
                return -1

        # The test prints an unraisable recursion error when
        # doing "except ValueError", this is because subclass
        # checking has recursion checking too.
        with captured_stderr():
            try:
                g()
            except RuntimeError:
                pass
            except:
                self.fail("Should have raised KeyError")
            else:
                self.fail("Should have raised KeyError")
Exemplo n.º 30
0
    def testInfiniteRecursion(self):
        def f():
            return f()
        self.assertRaises(RuntimeError, f)

        def g():
            try:
                return g()
            except ValueError:
                return -1

        # The test prints an unraisable recursion error when
        # doing "except ValueError", this is because subclass
        # checking has recursion checking too.
        with captured_stderr():
            try:
                g()
            except RuntimeError:
                pass
            except:
                self.fail("Should have raised KeyError")
            else:
                self.fail("Should have raised KeyError")
Exemplo n.º 31
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",
        ])
Exemplo n.º 32
0
 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())
Exemplo n.º 33
0
 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_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())
Exemplo n.º 35
0
 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())
Exemplo n.º 36
0
 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())
Exemplo n.º 37
0
            __metaclass__ = Meta
            pass

        with captured_stderr() as stderr:
            try:
                raise KeyError()
            except MyException, 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")

        with captured_stderr() as stderr:
            def g():
                try:
                    return g()
                except RuntimeError:
                    return sys.exc_info()
            e, v, tb = g()
            self.assertTrue(e is RuntimeError, e)
            self.assertIn("maximum recursion depth exceeded", str(v))

    def test_new_returns_invalid_instance(self):
        # See issue #11627.
        class MyException(Exception):
            def __new__(cls, *args):
                return object()
Exemplo n.º 38
0
 def test_main_exception_fixed_reps(self):
     with captured_stderr() as error_stringio:
         s = self.run_main(switches=['-n1', '1.0/0.0'])
     self.assert_exc_string(error_stringio.getvalue(), 'ZeroDivisionError')
Exemplo n.º 39
0
 def test_main_exception_fixed_reps(self):
     with captured_stderr() as error_stringio:
         s = self.run_main(switches=['-n1', '1.0/0.0'])
     self.assert_exc_string(error_stringio.getvalue(), 'ZeroDivisionError')
            __metaclass__ = Meta
            pass

        with captured_stderr() as stderr:
            try:
                raise KeyError()
            except MyException, 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")

        with captured_stderr() as stderr:
            def g():
                try:
                    return g()
                except RuntimeError:
                    return sys.exc_info()
            e, v, tb = g()
            self.assertTrue(e is RuntimeError, e)
            self.assertIn("maximum recursion depth exceeded", str(v))

    def test_new_returns_invalid_instance(self):
        # See issue #11627.
        class MyException(Exception):
            def __new__(cls, *args):
                return object()
Exemplo n.º 41
0
 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())