我们从Python开源项目中,提取了以下32个代码示例,用于说明如何使用unittest2.TextTestRunner()。
def _run_suite(suite): """Run tests from a unittest.TestSuite-derived class.""" if verbose: runner = unittest.TextTestRunner(sys.stdout, verbosity=2, failfast=failfast) else: runner = BasicTestRunner() result = runner.run(suite) if not result.wasSuccessful(): if len(result.errors) == 1 and not result.failures: err = result.errors[0][1] elif len(result.failures) == 1 and not result.errors: err = result.failures[0][1] else: err = "multiple errors occurred" if not verbose: err += "; run in verbose mode for details" raise TestFailed(err)
def test_startTestRun_stopTestRun_called(self): class LoggingTextResult(LoggingResult): separator2 = '' def printErrors(self): pass class LoggingRunner(unittest2.TextTestRunner): def __init__(self, events): super(LoggingRunner, self).__init__(StringIO()) self._events = events def _makeResult(self): return LoggingTextResult(self._events) events = [] runner = LoggingRunner(events) runner.run(unittest2.TestSuite()) expected = ['startTestRun', 'stopTestRun'] self.assertEqual(events, expected)
def test(coverage=False): import unittest2 import os import coverage as _coverage cov = None if coverage: cov = _coverage.coverage(branch=True, include='./*') cov.start() tests = unittest2.TestLoader().discover('tests') unittest2.TextTestRunner(verbosity=2).run(tests) if cov: cov.stop() cov.save() print('Coverage Summary:') cov.report() basedir = os.path.abspath(os.path.dirname(__file__)) covdir = os.path.join(basedir, 'tmp/coverage') cov.html_report(directory=covdir) print('HTML version: file://%s/index.html' % covdir) cov.erase() # TODO: Implement options
def main(): """ Run all of the tests when run as a module with -m. """ runner = unittest.TextTestRunner() runner.run(get_suite())
def testInheritance(self): self.assertIsSubclass(unittest2.TestCase, unittest.TestCase) self.assertIsSubclass(unittest2.TestResult, unittest.TestResult) self.assertIsSubclass(unittest2.TestSuite, unittest.TestSuite) self.assertIsSubclass(unittest2.TextTestRunner, unittest.TextTestRunner) self.assertIsSubclass(unittest2.TestLoader, unittest.TestLoader) self.assertIsSubclass(unittest2.TextTestResult, unittest.TestResult)
def test_new_runner_old_case(self): runner = unittest2.TextTestRunner(resultclass=resultFactory, stream=StringIO()) class Test(unittest.TestCase): def testOne(self): pass suite = unittest2.TestSuite((Test('testOne'),)) result = runner.run(suite) self.assertEqual(result.testsRun, 1) self.assertEqual(len(result.errors), 0)
def test_old_runner_new_case(self): runner = unittest.TextTestRunner(stream=StringIO()) class Test(unittest2.TestCase): def testOne(self): self.assertDictEqual({}, {}) suite = unittest.TestSuite((Test('testOne'),)) result = runner.run(suite) self.assertEqual(result.testsRun, 1) self.assertEqual(len(result.errors), 0)
def testFailFastSetByRunner(self): runner = unittest2.TextTestRunner(stream=StringIO(), failfast=True) self.testRan = False def test(result): self.testRan = True self.assertTrue(result.failfast) runner.run(test) self.assertTrue(self.testRan)
def test_NonExit(self): program = unittest2.main(exit=False, argv=["foobar"], testRunner=unittest2.TextTestRunner(stream=StringIO()), testLoader=self.FooBarLoader()) self.assertTrue(hasattr(program, 'result'))
def test_ExitAsDefault(self): self.assertRaises( SystemExit, unittest2.main, argv=["foobar"], testRunner=unittest2.TextTestRunner(stream=StringIO()), testLoader=self.FooBarLoader())
def testRunner(self): # Creating a TextTestRunner with the appropriate argument should # register the TextTestResult it creates runner = unittest2.TextTestRunner(stream=StringIO()) result = runner.run(unittest2.TestSuite()) self.assertIn(result, unittest2.signals._results)
def test_init(self): runner = unittest2.TextTestRunner() self.assertFalse(runner.failfast) self.assertFalse(runner.buffer) self.assertEqual(runner.verbosity, 1) self.assertTrue(runner.descriptions) self.assertEqual(runner.resultclass, unittest2.TextTestResult) self.assertFalse(runner.tb_locals)
def testBufferAndFailfast(self): class Test(unittest2.TestCase): def testFoo(self): pass result = unittest2.TestResult() runner = unittest2.TextTestRunner(stream=StringIO(), failfast=True, buffer=True) # Use our result object runner._makeResult = lambda: result runner.run(Test('testFoo')) self.assertTrue(result.failfast) self.assertTrue(result.buffer)
def test_locals(self): runner = unittest.TextTestRunner(stream=io.StringIO(), tb_locals=True) result = runner.run(unittest.TestSuite()) self.assertEqual(True, result.tb_locals)
def test_works_with_result_without_startTestRun_stopTestRun(self): class OldTextResult(OldTestResult): def __init__(self, *_): super(OldTextResult, self).__init__() separator2 = '' def printErrors(self): pass runner = unittest2.TextTestRunner(stream=StringIO(), resultclass=OldTextResult) runner.run(unittest2.TestSuite())
def test_pickle_unpickle(self): # Issue #7197: a TextTestRunner should be (un)pickleable. This is # required by test_multiprocessing under Windows (in verbose mode). stream = StringIO(u("foo")) runner = unittest2.TextTestRunner(stream) for protocol in range(2, pickle.HIGHEST_PROTOCOL + 1): s = pickle.dumps(runner, protocol=protocol) obj = pickle.loads(s) # StringIO objects never compare equal, a cheap test instead. self.assertEqual(obj.stream.getvalue(), stream.getvalue())
def test_resultclass(self): def MockResultClass(*args): return args STREAM = object() DESCRIPTIONS = object() VERBOSITY = object() runner = unittest2.TextTestRunner(STREAM, DESCRIPTIONS, VERBOSITY, resultclass=MockResultClass) self.assertEqual(runner.resultclass, MockResultClass) expectedresult = (runner.stream, DESCRIPTIONS, VERBOSITY) self.assertEqual(runner._makeResult(), expectedresult)
def test_oldresult(self): class Test(unittest2.TestCase): def testFoo(self): pass runner = unittest2.TextTestRunner(resultclass=OldTestResult, stream=StringIO()) # This will raise an exception if TextTestRunner can't handle old # test result objects runner.run(Test('testFoo'))
def execute(cls): """ Run this test case. """ suite = unittest.TestLoader().loadTestsFromTestCase(cls) runner = unittest.TextTestRunner() return runner.run(suite)
def run(self): Config.setDefaultGeneratedDataRoot(self.generated_data) if self.update: Config().updateDataFiles() else: Config().ensureDataConsistency() builder = self.builder() suite = builder.loadMultipleTests(self.namespace) runner = unittest.TextTestRunner(verbosity=self.verbosity) runner.run(suite)
def parseArguments(self, argv): parser = argparse.ArgumentParser(prog=self.program, description="CSB Test Runner Console.") parser.add_argument("-t", "--type", type=str, default="any", choices=list(Console.BUILDERS), help="Type of tests to load from each namespace (default=any)") parser.add_argument("-v", "--verbosity", type=int, default=1, help="Verbosity level passed to unittest.TextTestRunner (default=1).") parser.add_argument("-u", "--update-files", default=False, action="store_true", help="Force update of the test pickles in " + Config.GENERATED_DATA) parser.add_argument("-g", "--generated-resources", type=str, default=Config.GENERATED_DATA, help="Generate, store and load additional test resources in this directory" " (default=" + Config.GENERATED_DATA + ")") parser.add_argument("namespaces", nargs='*', help="""An optional list of CSB test dotted namespaces, from which to load tests. '__main__' and '.' are interpreted as the current module. If a namespace ends with an asterisk '.*', all sub-packages will be scanned as well. Examples: "csb.test.cases.bio.*" "csb.test.cases.bio.io" "csb.test.cases.bio.utils" ".")""") args = parser.parse_args(argv) self.builder = Console.BUILDERS[args.type] self.verbosity = args.verbosity self.update = args.update_files self.generated_data = args.generated_resources if args.namespaces: self.namespace = args.namespaces
def run(self): suite = unittest.TestLoader().loadTestsFromNames( ['tests.__main__.suite'] ) unittest.TextTestRunner(verbosity=2).run(suite)