class NoDjangoTestLoader(object): def __init__(self): self.loader = TestLoader() def discover(self, start_dir, pattern='test*.py', top_level_dir=None): suite = self.loader.discover(start_dir, pattern, top_level_dir) return self.suite_without_django(suite) def loadTestsFromNames(self, names, module=None): return self.suite_without_django( self.loader.loadTestsFromNames(names, module)) def suite_without_django(self, suite): tests = (t for t in self.iterate_over_suite(suite) if not self.is_django(t)) return unittest.suite.TestSuite(tests) def iterate_over_suite(self, suite): for test_like in suite: if not isinstance(test_like, unittest.suite.TestSuite): yield test_like else: for test in self.iterate_over_suite(test_like): yield test def is_django(self, test): return any('django' in c.__module__ for c in inspect.getmro(test.__class__))
def invoked(self, ns): # Use standard unittest runner, it has somewhat annoying way of # displaying test progress but is well-known and will do for now. runner = TextTestRunner(verbosity=ns.verbosity, failfast=ns.fail_fast) loader = TestLoader() # Discover all integration tests tests = loader.discover(get_plainbox_dir(), pattern="integration_*.py") result = runner.run(tests) # Forward the successfulness of the test suite as the exit code return 0 if result.wasSuccessful() else 1
def prepare_test_list(self): test_loader = TestLoader() try: if len(self.args) > 0: self.test_list = test_loader.loadTestsFromNames(self.args, None) else: self.test_list = test_loader.discover(".", "test*.py", None) except: print "Problem to import load the test(s)." print "If you are sure that the import is correct, check if source if don't have a wrong import declaration." print_exception() sys.exit(1)
''' 方式二:通过TestLoader类 ''' # 实例化一个TestLoader对象 loader = TestLoader() # 根据测试用例类名进行加载 # suite = loader.loadTestsFromTestCase(TestFriendlyLink) # 根据指明的模块名进行加载 # suite = loader.loadTestsFromModule(t02_friendly_link) # 通过discover方法:根据指定的工程目录下文件(模块)的命名规则来进行自动扫描加载测试用例,返回值为:TestSuite对象 # test*.py 指的是: # 1、先加载包的配置文件中已经声明的模块中符合规则的测试用例: # (第一必须继承TestCase类,第二必须有以test开头的方法)(如果没有符合规则的,会取得内容为空 的suite对象) # 2、再去扫描所有以test开头的模块,并加载用例(如果没有符合规则的,则不录入,就是不收集起来) project_path = os.path.dirname(os.getcwd()) suite = loader.discover(project_path, "test*.py") # 第二部分:执行脚本 ''' 方式一:通过TextTestRunner类 ''' # # 实例化一个TextTestRunner对象 # runner = TextTestRunner() # # 调用run方法执行测试集合 # runner.run(suite) ''' 方式二:通过HTMLTestRunner类 ''' # 定义报告文件的路径 report_path = project_path+"\\reports\\"+time.strftime("%Y%m%d%H%M%S")+".html" # strftime方法的参数格式有:
BASE_DIR = os.path.dirname(os.path.abspath(__file__)) test_loader = TestLoader() test_runner = TextTestRunner() os.environ['CELERY_CONFIG_MODULE'] = 'pmworker.config.test' setup_logging() parser = argparse.ArgumentParser() parser.add_argument('-p', '--pattern', default='test*py', help='Test files pattern.') args = parser.parse_args() if args.pattern.endswith('py'): discovery_pattern = args.pattern else: discovery_pattern = args.pattern + "*" tests = test_loader.discover(start_dir=BASE_DIR, pattern=discovery_pattern) result = test_runner.run(tests) if not result.wasSuccessful(): sys.exit(1)
import argparse import os import sys from unittest.loader import TestLoader from unittest.runner import TextTestRunner BASE_DIR = os.path.dirname(os.path.abspath(__file__)) test_loader = TestLoader() test_runner = TextTestRunner() parser = argparse.ArgumentParser() tests = test_loader.discover(start_dir=BASE_DIR, ) result = test_runner.run(tests) if not result.wasSuccessful(): sys.exit(1)
import unittest from unittest.loader import TestLoader import os from thinksns_test.demo.t01_register import TestRegister #第一种方式 suite = unittest.TestSuite() # 构建测试集 # suite.addTest(TestRegister('test_register_01')) # suite.addTests([TestRegister('test_register_01')])#以列表的方式 #第二种方式 loader = TestLoader() #根据类名进行加载 # suite = loader.loadTestsFromTestCase(TestFri) #根据模块(py文件)名进行加载 # suite = loader.loadTestsFromModule() #通过discover实现,注意,discover 首先回去读取__init__中符合规则的 project_path = os.path.dirname(os.getcwd()) suite = loader.discover(project_path, 'test*.py') if __name__ == "__main__": #第一种方式 # 运行测试集合 runner = unittest.TextTestRunner() runner.run(suite) #第二种方式 # HTML
#!/usr/bin/env python3 from unittest.loader import TestLoader from unittest.runner import TextTestRunner if __name__ == '__main__': loader = TestLoader() runner = TextTestRunner() suites = loader.discover("nrf5_cmake", "*.py", ".") runner.run(suites)
def load_tests(loader: TestLoader, standard_tests, pattern): # top level directory cached on loader instance this_dir = os.path.dirname(__file__) package_tests = loader.discover(start_dir=this_dir) standard_tests.addTests(package_tests) return standard_tests
方式二:通过TestLoader类 ''' # 实例化一个TestLoader对象 loader = TestLoader() # 根据测试用例类名进行加载 # suite = loader.loadTestsFromTestCase(TestFriendlyLink) # 根据指明的模块名进行加载 # suite = loader.loadTestsFromModule(t02_friendly_link) # 通过discover方法:根据指定的工程目录下文件(模块)的命名规则来进行自动扫描加载测试用例,返回值为:TestSuite对象 # test*.py 指的是: # 1、先加载包的配置文件中已经声明的模块中符合规则的测试用例: # (第一必须继承TestCase类,第二必须有以test开头的方法)(如果没有符合规则的,会取得内容为空 的suite对象) # 2、再去扫描所有以test开头的模块,并加载用例(如果没有符合规则的,则不录入,就是不收集起来) #注意,根据1条件查找执行后,依然会根据2条件再次查找执行符合条件的用例 project_path = os.path.dirname(os.getcwd()) suite = loader.discover(project_path, "specification*.py") # 第二部分:执行脚本 ''' 方式二:通过HTMLTestRunner类 ''' # 定义报告文件的路径 report_path = project_path + "\\reports\\" + time.strftime( "%Y%m%d%H%M%S") + ".html" # 打开报告文件(如果不存在会新建),得到文件对象 fp = open(report_path, "wb") # 实例化HTMLTestRunner类,得到执行器 runner = HTMLTestRunner(stream=fp, title="ecshop项目自动化测试报告",
class CustomSuite(unittest.TestSuite): def __init__(self, tests=()): stripped = [] for test in tests: if isinstance(test, CustomSuite): stripped.append(test) elif any(member[0].startswith('test_') for member in inspect.getmembers(test)): stripped.append(test) super(CustomSuite, self).__init__(tests=stripped) if __name__ == "__main__": # We have to regen the plugins cache to be able to install # alternative reactors. Regen utility should be run in a separate # interpreter because reactors cannot be installed twice or unloaded. subprocess.call(["python", "regen_plugins_cache.py"]) config = Options() config.parseOptions() config['tbformat'] = 'verbose' config['exitfirst'] = True _initialDebugSetup(config) trialRunner = _makeRunner(config) test_loader = TestLoader() test_loader.suiteClass = CustomSuite test_suite = test_loader.discover(abspath(join('.', 'ipv8', 'test')), top_level_dir=abspath('.')) test_result = trialRunner.run(test_suite)
def __init__(self, discovery_dir='.', discovery_pattern='test*.py', output_file='test_results.html', silent=False, verbosity=2): test_groups = {} loader = TestLoader() groups_data = {} summary_data = { 'discovery_dir' : discovery_dir, 'discovery_pattern' : discovery_pattern, 'num_groups' : 0, 'num_groups_fail' : 0, 'num_groups_pass' : 0, 'num_tests' : 0, 'num_tests_fail' : 0, 'num_tests_pass' : 0, 'num_tests_skip' : 0, 'raw_log' : '' } # Discovery tests from specified directory tests = loader.discover(discovery_dir, discovery_pattern) # Group tests by file for group in tests: group_name = None for suite in group: # Determine group name if hasattr(suite, '_testMethodName'): test_groups[suite._testMethodName] = group else: for test in suite: test_groups[inspect.getmodule(test).__name__] = group break # Run tests for each group for group_name, tests in test_groups.items(): raw_log = StringIO() runner = TextTestRunner(stream=TestRunner.StreamRouter(raw_log, silent), verbosity=verbosity) result = runner.run(tests) # Index errors by test class errors = {} for error in result.errors: errors['{0}.{1}'.format(error[0].__class__.__name__, error[0]._testMethodName)] = error[1] # Marshall/record data group_data = { 'tests' : [] } group_data['tests_errored'] = len(result.errors) group_data['tests_passed'] = result.testsRun - group_data['tests_errored'] group_data['tests_skipped'] = len(result.skipped) group_data['tests_run'] = result.testsRun summary_data['num_groups'] += 1 summary_data['num_tests'] += group_data['tests_run'] + group_data['tests_skipped'] summary_data['num_tests_fail'] += group_data['tests_errored'] summary_data['num_tests_pass'] += group_data['tests_passed'] summary_data['num_tests_skip'] += group_data['tests_skipped'] summary_data['raw_log'] += raw_log.getvalue() if group_data['tests_errored'] > 0: summary_data['num_groups_fail'] += 1 else: summary_data['num_groups_pass'] += 1 # Detailed test data for suite in tests: cls_name = suite.__class__.__name__ if cls_name == 'ModuleImportFailure' or cls_name == 'LoadTestsFailure': # Record loader failure group_data['tests'].append({ 'name' : suite._testMethodName, 'status' : 'fail', 'description' : errors['{0}.{1}'.format(suite.__class__.__name__, suite._testMethodName)] }) else: for t in suite: signature = '{0}.{1}'.format(t.__class__.__name__, t._testMethodName) test_data = {'name' : '{0}.{1}'.format(group_name, signature)} if signature in errors: test_data['status'] = 'fail' test_data['description'] = errors[signature] else: test_data['description'] = ''; test_data['status'] = 'pass' group_data['tests'].append(test_data) groups_data[group_name] = group_data # Write results if summary_data['num_tests'] > 0: results.PageBuilder(groups_data, summary_data).generate_html(output_file) print 'Results available at {0}'.format(os.path.realpath(output_file)) else: print 'No tests run; no results to publish.'