本文整理汇总了Python中test.support.captured_stderr函数的典型用法代码示例。如果您正苦于以下问题:Python captured_stderr函数的具体用法?Python captured_stderr怎么用?Python captured_stderr使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了captured_stderr函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_issue31285
def test_issue31285(self):
# warn_explicit() should neither raise a SystemError nor cause an
# assertion failure, in case the return value of get_source() has a
# bad splitlines() method.
def get_bad_loader(splitlines_ret_val):
class BadLoader:
def get_source(self, fullname):
class BadSource(str):
def splitlines(self):
return splitlines_ret_val
return BadSource('spam')
return BadLoader()
wmod = self.module
with original_warnings.catch_warnings(module=wmod):
wmod.filterwarnings('default', category=UserWarning)
with support.captured_stderr() as stderr:
wmod.warn_explicit(
'foo', UserWarning, 'bar', 1,
module_globals={'__loader__': get_bad_loader(42),
'__name__': 'foobar'})
self.assertIn('UserWarning: foo', stderr.getvalue())
show = wmod._showwarnmsg
try:
del wmod._showwarnmsg
with support.captured_stderr() as stderr:
wmod.warn_explicit(
'eggs', UserWarning, 'bar', 1,
module_globals={'__loader__': get_bad_loader([42]),
'__name__': 'foobar'})
self.assertIn('UserWarning: eggs', stderr.getvalue())
finally:
wmod._showwarnmsg = show
示例2: test_warn
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')
示例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")
# The following line is included in the traceback report:
raise exc
class BrokenExceptionDel:
def __del__(self):
exc = BrokenStrException()
# The following line is included in the traceback report:
raise exc
for test_class in (BrokenDel, BrokenExceptionDel):
with self.subTest(test_class):
obj = test_class()
with captured_stderr() as stderr:
del obj
report = stderr.getvalue()
self.assertIn("Exception ignored", report)
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"))
示例4: test_warnings_on_cleanup
def test_warnings_on_cleanup(self) -> None:
# Two kinds of warning on shutdown
# Issue 10888: may write to stderr if modules are nulled out
# ResourceWarning will be triggered by __del__
with self.do_create() as dir:
if os.sep != '\\':
# Embed a backslash in order to make sure string escaping
# in the displayed error message is dealt with correctly
suffix = '\\check_backslash_handling'
else:
suffix = ''
d = self.do_create(dir=dir, suf=suffix)
#Check for the Issue 10888 message
modules = [os, os.path]
if has_stat:
modules.append(stat)
with support.captured_stderr() as err:
with NulledModules(*modules):
d.cleanup()
message = err.getvalue().replace('\\\\', '\\')
self.assertIn("while cleaning up", message)
self.assertIn(d.name, message)
# Check for the resource warning
with support.check_warnings(('Implicitly', ResourceWarning), quiet=False):
warnings.filterwarnings("always", category=ResourceWarning)
d.__del__()
self.assertFalse(os.path.exists(d.name),
"TemporaryDirectory %s exists after __del__" % d.name)
示例5: 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 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))
示例6: 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()
self.assertIn('ZeroDivisionError', output.getvalue())
示例7: test_fatal_coro_warning
def test_fatal_coro_warning(self):
# Issue 27811
async def func(): pass
with warnings.catch_warnings(), support.captured_stderr() as stderr:
warnings.filterwarnings("error")
func()
support.gc_collect()
self.assertIn("was never awaited", stderr.getvalue())
示例8: 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):
with transaction.atomic():
self.model_class.objects.create(f1='a', f2='b')
示例9: test_get
def test_get(self):
self.con = http.client.HTTPConnection(self.HOST, self.PORT)
self.con.connect()
with support.captured_stderr() as err:
self.con.request("GET", "/")
self.con.getresponse()
self.assertTrue(err.getvalue().endswith('"GET / HTTP/1.1" 200 -\n'))
示例10: test_addpackage_import_bad_pth_file
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:
self.assertFalse(site.addpackage(pth_dir, pth_fn, set()))
self.assertEqual(err_out.getvalue(), "")
for path in sys.path:
if isinstance(path, str):
self.assertNotIn("abc\x00def", path)
示例11: test_unicode_args
def test_unicode_args(self):
e = RuntimeError("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 support.captured_stderr() as s:
sys.excepthook(RuntimeError, "Drink \u2615", None)
self.assertEqual(s.getvalue(), "RuntimeError\n")
# It is fine with ascii values, of course
with support.captured_stderr() as s:
sys.excepthook(RuntimeError, "Drink java", None)
self.assertEqual(s.getvalue(), "RuntimeError: Drink java\n")
示例12: 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):
with transaction.atomic():
self.ut.field_defs = (self.f1, self.f2)
示例13: test_debuglevel
def test_debuglevel(self):
mock_socket.reply_with(b"220 Hello world")
smtp = smtplib.SMTP()
smtp.set_debuglevel(1)
with support.captured_stderr() as stderr:
smtp.connect(HOST, self.port)
smtp.close()
expected = re.compile(r"^connect:", re.MULTILINE)
self.assertRegex(stderr.getvalue(), expected)
示例14: test_command_line_handling_do_discovery_too_many_arguments
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())
示例15: test_keywords_invalid_type
def test_keywords_invalid_type(self):
attrs = {'name': 'Monty', 'version': '1.0',
'keywords': ('spam', 'eggs', 'life of brian')}
with captured_stderr() as error:
d = Distribution(attrs)
# should have warning about passing a non-list
self.assertIn('should be a list', error.getvalue())
# should be converted to a list
self.assertIsInstance(d.metadata.keywords, list)
self.assertEqual(d.metadata.keywords, list(attrs['keywords']))