def test_label_single_transaction(self): test_file = os.path.join(RESOURCES_DIR, "test_single_transaction.py") self.assertTrue(os.path.exists(test_file)) store.writer = CachingWriter() nose2.discover( argv=[__file__, "tests.resources.test_single_transaction", '-v'], module="None", exit=False, plugins=["tests.unit.test_samples"]) samples = store.writer.samples self.assertEqual(len(samples), 1) toplevel = samples[0] self.assertEqual(2, len(toplevel.subsamples)) first, second = toplevel.subsamples self.assertEqual(first.test_suite, "test_requests") self.assertEqual(first.test_case, "blazedemo 123") self.assertEqual(1, len(first.subsamples)) first_req = first.subsamples[0] self.assertEqual(first_req.test_suite, "blazedemo 123") self.assertEqual(first_req.test_case, 'https://api.demoblaze.com/entries') self.assertEqual(second.test_suite, "test_requests") self.assertEqual(second.test_case, "blazedemo 456") self.assertEqual(1, len(second.subsamples)) second_req = second.subsamples[0] self.assertEqual(second_req.test_suite, "blazedemo 456") self.assertEqual(second_req.test_case, 'https://api.demoblaze.com/entries')
def test_two_transactions(self): test_file = os.path.join(RESOURCES_DIR, "test_two_transactions.py") self.assertTrue(os.path.exists(test_file)) store.writer = CachingWriter() nose2.discover( argv=[__file__, "tests.resources.test_two_transactions", '-v'], module="None", exit=False, plugins=["tests.unit.test_samples"]) samples = store.writer.samples self.assertEqual(len(samples), 2) first, second = samples self.assertEqual(first.test_case, "test_simple") self.assertEqual(1, len(first.subsamples)) self.assertEqual(first.subsamples[0].test_case, "1st") self.assertEqual(first.subsamples[0].subsamples[0].test_case, 'https://blazedemo.com/') self.assertEqual(first.subsamples[0].subsamples[0].assertions[0].name, 'assert_ok') self.assertEqual(second.test_case, "test_simple") self.assertEqual(1, len(second.subsamples)) self.assertEqual(second.subsamples[0].test_case, "2nd") self.assertEqual(second.subsamples[0].subsamples[0].test_case, 'https://blazedemo.com/vacation.html')
def main(): address = os.getenv('TEST_HOST') user = os.getenv('TEST_USERNAME') password = os.getenv('TEST_PASSWORD') xml = os.getenv('TEST_XML') ctx = Context(address, user, password, xml.lower() == 'yes') nose2.discover(extraHooks=[('startTest', ContextInjector(ctx))])
def main(cli): """Use nose2 to run unittests """ try: import nose2 except ImportError: cli.log.error( 'Could not import nose2! Please install it with {fg_cyan}pip3 install nose2' ) return False nose2.discover()
def runTestsForEnv(env, args): nose_base_args = _getNoseCommandLineArgs(args) nose_args = list(nose_base_args) if args.tests: nose_args += args.tests else: nose_args += _getDefaultTestByEnv(env) if env in TEST_ENVS and not _ON_WINDOWS: test_env = TEST_ENVS[env] test_env.update( {'HDLCC_SERVER_LOG_LEVEL' : args.log_level}) patch = mock.patch.dict('os.environ', test_env) else: patch = mock.patch.dict( 'os.environ', {'HDLCC_SERVER_LOG_LEVEL' : args.log_level}) patch.start() tests = nose2.discover(exit=False, argv=nose_args) patch.stop() return tests.result.wasSuccessful()
def runTestsForEnv(args): nose_base_args = _getNoseCommandLineArgs(args) nose_args = list(nose_base_args) if args.tests: nose_args += args.tests test_env = os.environ.copy() test_env.update({"SERVER_LOG_LEVEL": args.log_level}) home = p.join(os.environ["TOX_ENV_DIR"], "tmp", "home") os.makedirs(home) if not _ON_WINDOWS: test_env.update({"HOME": home}) else: test_env.update({"LOCALAPPDATA": home}) _logger.info("nose2 args: %s", nose_args) with mock.patch.dict("os.environ", test_env): successful = nose2.discover(exit=False, argv=nose_args).result.wasSuccessful() return successful
def _run(self): argv = [''] argv += self.test_args.split() collector = Nose2ResultsCollector() with open(os.devnull, 'w') as devnull: with redirect_stdout(devnull): with redirect_stderr(devnull): nose2.discover(argv=argv, extraHooks=[('testOutcome', collector)], exit=False) failures = [x for x in collector.events if x.outcome != 'passed'] return (not failures, [(str(r.test), traceback.format_exception(*r.exc_info)) for r in failures])
def communicate(self): with self: try: self.result = discover( argv=('nose2',) + self.args, exit=False, **self.kwargs) except SystemExit as e: pass return self.stdout.getvalue(), self.stderr.getvalue()
def communicate(self): with self: try: self.result = discover(argv=('nose2', ) + self.args, exit=False, **self.kwargs) except SystemExit as e: self._exit_code = e.code return self.stdout.getvalue(), self.stderr.getvalue()
def communicate(self): with self: try: self.result = discover(argv=('nose2', ) + self.args, exit=False, **self.kwargs) except SystemExit as e: return "", "EXIT CODE %s" % str(e) return self.stdout.getvalue(), self.stderr.getvalue()
def iterAllTestPathsFromRootDir(startDirOrModuleName, topDir=None): argv = [ "nose2", "--plugin", "iutest.plugins.nose2plugins.testlister", "--list-tests", "--plugin", "nose2.plugins.loader.eggdiscovery", "--exclude-plugin", "nose2.plugins.result", ] extraHooks = duplicationremoval.TestsDuplicationRemovalHooks.getHooks() if pathutils.isPath(startDirOrModuleName): argv.extend(["-s", startDirOrModuleName, "-t", topDir]) else: argv.append(startDirOrModuleName) TestCollector.gotError = False nose2.discover(argv=argv, exit=False, extraHooks=extraHooks) for tid in TestCollector.iterTestIds(): yield tid
def main(test_names=None): import pkgutil if not test_names: test_names = [] #for name in ['test_new']: # test_names.append(name) for _, name, _ in pkgutil.iter_modules([os.path.dirname(__file__)]): test_names.append(name) suite = unittest.TestSuite() for name in test_names: str2 = re.search('^(test_[a-z_]+)', name) if str2: try: suite.addTest(unittest.TestLoader().loadTestsFromName(name)) except unittest.SkipTest as exc: print('###{0}###: {1}'.format(__name__, repr(exc))) #unittest.TextTestRunner(verbosity = 2).run(suite) nose2.discover(argv=sys.argv[:1] + test_names) return 0
def _noseRunner(args): "Runs nose2 with coverage" _logger.info("nose2 args: %s", repr(args)) cov = coverage.Coverage(config_file='.coveragerc') cov.start() try: result = nose2.discover(exit=False, argv=args) finally: cov.stop() cov.save() return result
def test(coverage=False): """Run unit tests.""" import nose2 script_path = os.path.realpath(__file__) server_path = os.path.dirname(script_path) #+ '/tests' # Remember that the first argument is always current file arguments = [script_path, '-s', server_path] plugins = ['nose2.plugins.layers'] if coverage: arguments.append('--with-coverage') return nose2.discover(argv=arguments, plugins=plugins)
def run_tests(python3=False, plugins=None): """Discover unittests and run them using nose2""" hook_args(sys.argv) # plugins if plugins is None: plugins = [] if python3: plugins.append('py3filter') # fix_encoding sys.path.insert(0, CLIENT_THIRD_PARTY_DIR) from depot_tools import fix_encoding fix_encoding.fix_encoding() # add nose2 plugin dir to path sys.path.insert(0, PLUGINS_DIR) result = discover(plugins=plugins, exit=False).result if not result.wasSuccessful(): return 1 return 0
"""Main entry point""" import sys if sys.argv[0].endswith("__main__.py"): sys.argv[0] = "nose2" __unittest = True if __name__ == '__main__': from nose2 import discover discover()
npts=10, radians=True) # Check they are equal for index, dpoint in enumerate(points_d): self.assertAlmostEqual(dpoint[0], math.degrees(points_r[index][0])) self.assertAlmostEqual(dpoint[1], math.degrees(points_r[index][1])) class UnicodeTest(unittest.TestCase): def setUp(self): self.datadir_save = pyproj.datadir.pyproj_datadir def tearDown(self): # restore the original datapath, othwise this could cause other # tests to have errors pyproj.set_datapath(self.datadir_save) def test_utf8_set_datapath(self): # Issue #83 reported that Unicode characters in the installation # path this would cause a UnicodeEncodeError # the path is fictious and not meant to be a real path pyproj.set_datapath(u'göteborg') if __name__ == '__main__': if HAS_NOSE2 is True: nose2.discover() else: unittest.main()
import nose2 import sys from yoga.yoga import test_env_setup from yoga.args import yoga_nose_argparser, nose_args if __name__ == '__main__': args = test_env_setup(yoga_nose_argparser) res = nose2.discover(argv=nose_args(args)).runTests() sys.exit(res)
import nose2 nose2.discover()
def test_transactions(self): test_file = os.path.join(RESOURCES_DIR, "test_transactions.py") self.assertTrue(os.path.exists(test_file)) store.writer = CachingWriter() nose2.discover( argv=[__file__, "tests.resources.test_transactions", '-v'], module="None", exit=False, plugins=["tests.unit.test_samples"]) samples = store.writer.samples self.assertEqual(len(samples), 8) single = samples[0] self.assertEqual(single.test_suite, 'TestTransactions') self.assertEqual(single.test_case, 'test_1_single_transaction') tran = single.subsamples[0] self.assertEqual('test_1_single_transaction', tran.test_suite) self.assertEqual('single-transaction', tran.test_case) self.assertEqual(tran.status, "PASSED") two_trans = samples[1] self.assertEqual(two_trans.test_case, 'test_2_two_transactions') self.assertEqual(len(two_trans.subsamples), 2) first, second = two_trans.subsamples self.assertEqual(first.status, "PASSED") self.assertEqual(first.test_suite, 'test_2_two_transactions') self.assertEqual(first.test_case, 'transaction-1') self.assertEqual(second.status, "PASSED") self.assertEqual(second.test_suite, 'test_2_two_transactions') self.assertEqual(second.test_case, 'transaction-2') nested = samples[2] middle = nested.subsamples[0] self.assertEqual('test_3_nested_transactions.outer', middle.test_suite + '.' + middle.test_case) self.assertEqual(middle.status, "PASSED") inner = middle.subsamples[0] self.assertEqual('outer.inner', inner.test_suite + '.' + inner.test_case) self.assertEqual(inner.status, "PASSED") no_tran = samples[3] self.assertEqual(no_tran.status, "PASSED") self.assertEqual(no_tran.test_suite, "TestTransactions") self.assertEqual(no_tran.test_case, "test_4_no_transactions") with_assert = samples[4] self.assertEqual(with_assert.status, "PASSED") self.assertEqual(len(with_assert.subsamples), 1) request = with_assert.subsamples[0] self.assertEqual(request.test_suite, "test_5_apiritif_assertions") self.assertEqual(request.test_case, "http://blazedemo.com/") self.assertEqual(len(request.assertions), 1) assertion = request.assertions[0] self.assertEqual(assertion.name, "assert_ok") self.assertEqual(assertion.failed, False) assert_failed = samples[5] self.assertEqual(assert_failed.status, "FAILED") request = assert_failed.subsamples[0] self.assertEqual(request.test_suite, "test_6_apiritif_assertions_failed") self.assertEqual(request.test_case, "http://blazedemo.com/") self.assertEqual(len(request.assertions), 1) assertion = request.assertions[0] self.assertEqual(assertion.name, "assert_failed") self.assertEqual(assertion.failed, True) self.assertEqual( assertion.error_message, "Request to https://blazedemo.com/ didn't fail (200)") assert_failed_req = samples[6] self.assertEqual(assert_failed_req.status, "FAILED") request = assert_failed_req.subsamples[0] self.assertEqual(request.test_suite, "test_7_failed_request") self.assertEqual(request.test_case, "http://notexists") self.assertEqual(len(request.assertions), 0) # checks if series of assertions is recorded into trace correctly assert_seq_problem = samples[7] self.assertEqual(assert_seq_problem.status, "FAILED") request = assert_seq_problem.subsamples[0] self.assertEqual(request.test_suite, "test_8_assertion_trace_problem") self.assertEqual(len(request.assertions), 3) self.assertFalse(request.assertions[0].failed) self.assertFalse(request.assertions[1].failed) self.assertTrue(request.assertions[2].failed)
def runNose2(): import nose2 nose2.discover(exit=False)
#!/usr/bin/env python """ HACK to support the Django + nose without django-nose. Built based on documentation from: * https://docs.djangoproject.com/en/1.8/topics/testing/advanced/#using-the-django-test-runner-to-test-reusable-applications * http://nose.readthedocs.org/en/latest/usage.html#basic-usage """ import os import sys import nose2 import django from django.conf import settings if __name__ == '__main__': settings.configure() django.setup() settings.BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) settings.DJANGO_LIVESYNC = {'PORT': 9001, 'HOST': '127.0.0.1'} result = nose2.discover() if not result: sys.exit(1)
# import unittest # from selenium import webdriver # # class AweberTest(unittest.TestCase): # # #@classmethod # def setUpClass(cls): # cls.driver = webdriver.Firefox() # # def test_title(self): # self.driver.get('https://www.aweber.com') # self.assertEqual( # self.driver.title, # 'AWeber Email Marketing Services & Software Solutions for Small Business') # # # @classmethod # def tearDownClass(cls): #============================================================================== #cls.driver.quit() if __name__ == '__main__': import nose2 class Hello(object): def startTestRun(self,event): print('hello!') nose2.discover(extraHooks=[('startTestRun', Hello())])
def run_all(): import nose2 nose2.discover(module='pygraphml')
#!/usr/bin/env python # -*- coding: utf-8 -*- try: import nose2 except ImportError: message = """nose2 package not installed, install test requirements with: pip install -r requirements-test.txt """ raise ImportError(message) if __name__ == "__main__": result = nose2.discover() if result is False: import sys sys.exit(1)
import nose2 from nose2.tools import params from game import Frame, Game class FrameTests(unittest.TestCase): def setUp(self): # We probably need a frame object every time self.frame = Frame() class GameTests(unittest.TestCase): def setUp(self): # We probably need a game object every time self.game = Game() if __name__ == '__main__': # Construct command line CURRENT_DIRECTORY = os.path.dirname(os.path.abspath(__file__)) PARENT_DIRECTORY = os.path.split(CURRENT_DIRECTORY)[0] argv = [ sys.argv[0], '-s', PARENT_DIRECTORY ] # Run the tests with exit=False so we can print coverage after nose2.discover(argv=argv)