def test(tests_path=None): loader = TestLoader() if tests_path: try: tests = loader.loadTestsFromName(tests_path) if not tests._tests: tests = loader.discover(tests_path, top_level_dir=".") except ModuleNotFoundError: tests = loader.discover(".") else: tests = loader.discover(".") test_runner = TextTestRunner(verbosity=2) settings.SENTRY_URL = None settings.BOT_TOKEN = None settings.DEVELOPER_BOT_TOKEN = None settings.DEVELOPER_USER_ID = None db_url, db_name = settings.DATABASE["url"].rsplit("/", 1) settings.DATABASE["url"] = f"{db_url}/test_{db_name}" db_engine = create_engine(settings.DATABASE["url"]) init_sqlalchemy(db_engine) alembic_cfg.set_main_option("sqlalchemy.url", settings.DATABASE["url"]) click.echo("Creating DB...") if database_exists(db_engine.url): drop_database(db_engine.url) create_database(db_engine.url) try: click.echo("Migrating DB...") command_migrate("head") click.echo("Running tests...") result = test_runner.run(tests) except Exception: result = None finally: click.echo("Deleting DB...") drop_database(db_engine.url) if not result or result.failures or result.errors: exit(-1)
def run(self, ): loader = TestLoader() tests = loader.discover('.', 'test_*.py') t = XMLTestRunner(verbosity=1, output=self.TEST_RESULTS) res = t.run(tests) if not res.wasSuccessful(): raise FailTestException()
def main(self): loader = TestLoader() suite = unittest.TestSuite() print(loader.loadTestsFromModule(test_calculator)) print(loader.loadTestsFromModule(test_primenumbers)) print(loader.loadTestsFromTestCase(Test_Calculator)) print(loader.loadTestsFromTestCase(Test_PrimeNumbers)) suite.addTests(loader.loadTestsFromModule(test_primenumbers)) loader.discover("Test_Package_One", "test*.py") suite.addTests(loader.discover("Test_Package_One")) runner = unittest.TextTestRunner() runner.run(suite)
def run(self): # Do not include current directory, validate using installed pythran current_dir = _exclude_current_dir_from_import() os.chdir("pythran/tests") where = os.path.join(current_dir, 'pythran') from pythran import test_compile test_compile() try: import py import xdist args = ["-n", str(self.num_threads), where, '--pep8'] if self.failfast: args.insert(0, '-x') if self.cov: try: import pytest_cov args = ["--cov-report", "html", "--cov-report", "annotate", "--cov", "pythran"] + args except ImportError: print ("W: Skipping coverage analysis, pytest_cov" "not found") if py.test.cmdline.main(args) == 0: print "\\_o<" except ImportError: print ("W: Using only one thread, " "try to install pytest-xdist package") loader = TestLoader() t = TextTestRunner(failfast=self.failfast) t.run(loader.discover(where)) if t.wasSuccessful(): print "\\_o<"
def find_testcases(**kwargs): # Use the TestLoder to load all test cases defined within tests/vmtests/ # and figure out what distros and releases they are testing. Any tests # which are disabled will be excluded. loader = TestLoader() # dir with the vmtest modules (i.e. tests/vmtests/) tests_dir = os.path.dirname(__file__) # The root_dir for the curtin branch. (i.e. curtin/) root_dir = os.path.split(os.path.split(tests_dir)[0])[0] # Find all test modules defined in curtin/tests/vmtests/ module_test_suites = loader.discover(tests_dir, top_level_dir=root_dir) filter_attrs = [attr for attr, value in kwargs.items() if value] for mts in module_test_suites: for class_test_suite in mts: for test_case in class_test_suite: # skip disabled tests if not getattr(test_case, '__test__', False): continue # compare each filter attr with the specified value tcmatch = [ not _attr_match(kwargs[attr], getattr(test_case, attr, False)) for attr in filter_attrs ] if any(tcmatch): continue yield test_case
def run(self, ): loader = TestLoader() tests = loader.discover('.', 'test_*.py') t = TextTestRunner(verbosity=1) res = t.run(tests) if not res.wasSuccessful(): raise FailTestException()
def main(pattern='test*.py', config={}, argv=None, start_directory='.', config_file=None, config_args=None, config_json=None, test_runner=TextTestRunner()): """ Arguments in main should map to the cli arguments in __main__.py, so that kryptonic suites can run via cli or python. :param pattern: files to match when discovering unit tests. :param config: Dict of config options :param argv: :param start_directory: the start directory to search in, default '.' :param config_file: json file to load config options from """ if config is None: config = {} # _CALLEE__FILE__ = inspect.getmodule(inspect.stack()[1][0]).__file__ # https://stackoverflow.com/a/13699329 config_options = Config() config_options.__init__(**config) update_config_from_environment_variables(config_options) update_config_form_json(config_options, config_json) update_config_from_args(config_options, config_args) resolve_config_arguments(config_options) test_loader = TestLoader() tests = test_loader.discover(f'{getcwd()}/{start_directory}', pattern=pattern) print() print('⚗️ Pytonium Test config:\n') print(json.dumps(config_options.options, indent=2)) test_runner.run(tests)
def discover(directory): directory = os.path.expanduser( directory) # The tilde does not work with os.chdir os.chdir(directory) # Discovering tests using unittest framework loader = TestLoader() tests = loader.discover(directory, top_level_dir=directory) result = EmacsTestResult() # Create a buffer (if it not exists) and put the formatted results # inside it let = Let() lisp.get_buffer_create("unittest") let.push_excursion() lisp.set_buffer("unittest") lisp.erase_buffer() tests.run(result) lisp.insert("\n") lisp.insert("Errors:\n") for test, traceback in result.errors: lisp.insert(str(test)) lisp.insert(traceback) let.pop_excursion() lisp.pop_to_buffer("unittest") lisp.compilation_mode() lisp.beginning_of_buffer()
def discover(root_dir): if not os.path.exists(root_dir): return [] loader = TestLoader() prev_dir = os.curdir os.chdir(root_dir) tests = loader.discover(root_dir, top_level_dir=root_dir) os.chdir(prev_dir) ret = [] for suite in tests: for suite2 in suite: if suite2.__class__.__name__ == 'ModuleImportFailure': continue for test in suite2: name = ".".join( (test.__class__.__name__, test._testMethodName)) module = test.__module__ ret.append([ symbol(":name"), name, symbol(":module"), module, symbol(":root"), root_dir ]) modkey = lambda x: x[3] ret.sort(key=modkey) return [[k, list(g)] for k, g in groupby(ret, key=modkey) ] # Converting to a list of lists
def run(self): where = os.path.join('pythran', 'tests') try: import py import xdist import multiprocessing cpu_count = multiprocessing.cpu_count() args = ["-n", str(cpu_count), where] if self.failfast: args.insert(0, '-x') if self.cov: try: import pytest_cov args = ["--cov-report", "html", "--cov-report", "annotate", "--cov", "pythran"] + args except ImportError: print ("W: Skipping coverage analysis, pytest_cov" "not found") py.test.cmdline.main(args) except ImportError: print ("W: Using only one thread, " "try to install pytest-xdist package") loader = TestLoader() t = TextTestRunner(failfast=self.failfast) t.run(loader.discover(where))
def load_tests(): test_suite = TestSuite() this_dir = os.path.dirname(__file__) loader = TestLoader() package_tests = loader.discover(start_dir=this_dir) test_suite.addTests(package_tests) return test_suite
def load_tests(loader: unittest.TestLoader, standard_tests, pattern): if not ImportCore().HasClangSupport(): return unittest.TestSuite() this_dir = os.path.dirname(__file__) package_tests = loader.discover(this_dir, pattern) standard_tests.addTests(package_tests) return standard_tests
def discover(directory): directory = os.path.expanduser(directory) # The tilde does not work with os.chdir os.chdir(directory) # Discovering tests using unittest framework loader = TestLoader() tests = loader.discover(directory, top_level_dir=directory) result = EmacsTestResult() # Create a buffer (if it not exists) and put the formatted results # inside it let = Let() lisp.get_buffer_create("unittest") let.push_excursion() lisp.set_buffer("unittest") lisp.erase_buffer() tests.run(result) lisp.insert("\n") lisp.insert("Errors:\n") for test, traceback in result.errors: lisp.insert(str(test)) lisp.insert(traceback) let.pop_excursion() lisp.pop_to_buffer("unittest") lisp.compilation_mode() lisp.beginning_of_buffer()
def discover(root_dir): if not os.path.exists(root_dir): return [] loader = TestLoader() prev_dir = os.curdir os.chdir(root_dir) tests = loader.discover(root_dir, top_level_dir=root_dir) os.chdir(prev_dir) ret = [] for suite in tests: for suite2 in suite: if suite2.__class__.__name__ == 'ModuleImportFailure': continue for test in suite2: name = ".".join((test.__class__.__name__, test._testMethodName)) module = test.__module__ ret.append([symbol(":name"), name, symbol(":module"), module, symbol(":root"), root_dir]) modkey = lambda x: x[3] ret.sort(key=modkey) return [[k, list(g)] for k,g in groupby(ret, key=modkey)] # Converting to a list of lists
def test_all(dir=''): loader = TestLoader() suite = TestSuite() for all_test_suite in loader.discover(start_dir=os.path.join(path, 'tests', dir), pattern='test*.py'): for test_case in all_test_suite: suite.addTest(test_case) TextTestRunner().run(test=suite)
def _test_suite(): """ This method will discover and run all the test """ test_loader = TestLoader() test_suite = test_loader.discover("tests", pattern="test_*.py") return test_suite
def run(self): import os from unittest import TestLoader, TextTestRunner cur_dir = os.path.dirname(os.path.abspath(__file__)) loader = TestLoader() test_suite = loader.discover(cur_dir) runner = TextTestRunner(verbosity=2) runner.run(test_suite)
def test_suite(): """ Discover the tests. """ test_loader = TestLoader() discovered_tests = test_loader.discover("tests", pattern="test_*.py") return discovered_tests
def unittest(): """ Runs all unit tests using test discovery. """ loader = TestLoader() suite = loader.discover(join(getcwd(), "tests"), pattern="*.py") runner = TextTestRunner(verbosity=2) runner.run(suite)
def main(): """ Tests runner """ path_setup() sys.path.insert(1, os.getcwd()) import tester_coverage verbose = 1 suite = None loader = TestLoader() buf = True log_level = logging.NOTSET if len(sys.argv) > 1: arg1 = sys.argv[1] if arg1 == 'verbose': verbose = 2 suite = loader.discover('tests') log_level = logging.CRITICAL elif arg1 == 'combine': return tester_coverage.combine(dest_dir=".", data_dir="tests") elif arg1 == 'clean': return tester_coverage.clean("tests") elif arg1 == 'increment': tester_coverage.is_increment = True suite = loader.discover('tests') else: lst = arg1.split('.') tester_coverage.clean_coverage_data(os.path.join(*lst[:-1]), ".coverage.{}".format(lst[-1])) suite = loader.loadTestsFromNames([sys.argv[1]]) buf = False tester_coverage.is_increment = True else: tester_coverage.clean('tests') suite = loader.discover('tests') log_level = logging.CRITICAL logging.disable(log_level) sys.exit(0 if TextTestRunner(verbosity=verbose, buffer=buf).run(suite). wasSuccessful() else 1)
def allTests(): """Retrieve a test suite containing all tests.""" # Explicitly load all tests by name and not using a single discovery # to be able to easily deselect parts. tests = ["testInvocationLogger.py"] loader = TestLoader() directory = dirname(__file__) suites = [loader.discover(directory, pattern=test) for test in tests] return TestSuite(suites)
def allTests(): """Retrieve a test suite containing all tests.""" tests = [ "testGitHookCopyright.py", ] loader = TestLoader() directory = dirname(__file__) suites = [loader.discover(directory, pattern=test) for test in tests] return TestSuite(suites)
def run(): # switch test config environ['APP_TYPE'] = 'test' config = get_config() paths = (config.TEST_ROOT_DIR, ) loader = TestLoader() for p in paths: tests = loader.discover(p) runner = TextTestRunner() runner.run(tests)
def available_points(self): testLoader = TestLoader() tests = testLoader.discover('.', 'test*.py', None) tests = list(chain(*chain(*tests._tests))) points = map(_parse_points, tests) names = map(_name_test, tests) result = dict(zip(names, points)) with open('.available_points.json', 'w') as f: json.dump(result, f, ensure_ascii=False)
def test(args): from unittest import TestLoader, TextTestRunner loader = TestLoader() if args.module: suite = loader.loadTestsFromName(args.module) else: suite = loader.discover(TESTS_DIR) runner = TextTestRunner(verbosity=2) runner.run(suite)
def unit_test(args): from unittest import TestLoader, TextTestRunner loader = TestLoader() if args.module: suite = loader.loadTestsFromName(args.module) else: suite = loader.discover('code/tests') runner = TextTestRunner() runner.run(suite)
class TestSuiteDesigner(object): def __init__(self, agility): self._agility = agility self._testloader = TestLoader() def discover(self, startpath='', pattern='test*.py', rootpath=None): startpath = startpath or os.path.join(agility.cfg.path.pluginsdir, 'fieldtests', 'testcases') startpath = os.path.realpath(os.path.abspath(startpath)) if rootpath: pythonpath.addPath(rootpath) logger.info('Discovering test cases in path [%s], root path [%s]', startpath, rootpath or '') suite = self._testloader.discover(startpath, pattern=pattern, top_level_dir=rootpath) return suite
def allTests(): """Retrieve a test suite containing all tests.""" # Explicitly load all tests by name and not using a single discovery # to be able to easily deselect parts. tests = [ "testFixStrings.py", ] loader = TestLoader() directory = dirname(__file__) suites = [loader.discover(directory, pattern=test) for test in tests] return TestSuite(suites)
def allTests(): """Retrieve a test suite containing all tests.""" tests = [ "testNormalize.py", "testRange.py", "testRanges.py", "testUtil.py", ] loader = TestLoader() directory = dirname(__file__) suites = [loader.discover(directory, pattern=test) for test in tests] return TestSuite(suites)
def run_unittests(do_coverage=True): loader = TestLoader() if do_coverage: cov = coverage.coverage(source=["coinpy"], branch=True) cov.start() suite = loader.discover("unit", pattern='test_*.py') runner = unittest.TextTestRunner() runner.run(suite) if do_coverage: cov.stop() cov.save() cov.html_report(directory="coverage_html")
def run_test(self): suit = TestSuite() load = TestLoader() # suit.addTest(load.loadTestsFromModule(test_4_invest)) suit.addTest(load.discover(PATH.case_path)) self.filename = self.filename + '_' + str(datetime.datetime.now().strftime('%Y%m%d%H%M%S')) + '.html' create_user.Three_user().del_reports() with open(os.path.join(PATH.reports_path, self.filename), 'wb')as f: runs = HTMLTestRunner(stream=f, verbosity=2, title='测试报告', description='内容', tester='virgil') runs.run(suit)
def functionTest(name, testplan: dict): if not isinstance(testplan, dict): logger.debug('测试计划配置错误,测试异常终止,请检查conig文件!') myprint('测试计划配置错误,测试异常终止,请检查conig文件!') return reports_dir = path + 'reports/' test_plan_comment = testplan['comment'] jobs = eval(testplan['jobs']) loader = TestLoader() cases = [] for job_name, job_conf in jobs.items(): # 遍历测试计划下面得所有测试任务 with open('config/job_config.json', 'w', encoding='utf8') as f: # 写临时的job_conf文件, tmp = {} tmp['case_timeout'] = testplan['case_timeout'] tmp['filter_count'] = testplan['filter_count'] tmp['unfilter_count'] = testplan['unfilter_count'] tmp['case_path'] = job_conf['case_path'] tmp['case'] = job_conf['case'] with open('config/environments.json') as envs: envs = json.load(envs) env = envs[job_conf['env']] tmp = dict(tmp, **env) f.write(str(tmp).replace('\'', '\"')) if job_conf['case']: # add test cases in test job. if job_conf['case_path']: # 如果不指定case路径,默认添加所有case执行 case_path = path + 'test_case/' + job_conf['case_path'] else: case_path = path + 'test_case/' for case in job_conf['case']: # 搜索指定目录下的所有符合匹配规则的case myprint(case_path, case) cases.append(loader.discover(case_path, pattern=case)) else: pass # 将所有测试case全部加载到suite suite = TestSuite(cases) # 执行测试计划 now = time.strftime("%Y-%m-%d_%H-%M-%S") filename = reports_dir + 'report_' + now + '.html' with open(filename, 'wb') as f: html_test_runner = tools.HTMLTestRunner.HTMLTestRunner( stream=f, verbosity=2, title=name, description=test_plan_comment) html_test_runner.run(suite)
def preload(fill_cache: bool): """ Pre-loads any data so the user experience is better, i.e. there is less delay during. :param fill_cache: if true, will run all parsing tests to fill the cache for the semantic distance function. """ # Preload the WordNet dictionary. print('Loading WordNet...') wn.ensure_loaded() if fill_cache: print('Filling Cache (Running Tests)...') loader = TestLoader() suite = loader.discover(start_dir='tests/parsing') TextTestRunner(verbosity=1).run(suite)
def available_points(self): testLoader = TestLoader() tests = testLoader.discover('.', 'test*.py', None) try: tests = list(chain(*chain(*tests._tests))) except Exception as error: print("Received following Exception:", error) tests.debug() points = map(_parse_points, tests) names = map(_name_test, tests) result = dict(zip(names, points)) with open('.available_points.json', 'w') as f: json.dump(result, f, ensure_ascii=False)
def run(): init_config(env='test') # テスト用データベースの削除 drop_database() loader = TestLoader() base_dir = os.path.dirname(__file__) package = loader.discover(base_dir) runner = TextTestRunner(verbosity=2) result = runner.run(package) if len(result.errors) > 0 or len(result.failures) > 0: sys.exit(3)
def run(self): where = os.path.join('pythran', 'tests') try: import py import xdist import multiprocessing cpu_count = multiprocessing.cpu_count() args = ["-n", str(cpu_count), where] if self.failfast: args.insert(0, '-x') py.test.cmdline.main(args) except ImportError: print ("W: Using only one thread, " "try to install pytest-xdist package") loader = TestLoader() t = TextTestRunner() t.run(loader.discover(where))
def run(self, ): # Perform imports in run to avoid test dependencies in setup from xmlrunner import XMLTestRunner import coverage from unittest import TestLoader loader = TestLoader() tests = loader.discover('.', 'test_*.py') t = XMLTestRunner(verbosity=1, output=self.TEST_RESULTS) cov = coverage.Coverage( omit=['*/tests/', 'test_*.py', ], source=self.MODULE_NAMES, ) cov.start() t.run(tests) cov.stop() cov.save() cov.xml_report(outfile=self.COVERAGE_RESULTS)
def allTests(): """Retrieve a test suite containing all tests.""" from os.path import ( dirname, ) from unittest import ( TestLoader, TestSuite, ) # Explicitly load all tests by name and not using a single discovery # to be able to easily deselect parts. tests = [ "testDefer.py", ] loader = TestLoader() directory = dirname(__file__) suites = [loader.discover(directory, pattern=test) for test in tests] return TestSuite(suites)
# Ideally this would be in a common helper library shared between the tests def terminate_server_process(process): if os.name == "nt": process.kill() else: os.killpg(os.getpgid(process.pid), signal.SIGTERM) # Send the signal to all the process groups if __name__ == "__main__": cwd = dirname(realpath(__file__)) print("Current directory is: " + cwd) server = start_server_process() try: runner = TextTestRunner(verbosity=2) test_loader = TestLoader() test_loader.sortTestMethodsUsing = sort_test suite = test_loader.discover(cwd, pattern="*_tests.py") result = runner.run(suite) if not result.wasSuccessful(): sys.exit(1) finally: print("Killing server") terminate_server_process(server) print("Done killing server")
def iterate_tests(test_suite_or_case): """Iterate through all of the test cases in 'test_suite_or_case'.""" try: suite = iter(test_suite_or_case) except TypeError: yield test_suite_or_case else: for test in suite: for subtest in iterate_tests(test): yield subtest loader = TestLoader() tests = TestSuite([loader.discover(os.path.join(this_dir, d), top_level_dir=this_dir) for d in dirs]) test_runner = runner.TextTestRunner() def run_light(): lighttests = [] for test in iterate_tests(tests): if hasattr(test, "is_heavy") and test.is_heavy: pass else: lighttests.append(test) lighttests = TestSuite(lighttests) test_runner.run(lighttests) def run_heavy():
#!/usr/bin/env python import unittest from unittest import TestLoader, TextTestRunner import sys TEST_PATH = "." loader = TestLoader() runner = TextTestRunner() runner.run(loader.discover(TEST_PATH))
sys.path[0] = testdir else: sys.path.insert(0, testdir) from support import TestCase, MemoryTest, PerformanceTest suite = TestSuite() for name in args.suite: TestCase.setup_loader() if name == 'unit': pattern = 'test_*.py' elif name == 'performance': pattern = 'perf_*.py' PerformanceTest.setup_loader() PerformanceTest.start_new_results() elif name == 'memory': pattern = 'mem_*.py' MemoryTest.setup_loader() MemoryTest.start_new_results() elif name == 'documentation': pattern = 'documentation.py' loader = TestLoader() tests = loader.discover('.', pattern) suite.addTest(tests) runner = TextTestRunner(verbosity=args.verbose, buffer=args.buffer, failfast=args.failfast) result = runner.run(suite) if result.errors or result.failures: sys.exit(1)
def main(): loader = TestLoader() tests = loader.discover('tests') runner = TextTestRunner() runner.run(tests)
def run(self): loader = TestLoader() suite = loader.discover('pynes/tests', pattern='*_test.py') TextTestRunner(verbosity=4).run(suite)
__author__ = 'mdavid' import os import sys from unittest import TestLoader, TextTestRunner if __name__ == '__main__': tl = TestLoader() master_test_suite = tl.discover( start_dir=os.getcwd(), pattern='test_*.py', top_level_dir=os.path.join(os.getcwd(), '..') ) result = TextTestRunner(verbosity=2).run(master_test_suite) if result.errors or result.failures: sys.exit(-1) sys.exit(0)
def run(self): loader = TestLoader() t = TextTestRunner() # Run all test*py files in libtim subdirectory t.run(loader.discover('libtim'))
__author__ = "mdavid" import os import sys from unittest import TestLoader, TextTestRunner if __name__ == "__main__": tl = TestLoader() master_test_suite = tl.discover( start_dir=os.getcwd(), pattern="functest_*.py", top_level_dir=os.path.join(os.getcwd(), "..") ) result = TextTestRunner(verbosity=2).run(master_test_suite) if result.errors or result.failures: sys.exit(-1) sys.exit(0)
def path(self, appendPath): return pjoin(self.root_path, appendPath) def contents(self, appendPath): filename = self.path(appendPath) with open(filename, 'r') as fp: return fp.read() def fixturesLoader(path): p = Fixtures(pjoin(THIS_DIR, 'fixtures', path)) return p if __name__ == "__main__": import coverage from unittest import TestLoader, TestSuite, TextTestRunner cov = coverage.coverage(config_file=pjoin(THIS_DIR, '.coveragerc')) cov.start() loader = TestLoader() tests = loader.discover(THIS_DIR) suite = TestSuite(tests) runner = TextTestRunner() runner.run(suite) cov.stop() cov.save() cov.html_report()
# Unit test driver. import os import sys if sys.version_info[:2] >= (2,7): from unittest import TestLoader, TextTestRunner, TestSuite else: from unittest2 import TestLoader, TextTestRunner, TestSuite topdir = os.path.split(os.path.abspath(__file__))[0] os.chdir(topdir) loader = TestLoader() if sys.version_info[:2] < (3, 0): tests = loader.discover('.', 'test_*.py') elif sys.version_info[:2] > (3, 2): tests = TestSuite() tests.addTests(loader.discover('.', 'test_marshal.py')) tests.addTests(loader.discover('.', 'test_message.py')) else: tests = TestSuite() runner = TextTestRunner(verbosity=1, buffer=True) runner.run(tests)
def cmd_test(argv): loop = asyncio.get_event_loop() if argv: parser = argparse.ArgumentParser( prog="aio test", description='run aio tests') parser.add_argument( "modules", nargs="*", default=None, choices=[m.__name__ for m in aio.app.modules], help="module to test") try: parsed = parser.parse_args(argv) except (SystemExit, IndexError): loop.stop() modules = [] for module in parsed.modules: log.debug("Importing: %s" % module) modules.append(resolve(module)) else: if aio.app.config.get("aio/testing", "modules"): modules = [ resolve(module.strip()) for module in aio.app.config["aio/testing"]["modules"].split("\n") if module.strip()] else: modules = aio.app.modules aio.app.clear() errors = 0 def setUp(module, self): aio.app.clear() def tearDown(module, self): aio.app.clear() for attr in dir(module): if attr.startswith('_example_'): delattr(module, attr) for module in modules: try: test_module = resolve("%s.tests" % module.__name__) suite = TestSuite() loader = TestLoader() this_dir = "%s/tests" % module.__path__[0] readme = "%s/README.rst" % module.__path__[0] if os.path.exists(readme): suite.addTest(doctest.DocFileSuite( readme, module_relative=False, setUp=functools.partial(setUp, test_module), tearDown=functools.partial(tearDown, test_module), optionflags=doctest.ELLIPSIS)) package_tests = loader.discover(start_dir=this_dir) suite.addTests(package_tests) print('Running tests for %s...' % module.__name__) print("------------------------------------------" + "----------------------------") result = TextTestRunner(verbosity=2).run(suite) aio.app.clear() print("") if result.failures or result.errors: errors += 1 except ImportError: print('No tests for %s' % module.__name__) except: import traceback traceback.print_exc() errors += 1 if errors: loop.stop() sys.exit(1) loop.stop()
import os import sys from unittest import TestLoader, TestSuite import xmlrunner """ NOTE: "If a test package name (directory with __init__.py) matches the pattern then the package will be checked for a load_tests function. If this exists then it will be called with loader, tests, pattern." """ """ Load all tests in the current directory and run them """ if __name__ == "__main__": # must set the path for the imported tests sys.path.insert(0, os.path.abspath('../..')) loader = TestLoader() suite = TestSuite(loader.discover(start_dir='.', pattern='*_test.py', top_level_dir=".")) result = xmlrunner.XMLTestRunner( verbosity=2, output='test-reports').run(suite) if result.wasSuccessful(): sys.exit(0) sys.exit(1)
from unittest import TestLoader, TextTestRunner, main, TestSuite import sys if __name__ == '__main__': if sys.argv[1:]: patterns = sys.argv[1:] else: patterns = ['test*.py', 'ft_*.py', 'it_*.py', 'rt_*.py', 'qa_*.py'] start_dir_tests = './tests' loader = TestLoader() suite = TestSuite([loader.discover(start_dir_tests, pattern) for pattern in patterns]) TextTestRunner(verbosity=1).run(suite)
#!/usr/bin/env python from unittest import TestLoader, TextTestRunner loader = TestLoader() testRunner = TextTestRunner() modelsTestSuite = loader.discover('.', pattern='test_models.py') APITestSuite = loader.discover('.', pattern='test_api_server.py') print('\n\tRUNNING MODEL TEST CASES\n') testRunner.run(modelsTestSuite) print('\n\tRUNNING API TEST CASES\n') testRunner.run(APITestSuite)
import unittest from unittest import TestLoader, TextTestRunner, TestSuite if __name__ == "__main__": loader = TestLoader() suite = TestSuite(( loader.discover(".", pattern="*.py") )) runner = TextTestRunner(verbosity=2) runner.run(suite) unittest.main()