本文整理汇总了Python中test.support.captured_stderr函数的典型用法代码示例。如果您正苦于以下问题:Python captured_stderr函数的具体用法?Python captured_stderr怎么用?Python captured_stderr使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了captured_stderr函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:Apoorvadabhere,项目名称:cpython,代码行数:35,代码来源:__init__.py
示例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')
开发者ID:SylvainDe,项目名称:cpython,代码行数:14,代码来源:test_config.py
示例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"))
开发者ID:Eyepea,项目名称:cpython,代码行数:31,代码来源:test_exceptions.py
示例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)
开发者ID:FlorianLudwig,项目名称:mypy,代码行数:30,代码来源:test_tempfile.py
示例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))
开发者ID:cpcloud,项目名称:cpython,代码行数:29,代码来源:test_exceptions.py
示例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())
开发者ID:isaiah,项目名称:jython3,代码行数:30,代码来源:test_pep380.py
示例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())
开发者ID:Connor124,项目名称:Gran-Theft-Crop-Toe,代码行数:8,代码来源:test_coroutines.py
示例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')
开发者ID:tfroehlich82,项目名称:django-mutant,代码行数:8,代码来源:test_model_defs.py
示例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'))
开发者ID:yoongkang,项目名称:cpython,代码行数:9,代码来源:test_httpservers.py
示例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)
开发者ID:funkyHat,项目名称:cpython,代码行数:9,代码来源:test_site.py
示例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")
开发者ID:isaiah,项目名称:jython3,代码行数:18,代码来源:test_exceptions_jy.py
示例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)
开发者ID:tfroehlich82,项目名称:django-mutant,代码行数:9,代码来源:test_model_defs.py
示例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)
开发者ID:CCNITSilchar,项目名称:cpython,代码行数:9,代码来源:test_smtplib.py
示例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())
开发者ID:kwatch,项目名称:cpython,代码行数:9,代码来源:test_discovery.py
示例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']))
开发者ID:willingc,项目名称:cpython,代码行数:10,代码来源:test_dist.py
示例16: test_platforms_invalid_types
def test_platforms_invalid_types(self):
attrs = {'name': 'Monty', 'version': '1.0',
'platforms': ('GNU/Linux', 'Some Evil Platform')}
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.platforms, list)
self.assertEqual(d.metadata.platforms, list(attrs['platforms']))
开发者ID:willingc,项目名称:cpython,代码行数:10,代码来源:test_dist.py
示例17: 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):
with transaction.atomic():
self.ut.field_defs.remove(self.f2)
开发者ID:tfroehlich82,项目名称:django-mutant,代码行数:10,代码来源:test_model_defs.py
示例18: test_falls_back_to_stdin
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())
开发者ID:5outh,项目名称:Databases-Fall2014,代码行数:11,代码来源:test_getpass.py
示例19: test_classifier_invalid_type
def test_classifier_invalid_type(self):
attrs = {'name': 'Boa', 'version': '3.0',
'classifiers': ('Programming Language :: Python :: 3',)}
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.classifiers, list)
self.assertEqual(d.metadata.classifiers,
list(attrs['classifiers']))
开发者ID:willingc,项目名称:cpython,代码行数:11,代码来源:test_dist.py
示例20: 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(), "")
开发者ID:alfonsodiecko,项目名称:PYTHON_DIST,代码行数:20,代码来源:test_pydoc.py
注:本文中的test.support.captured_stderr函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论