本文整理汇总了Python中test.test_support.captured_stderr函数的典型用法代码示例。如果您正苦于以下问题:Python captured_stderr函数的具体用法?Python captured_stderr怎么用?Python captured_stderr使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了captured_stderr函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_broken_getattr_handling
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()
示例2: test_cannot_insert_duplicate_row
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')
示例3: test_unraisable
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"))
示例4: test_cannot_create_unique
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)
示例5: test_cannot_remove_unique
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)
示例6: test_unicode_args
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")
示例7: test_apropos_with_bad_package
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(), '')
示例8: _test_suggest
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()
示例9: test_apropos_with_unreadable_dir
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(), '')
示例10: test_badisinstance
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
示例11: test_unhandled
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"))
示例12: test_issue31285
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())
示例13: test_delegation_of_close_to_non_generator
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",
])
示例14: testInfiniteRecursion
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")
示例15: captured_stderr
__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()