我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用unittest.TextTestRunner()。
def runTests(self): # Setup some globals to pass to the TestCase global SOFT_PKG global IMPL_ID SOFT_PKG = self.spd_file spd = SPDParser.parse(self.spd_file) if self.testRunner is None: try: import xmlrunner self.testRunner = xmlrunner.XMLTestRunner(verbosity=self.verbosity) except ImportError: self.testRunner = unittest.TextTestRunner(verbosity=self.verbosity) for implementation in spd.get_implementation(): IMPL_ID = implementation.get_id() if IMPL_ID == self.impl or self.impl is None: result = self.testRunner.run(self.test) self.results.append(result) #sys.exit(not result.wasSuccessful())
def cov(): """Runs the unit tests with coverage.""" tests = unittest.TestLoader().discover('project/tests') result = unittest.TextTestRunner(verbosity=2).run(tests) if result.wasSuccessful(): 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() return 0 return 1
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 main(sdk_path, test_path, test_pattern): # If the SDK path points to a Google Cloud SDK installation # then we should alter it to point to the GAE platform location. if os.path.exists(os.path.join(sdk_path, 'platform/google_appengine')): sdk_path = os.path.join(sdk_path, 'platform/google_appengine') # Make sure google.appengine.* modules are importable. fixup_paths(sdk_path) # Make sure all bundled third-party packages are available. import dev_appserver dev_appserver.fix_sys_path() # Loading appengine_config from the current project ensures that any # changes to configuration there are available to all tests (e.g. # sys.path modifications, namespaces, etc.) try: import appengine_config (appengine_config) except ImportError: print('Note: unable to import appengine_config.') # Discover and run tests. suite = unittest.loader.TestLoader().discover(test_path, test_pattern) return unittest.TextTestRunner(verbosity=2).run(suite)
def testRunnerRegistersResult(self): class Test(unittest.TestCase): def testFoo(self): pass originalRegisterResult = unittest.runner.registerResult def cleanup(): unittest.runner.registerResult = originalRegisterResult self.addCleanup(cleanup) result = unittest.TestResult() runner = unittest.TextTestRunner(stream=StringIO()) # Use our result object runner._makeResult = lambda: result self.wasRegistered = 0 def fakeRegisterResult(thisResult): self.wasRegistered += 1 self.assertEqual(thisResult, result) unittest.runner.registerResult = fakeRegisterResult runner.run(unittest.TestSuite()) self.assertEqual(self.wasRegistered, 1)
def test_startTestRun_stopTestRun_called(self): class LoggingTextResult(LoggingResult): separator2 = '' def printErrors(self): pass class LoggingRunner(unittest.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(unittest.TestSuite()) expected = ['startTestRun', 'stopTestRun'] self.assertEqual(events, expected)
def _run_suite(suite): """Run tests from a unittest.TestSuite-derived class.""" if verbose: runner = unittest.TextTestRunner(sys.stdout, verbosity=2) 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 __init__(self, stream=sys.stderr, descriptions=True, verbosity=1, failfast=False, buffer=False, resultclass=None, tb_locals=False): """Construct a TextTestRunner. Subclasses should accept **kwargs to ensure compatibility as the interface changes. """ self.stream = _WritelnDecorator(stream) self.descriptions = descriptions self.verbosity = verbosity self.failfast = failfast self.buffer = buffer self.tb_locals = tb_locals if resultclass is not None: self.resultclass = resultclass
def handle(self, *args, **options): loader = unittest.TestLoader() tests = loader.discover( './acceptancetests/tests', pattern="acc_test_*.py" ) runner = unittest.TextTestRunner(verbosity=2) test_result = runner.run(tests) if test_result.wasSuccessful(): sys.exit() else: number_failed = len(test_result.failures) + len(test_result.errors) sys.exit(number_failed)
def run_tests(self, stream, test_suite): """Runs the given TestSuite. @param stream: A stream object with write functionality to capture the test output. @param test_suite: The TestSuite to run. """ runner = unittest.TextTestRunner(stream=stream, verbosity=2, resultclass=mayaunittest.TestResult) runner.failfast = False runner.buffer = mayaunittest.Settings.buffer_output result = runner.run(test_suite) self._set_test_result_data(result.failures, TestStatus.fail) self._set_test_result_data(result.errors, TestStatus.error) self._set_test_result_data(result.skipped, TestStatus.skipped) for test in result.successes: node = self.node_lookup[str(test)] index = self.get_index_of_node(node) self.setData(index, 'Test Passed', QtCore.Qt.ToolTipRole) self.setData(index, TestStatus.success, QtCore.Qt.DecorationRole)
def main(): """Runs the unit tests""" suite = unittest.TestSuite() suite.addTests(unittest.makeSuite(TestFunctions)) suite.addTests(unittest.makeSuite(TestPointCharge)) suite.addTests(unittest.makeSuite(TestLineCharge)) suite.addTests(unittest.makeSuite(TestElectricField)) suite.addTests(unittest.makeSuite(TestGaussianCircle)) result = unittest.TextTestRunner(verbosity=1).run(suite) n_errors = len(result.errors) n_failures = len(result.failures) if n_errors or n_failures: print('\n\nSummary: %d errors and %d failures reported\n'%\ (n_errors, n_failures)) print() sys.exit(n_errors+n_failures)
def test(): '''Run the face test suite.''' pv.disableCommercialUseWarnings() normalize_suite = unittest.TestLoader().loadTestsFromTestCase(_TestNormalize) surf_suite = unittest.TestLoader().loadTestsFromTestCase(_TestSURF) dist_suite = unittest.TestLoader().loadTestsFromTestCase(_TestDistance) test_suites = [ normalize_suite, surf_suite, dist_suite ] pyvision_suite = unittest.TestSuite(test_suites) unittest.TextTestRunner(verbosity=2).run(pyvision_suite)
def test(): import QuantLib print('testing QuantLib ' + QuantLib.__version__) suite = unittest.TestSuite() suite.addTest(DateTest()) suite.addTest(DayCountersTest()) suite.addTest(unittest.makeSuite(InstrumentTest,'test')) suite.addTest(unittest.makeSuite(MarketElementTest,'test')) suite.addTest(unittest.makeSuite(IntegralTest,'test')) suite.addTest(Solver1DTest()) suite.addTest(unittest.makeSuite(TermStructureTest,'test')) suite.addTest(unittest.makeSuite(FixedRateBondTest, 'test')) suite.addTest(unittest.makeSuite(FixedRateBondHelperTest, 'test')) suite.addTest(unittest.makeSuite(CmsTest, 'test')) suite.addTest(unittest.makeSuite(AssetSwapTest, 'test')) suite.addTest(unittest.makeSuite(CapFloorTest, 'test')) result = unittest.TextTestRunner(verbosity=2).run(suite) if not result.wasSuccessful: sys.exit(1)
def test(coverage=False): """Run the unit tests.""" if coverage and not os.environ.get('FLASK_COVERAGE'): import sys os.environ['FLASK_COVERAGE'] = '1' os.execvp(sys.executable, [sys.executable] + sys.argv) import unittest tests = unittest.TestLoader().discover('tests') unittest.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()
def run_transcript_tests(self, callargs): """Runs transcript tests for provided file(s). This is called when either -t is provided on the command line or the transcript_files argument is provided during construction of the cmd2.Cmd instance. :param callargs: List[str] - list of transcript test file names """ class TestMyAppCase(Cmd2TestCase): cmdapp = self self.__class__.testfiles = callargs sys.argv = [sys.argv[0]] # the --test argument upsets unittest.main() testcase = TestMyAppCase() runner = unittest.TextTestRunner() runner.run(testcase)
def test(coverage=False): """ ?? :param coverage ???????? :return: """ if coverage and not os.environ.get('PG_COVERAGE'): import sys os.environ['PG_COVERAGE'] = '1' os.execvp(sys.executable, [sys.executable] + sys.argv) import unittest tests = unittest.TestLoader().discover('tests') unittest.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, 'tests/coverage') COV.html_report(directory=covdir) print('HTML version: file://%s/index.html' % covdir) COV.erase()
def run_availability_tests(test_suite): __import__(test_suite) suite = unittest.TestLoader().loadTestsFromName(test_suite) runner = TextTestRunner(verbosity=4) result = runner.run(suite) return result
def unittest_main(*args, **kwargs): if 'testRunner' in kwargs and kwargs['testRunner'] is None: kwargs['testRunner'] = unittest.TextTestRunner return unittest.main(*args, **kwargs)
def run_tests(self): """ Loads the test suite and hook the callback for reporting progress. """ Controller.patch_keystore_path() test_suite = suite() self.stream_property = "" stream = StringIOCBWrite(callback_write=self.callback_write) verbosity = 2 unittest.TextTestRunner( stream=stream, verbosity=verbosity).run(test_suite)
def runTests(self): if self.testRunner is None: try: import xmlrunner self.testRunner = xmlrunner.XMLTestRunner(verbosity=self.verbosity) except ImportError: self.testRunner = unittest.TextTestRunner(verbosity=self.verbosity) unittest.TestProgram.runTests(self)
def test(): """Run the unit tests.""" import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests)
def runtests(debug=False): enableLogging(debug) test_suite = unittest.TestLoader().discover('tests/') result = unittest.TextTestRunner().run(test_suite) sys.exit(0 if result.wasSuccessful() else 1)
def test(): print("=" * len(__TITLE__)) print(__TITLE__) print("=" * len(__TITLE__)) suite = unittest.TestLoader().loadTestsFromTestCase(TestPJFEncoder) unittest.TextTestRunner(verbosity=2).run(suite)
def test(): print("=" * len(__TITLE__)) print(__TITLE__) print("=" * len(__TITLE__)) suite = unittest.TestLoader().loadTestsFromTestCase(TestPJFServer) unittest.TextTestRunner(verbosity=2).run(suite)
def test(): print("=" * len(__TITLE__)) print(__TITLE__) print("=" * len(__TITLE__)) suite = unittest.TestLoader().loadTestsFromTestCase(TestPJFMutation) unittest.TextTestRunner(verbosity=2).run(suite)
def test(): print("=" * len(__TITLE__)) print(__TITLE__) print("=" * len(__TITLE__)) suite = unittest.TestLoader().loadTestsFromTestCase(TestPJFFactory) unittest.TextTestRunner(verbosity=2).run(suite)
def test(): print("=" * len(__TITLE__)) print(__TITLE__) print("=" * len(__TITLE__)) suite = unittest.TestLoader().loadTestsFromTestCase(TestPJFConfiguration) unittest.TextTestRunner(verbosity=2).run(suite)
def test(): print("=" * len(__TITLE__)) print(__TITLE__) print("=" * len(__TITLE__)) suite = unittest.TestLoader().loadTestsFromTestCase(TestPJFExternalFuzzer) unittest.TextTestRunner(verbosity=2).run(suite)
def test(): print("=" * len(__TITLE__)) print(__TITLE__) print("=" * len(__TITLE__)) suite = unittest.TestLoader().loadTestsFromTestCase(TestEnvironment) unittest.TextTestRunner(verbosity=2).run(suite)
def test(): """Runs the unit tests without test coverage.""" tests = unittest.TestLoader().discover('project/tests', pattern='test*.py') result = unittest.TextTestRunner(verbosity=2).run(tests) if result.wasSuccessful(): return 0 return 1
def runTests(testCases=None, verbosity=1): """Run a series of tests.""" if testCases is None: testCases = _gatherTestCasesFromCallerByMagic() loader = unittest.TestLoader() suites = [] for testCase in testCases: suites.append(loader.loadTestsFromTestCase(testCase)) testRunner = unittest.TextTestRunner(verbosity=verbosity) testSuite = unittest.TestSuite(suites) testRunner.run(testSuite) # GLIF test tools
def main(): runner = unittest.TextTestRunner(verbosity=1 + sys.argv.count('-v')) suite = all_tests_suite() raise SystemExit(not runner.run(suite).wasSuccessful())
def run_test(module, incomplete=False, nosubprocess=False, randomize=False, exclude=('interactive',), buffer=True): """Run a unit test module """ suite = unittest.TestSuite() print ('loading %s' % module) loader = PygameTestLoader(randomize_tests=randomize, include_incomplete=incomplete, exclude=exclude) suite.addTest(loader.loadTestsFromName(module)) output = StringIO.StringIO() runner = unittest.TextTestRunner(stream=output, buffer=buffer) results = runner.run(suite) results = {module: { 'output': output.getvalue(), 'num_tests': results.testsRun, 'num_errors': len(results.errors), 'num_failures': len(results.failures), }} if not nosubprocess: print (TEST_RESULTS_START) print (pformat(results)) print (TEST_RESULTS_END) else: return results ################################################################################
def test(config, tests=(), fail_fast=False, with_coverage=True, with_lint=True): if tests: num_tests = len(tests) s = '' if num_tests == 1 else 's' printer.header('Running {num_tests} test{s}...'.format_map(locals())) else: coverage_message = ' with coverage' if with_coverage else '' printer.header('Running tests{coverage_message}...'.format_map(locals())) runner = unittest.TextTestRunner(failfast=fail_fast) loader = unittest.TestLoader() if with_coverage: from coverage import Coverage coverage = Coverage(source=['runcommands']) coverage.start() if tests: for name in tests: runner.run(loader.loadTestsFromName(name)) else: tests = loader.discover('.') result = runner.run(tests) if not result.errors: if with_coverage: coverage.stop() coverage.report() if with_lint: printer.header('Checking for lint...') lint(config)
def _test(): r = unittest.TextTestRunner() r.run(DocTestSuite())
def skip_other_tests(): """ Decorator which skips all tests except the one decorated with it. Based on original python-ideas proposal: http://mail.python.org/pipermail/python-ideas/2010-August/007992.html Working with Python from 2.5 to 3.3. Author: Giampaolo Rodola' <g.rodola [AT] gmail [DOT] com> License: MIT """ import unittest from unittest import TextTestRunner as _TextTestRunner class CustomTestRunner(_TextTestRunner): def run(self, test): if test._tests: for t1 in test._tests: for t2 in t1._tests: if t2._testMethodName == self._special_name: return _TextTestRunner.run(self, t2) raise RuntimeError("couldn't isolate test") def outer(fun, *args, **kwargs): # monkey patch unittest module unittest.TextTestRunner = CustomTestRunner if hasattr(unittest, 'runner'): # unittest2 unittest.runner.TextTestRunner = CustomTestRunner CustomTestRunner._special_name = fun.__name__ def inner(self): return fun(self, *args, **kwargs) return inner return outer # =================================================================== # --- test # ===================================================================
def run_unit_tests(): ''' Execute Unit Tests ''' tests = unittest.TestLoader().discover('tests/unit') result = unittest.TextTestRunner(verbosity=2).run(tests) return result.wasSuccessful()
def run_integration_tests(): ''' Execute Integration Tests ''' tests = unittest.TestLoader().discover('tests/integration') result = unittest.TextTestRunner(verbosity=2).run(tests) return result.wasSuccessful()
def run_functional_tests(): ''' Execute Functional Tests ''' tests = unittest.TestLoader().discover('tests/functional') result = unittest.TextTestRunner(verbosity=2).run(tests) return result.wasSuccessful()
def main(): results = unittest.TextTestRunner().run(buildTestSuite()) return results
def run_CRN_import_test(): suite = CRNImportTests.suite() unittest.TextTestRunner(verbosity=2).run(suite)
def run_tdm(): suite = TDMTests.suite() unittest.TextTestRunner(verbosity=2).run(suite)
def run_compilation(): suite = CompilationTests.suite() unittest.TextTestRunner(verbosity=2).run(suite)
def run_translation(): suite = DSDClassesTests.suite() unittest.TextTestRunner(verbosity=2).run(suite)
def run_nupack(): suite = TDM_NUPACK_tests.suite() unittest.TextTestRunner(verbosity=2).run(suite)
def run_all(): alltests = unittest.TestSuite( [ x.suite() for x in #[import_test, TDMTests, CompilationTests, RunDesignerTest, DSDClassesTests, TDM_NUPACK_tests, CommandlineTests] [CommandlineTests, CRNImportTests, TDMTests, CompilationTests, Srinivas2017Tests, TDM_NUPACK_tests] ]) unittest.TextTestRunner(verbosity=2).run(alltests)
def suite(): s = unittest.TestSuite() g = os.getcwd() + '/octagon/**.py' for path in glob.iglob(g): if os.path.basename(path) != "__init__.py": s.addTest(OctagonTestCase(path)) runner = unittest.TextTestRunner() runner.run(s)