本文整理汇总了Python中testtools.compat.StringIO类的典型用法代码示例。如果您正苦于以下问题:Python StringIO类的具体用法?Python StringIO怎么用?Python StringIO使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了StringIO类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _run_core
def _run_core(self):
# Add an observer to trap all logged errors.
self.case.reactor = self._reactor
error_observer = _log_observer
full_log = StringIO()
full_observer = log.FileLogObserver(full_log)
spinner = self._make_spinner()
successful, unhandled = run_with_log_observers(
[error_observer.gotEvent, full_observer.emit], self._blocking_run_deferred, spinner
)
self.case.addDetail("twisted-log", text_content(full_log.getvalue()))
logged_errors = error_observer.flushErrors()
for logged_error in logged_errors:
successful = False
self._got_user_failure(logged_error, tb_label="logged-error")
if unhandled:
successful = False
for debug_info in unhandled:
f = debug_info.failResult
info = debug_info._getDebugTracebacks()
if info:
self.case.addDetail("unhandled-error-in-deferred-debug", text_content(info))
self._got_user_failure(f, "unhandled-error-in-deferred")
junk = spinner.clear_junk()
if junk:
successful = False
self._log_user_exception(UncleanReactorError(junk))
if successful:
self.result.addSuccess(self.case, details=self.case.getDetails())
示例2: test_run_list
def test_run_list(self):
self.useFixture(SampleTestFixture())
out = StringIO()
run.main(['prog', '-l', 'testtools.runexample.test_suite'], out)
self.assertEqual("""testtools.runexample.TestFoo.test_bar
testtools.runexample.TestFoo.test_quux
""", out.getvalue())
示例3: test_run_load_list
def test_run_load_list(self):
self.useFixture(SampleTestFixture())
out = StringIO()
# We load two tests - one that exists and one that doesn't, and we
# should get the one that exists and neither the one that doesn't nor
# the unmentioned one that does.
tempdir = self.useFixture(fixtures.TempDir())
tempname = tempdir.path + '/tests.list'
f = open(tempname, 'wb')
try:
f.write(_b("""
testtools.runexample.TestFoo.test_bar
testtools.runexample.missingtest
"""))
finally:
f.close()
try:
run.main(['prog', '-l', '--load-list', tempname,
'testtools.runexample.test_suite'], out)
except SystemExit:
exc_info = sys.exc_info()
raise AssertionError(
"-l --load-list tried to exit. %r" % exc_info[1])
self.assertEqual("""testtools.runexample.TestFoo.test_bar
""", out.getvalue())
示例4: test_preserving_existing_handlers
def test_preserving_existing_handlers(self):
stream = StringIO()
self.logger.addHandler(logging.StreamHandler(stream))
self.logger.setLevel(logging.INFO)
fixture = LogHandler(self.CustomHandler(), nuke_handlers=False)
with fixture:
logging.info("message")
self.assertEqual(["message"], fixture.handler.msgs)
self.assertEqual("message\n", stream.getvalue())
示例5: _run_external_case
def _run_external_case(self):
"""Run the prepared test case in a seperate module"""
sys.path.insert(0, self.dir)
self.addCleanup(sys.path.remove, self.dir)
module = __import__(self.modname)
self.addCleanup(sys.modules.pop, self.modname)
stream = StringIO()
self._run(stream, module.Test())
return stream.getvalue()
示例6: test_run_list
def test_run_list(self):
self.useFixture(SampleTestFixture())
out = StringIO()
try:
run.main(['prog', '-l', 'testtools.runexample.test_suite'], out)
except SystemExit:
exc_info = sys.exc_info()
raise AssertionError("-l tried to exit. %r" % exc_info[1])
self.assertEqual("""testtools.runexample.TestFoo.test_bar
testtools.runexample.TestFoo.test_quux
""", out.getvalue())
示例7: test_run_list_failed_import
def test_run_list_failed_import(self):
if not run.have_discover:
self.skipTest("Need discover")
broken = self.useFixture(SampleTestFixture(broken=True))
out = StringIO()
exc = self.assertRaises(
SystemExit,
run.main, ['prog', 'discover', '-l', broken.package.base, '*.py'], out)
self.assertEqual(2, exc.args[0])
self.assertEqual("""Failed to import
runexample
""", out.getvalue())
示例8: test_replace_and_restore_handlers
def test_replace_and_restore_handlers(self):
stream = StringIO()
logger = logging.getLogger()
logger.addHandler(logging.StreamHandler(stream))
logger.setLevel(logging.INFO)
logging.info("one")
fixture = FakeLogger()
with fixture:
logging.info("two")
logging.info("three")
self.assertEqual("two\n", fixture.output)
self.assertEqual("one\nthree\n", stream.getvalue())
示例9: test_issue_16662
def test_issue_16662(self):
# unittest's discover implementation didn't handle load_tests on
# packages. That is fixed pending commit, but we want to offer it
# to all testtools users regardless of Python version.
# See http://bugs.python.org/issue16662
pkg = self.useFixture(SampleLoadTestsPackage())
out = StringIO()
self.assertEqual(None, run.main(
['prog', 'discover', '-l', pkg.package.base], out))
self.assertEqual(dedent("""\
discoverexample.TestExample.test_foo
fred
"""), out.getvalue())
示例10: test_stdout_honoured
def test_stdout_honoured(self):
self.useFixture(SampleTestFixture())
tests = []
out = StringIO()
exc = self.assertRaises(SystemExit, run.main,
argv=['prog', 'testtools.runexample.test_suite'],
stdout=out)
self.assertEqual((0,), exc.args)
self.assertThat(
out.getvalue(),
MatchesRegex(_u("""Tests running...
Ran 2 tests in \\d.\\d\\d\\ds
OK
""")))
示例11: test_run_orders_tests
def test_run_orders_tests(self):
self.useFixture(SampleTestFixture())
out = StringIO()
# We load two tests - one that exists and one that doesn't, and we
# should get the one that exists and neither the one that doesn't nor
# the unmentioned one that does.
tempdir = self.useFixture(fixtures.TempDir())
tempname = tempdir.path + '/tests.list'
f = open(tempname, 'wb')
try:
f.write(_b("""
testtools.runexample.TestFoo.test_bar
testtools.runexample.missingtest
"""))
finally:
f.close()
run.main(['prog', '-l', '--load-list', tempname,
'testtools.runexample.test_suite'], out)
self.assertEqual("""testtools.runexample.TestFoo.test_bar
""", out.getvalue())
示例12: TestTestResultStats
class TestTestResultStats(unittest.TestCase):
"""Test for TestResultStats, a TestResult object that generates stats."""
def setUp(self):
self.output = StringIO()
self.result = subunit.TestResultStats(self.output)
self.input_stream = BytesIO()
self.test = subunit.ProtocolTestCase(self.input_stream)
def test_stats_empty(self):
self.test.run(self.result)
self.assertEqual(0, self.result.total_tests)
self.assertEqual(0, self.result.passed_tests)
self.assertEqual(0, self.result.failed_tests)
self.assertEqual(set(), self.result.seen_tags)
def setUpUsedStream(self):
self.input_stream.write(_b("""tags: global
test passed
success passed
test failed
tags: local
failure failed
test error
error error
test skipped
skip skipped
test todo
xfail todo
"""))
self.input_stream.seek(0)
self.test.run(self.result)
def test_stats_smoke_everything(self):
# Statistics are calculated usefully.
self.setUpUsedStream()
self.assertEqual(5, self.result.total_tests)
self.assertEqual(2, self.result.passed_tests)
self.assertEqual(2, self.result.failed_tests)
self.assertEqual(1, self.result.skipped_tests)
self.assertEqual(set(["global", "local"]), self.result.seen_tags)
def test_stat_formatting(self):
expected = ("""
Total tests: 5
Passed tests: 2
Failed tests: 2
Skipped tests: 1
Seen tags: global, local
""")[1:]
self.setUpUsedStream()
self.result.formatStats()
self.assertEqual(expected, self.output.getvalue())
示例13: test_run_list_failed_import
def test_run_list_failed_import(self):
broken = self.useFixture(SampleTestFixture(broken=True))
out = StringIO()
# XXX: http://bugs.python.org/issue22811
unittest2.defaultTestLoader._top_level_dir = None
exc = self.assertRaises(
SystemExit,
run.main, ['prog', 'discover', '-l', broken.package.base, '*.py'], out)
self.assertEqual(2, exc.args[0])
self.assertThat(out.getvalue(), DocTestMatches("""\
Failed to import test module: runexample
Traceback (most recent call last):
File ".../loader.py", line ..., in _find_test_path
package = self._get_module_from_name(name)
File ".../loader.py", line ..., in _get_module_from_name
__import__(name)
File ".../runexample/__init__.py", line 1
class not in
...^...
SyntaxError: invalid syntax
""", doctest.ELLIPSIS))
示例14: TestTAP2SubUnit
class TestTAP2SubUnit(unittest.TestCase):
"""Tests for TAP2SubUnit.
These tests test TAP string data in, and subunit string data out.
This is ok because the subunit protocol is intended to be stable,
but it might be easier/pithier to write tests against TAP string in,
parsed subunit objects out (by hooking the subunit stream to a subunit
protocol server.
"""
def setUp(self):
self.tap = StringIO()
self.subunit = StringIO()
def test_skip_entire_file(self):
# A file
# 1..- # Skipped: comment
# results in a single skipped test.
self.tap.write("1..0 # Skipped: entire file skipped\n")
self.tap.seek(0)
result = subunit.TAP2SubUnit(self.tap, self.subunit)
self.assertEqual(0, result)
self.assertEqual([
"test file skip",
"skip file skip [",
"Skipped: entire file skipped",
"]",
],
self.subunit.getvalue().splitlines())
def test_ok_test_pass(self):
# A file
# ok
# results in a passed test with name 'test 1' (a synthetic name as tap
# does not require named fixtures - it is the first test in the tap
# stream).
self.tap.write("ok\n")
self.tap.seek(0)
result = subunit.TAP2SubUnit(self.tap, self.subunit)
self.assertEqual(0, result)
self.assertEqual([
"test test 1",
"success test 1",
],
self.subunit.getvalue().splitlines())
def test_ok_test_number_pass(self):
# A file
# ok 1
# results in a passed test with name 'test 1'
self.tap.write("ok 1\n")
self.tap.seek(0)
result = subunit.TAP2SubUnit(self.tap, self.subunit)
self.assertEqual(0, result)
self.assertEqual([
"test test 1",
"success test 1",
],
self.subunit.getvalue().splitlines())
def test_ok_test_number_description_pass(self):
# A file
# ok 1 - There is a description
# results in a passed test with name 'test 1 - There is a description'
self.tap.write("ok 1 - There is a description\n")
self.tap.seek(0)
result = subunit.TAP2SubUnit(self.tap, self.subunit)
self.assertEqual(0, result)
self.assertEqual([
"test test 1 - There is a description",
"success test 1 - There is a description",
],
self.subunit.getvalue().splitlines())
def test_ok_test_description_pass(self):
# A file
# ok There is a description
# results in a passed test with name 'test 1 There is a description'
self.tap.write("ok There is a description\n")
self.tap.seek(0)
result = subunit.TAP2SubUnit(self.tap, self.subunit)
self.assertEqual(0, result)
self.assertEqual([
"test test 1 There is a description",
"success test 1 There is a description",
],
self.subunit.getvalue().splitlines())
def test_ok_SKIP_skip(self):
# A file
# ok # SKIP
# results in a skkip test with name 'test 1'
self.tap.write("ok # SKIP\n")
self.tap.seek(0)
result = subunit.TAP2SubUnit(self.tap, self.subunit)
self.assertEqual(0, result)
self.assertEqual([
"test test 1",
"skip test 1",
],
#.........这里部分代码省略.........
示例15: TestSubUnitTags
class TestSubUnitTags(unittest.TestCase):
def setUp(self):
self.original = StringIO()
self.filtered = StringIO()
def test_add_tag(self):
self.original.write("tags: foo\n")
self.original.write("test: test\n")
self.original.write("tags: bar -quux\n")
self.original.write("success: test\n")
self.original.seek(0)
result = subunit.tag_stream(self.original, self.filtered, ["quux"])
self.assertEqual(
["tags: quux", "tags: foo", "test: test", "tags: bar", "success: test"],
self.filtered.getvalue().splitlines(),
)
def test_remove_tag(self):
self.original.write("tags: foo\n")
self.original.write("test: test\n")
self.original.write("tags: bar -quux\n")
self.original.write("success: test\n")
self.original.seek(0)
result = subunit.tag_stream(self.original, self.filtered, ["-bar"])
self.assertEqual(
["tags: -bar", "tags: foo", "test: test", "tags: -quux", "success: test"],
self.filtered.getvalue().splitlines(),
)