def load_tests_from_classes(test_cases): suite = TestSuite() loader = TestLoader() for test_class in test_cases: tests = loader.loadTestsFromTestCase(test_class) suite.addTests(tests) return suite
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)
def test_package(*package_names): tests = [] test_loader = TestLoader() for module_name, module in sys.modules.items(): for package_name in package_names: if module_name.startswith('{}.'.format(package_name)): module_tests = test_loader.loadTestsFromModule(module) module_tests = [t for t in module_tests if is_test_suite_loaded(t)] tests.extend(module_tests) test_result = TextTestRunner(failfast=True, resultclass=TimedTextTestResult).run(TestSuite(tests)) if not test_result.wasSuccessful(): raise Exception('test failed')
def load_tests(loader: TestLoader, standard_tests: TestSuite, pattern: Optional[str]) -> TestSuite: ret = TestSuite((standard_tests, )) for cls in tests: suite = loader.loadTestsFromTestCase(cls) ret.addTests(suite) return ret
def loadTests(self): loader = TestLoader() discover = unittest.defaultTestLoader.discover( "./testCases", pattern='*.py') #RechargeCases WithdrawCases PasswdManageCase #discover=unittest.defaultTestLoader.discover("./123", pattern='*.py') suite = unittest.TestSuite() testlist = discover._tests testlist = list(testlist) testCasesDict = {} testClassDict = {} for test in testlist: for x in test: for y in x: yy = dir(y.__class__) tempList = [] for y1 in yy: if y1.startswith("test"): print y1, y.__class__ tempList.append(y1) else: continue testClassDict[str(y.__class__)] = y.__class__ testCasesDict[str(y.__class__)] = tempList break for k in sorted(testClassDict.iterkeys()): for testValue in testCasesDict[k]: print testClassDict[k], testValue suite.addTest(testClassDict[k](testValue)) return suite
def test_package(*package_names): tests = [] test_loader = TestLoader() for module_name, module in sys.modules.items(): for package_name in package_names: if module_name.startswith('{}.'.format(package_name)): module_tests = test_loader.loadTestsFromModule(module) module_tests = [ t for t in module_tests if is_test_suite_loaded(t) ] tests.extend(module_tests) break test_result = TextTestRunner(failfast=True, resultclass=TimedTextTestResult).run( TestSuite(tests)) if not test_result.wasSuccessful(): raise Exception('test failed')
def main(): with app.app_context(): if os.getenv('FLASK_ENV') not in ['testing']: raise Exception('TESTS IS ALLOWED TO RUN ONLY END TESTING MODE') db.create_all() suite = TestLoader().discover( 'tests', pattern='test_*.py', top_level_dir=os.environ['PYTHONPATH'].split(os.pathsep)[0] ) return TextTestRunner(verbosity=1).run(suite)
def load_tests(loader: TestLoader, tests: TestSuite, pattern: Optional[str]) -> TestSuite: from .test_equipment import TestEquipment from .test_equipment_type import TestEquipmentType from .test_link import TestLink from .test_location import TestLocation from .test_port_type import TestEquipmentPortType from .test_service import TestService from .test_service_type import TestServiceType from .test_user import TestUser from ..utils.grpc.rpc_pb2_grpc import TenantServiceStub TESTS = [ TestEquipment, TestEquipmentType, TestLink, TestLocation, TestEquipmentPortType, TestService, TestServiceType, TestUser, ] print("Waiting for symphony to be ready") wait_for_platform() print("Initializing client") client = init_client(TEST_USER_EMAIL, TEST_USER_EMAIL) print("Initializing cleaner") address = get_grpc_server_address() channel = insecure_channel(address) stub = TenantServiceStub(channel) print("Packing tests") test_suite = TestSuite() for test_class in TESTS: testCaseNames = loader.getTestCaseNames(test_class) for test_case_name in testCaseNames: test_suite.addTest(test_class(test_case_name, client, stub)) return test_suite
def load_tests(loader: TestLoader, tests: TestSuite, pattern: Optional[str]) -> TestSuite: from .test_site_survey import TestSiteSurvey from ..utils.grpc.rpc_pb2_grpc import TenantServiceStub TESTS = [TestSiteSurvey] print("Waiting for symphony to be ready") wait_for_platform() print("Initializing client") client = init_client(TEST_USER_EMAIL, TEST_USER_EMAIL) print("Initializing cleaner") address = get_grpc_server_address() channel = insecure_channel(address) stub = TenantServiceStub(channel) print("Packing tests") test_suite = TestSuite() for test_class in TESTS: testCaseNames = loader.getTestCaseNames(test_class) for test_case_name in testCaseNames: test_suite.addTest(test_class(test_case_name, client, stub)) return test_suite
def __init__(self): ''' Constructor ''' parser = ArgumentParser(epilog = 'ACTC Test Runner') parser.add_argument('-c', '--coverage', action = 'store_true', help = 'activate code coverage measurement') args = parser.parse_args() if (args.coverage): from coverage import coverage cov = coverage(include = 'src/*', omit = '*/test/*.py') # actc.cli cov.exclude('Exception') cov.exclude('parser.error') # actc.dodo cov.exclude('NotImplementedError') cov.start() # end if TextTestRunner(verbosity = 2).run(TestLoader().discover('src')) if (args.coverage): cov.stop() cov.html_report(directory = 'coverage', title = 'ACTC code coverage') print('See coverage/index.html report')
#!/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
inst = LucteriosInstance("inst_psql", self.path_dir) inst.delete() self.assertEqual([], self.luct_glo.listing()) def test_archive(self): self.assertEqual([], self.luct_glo.listing()) inst = LucteriosInstance("inst_h", self.path_dir) inst.add() inst.filename = join(self.path_dir, "inst_h.arc") self.assertEqual(True, inst.archive()) inst = LucteriosInstance("inst_psql", self.path_dir) inst.set_database( "postgresql:name=" + self.data['dbname'] + ",user=puser,password=123456,host=localhost") inst.add() inst.filename = join(self.path_dir, "inst_h.arc") self.assertEqual(True, inst.restore()) if __name__ == "__main__": suite = TestSuite() loader = TestLoader() suite.addTest(loader.loadTestsFromTestCase(TestAdminSQLite)) suite.addTest(loader.loadTestsFromTestCase(TestAdminMySQL)) suite.addTest(loader.loadTestsFromTestCase(TestAdminPostGreSQL)) suite.addTest(loader.loadTestsFromTestCase(TestGlobal)) JUXDTestRunner(verbosity=1).run(suite) else: setup_from_none()
def main(): suite = TestLoader().discover(".") unittest.TextTestRunner().run(suite)
from unittest_timing import TimingTestRunner from unittest.loader import TestLoader suite = TestLoader().discover('apps') runner = TimingTestRunner() runner.run(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.'
def suite(): suite = TestLoader().loadTestsFromNames( ['testbxilog', 'testparserconf', 'testremotehandler']) return suite
def load_tests(loader, tests, pattern): ''' Returns all of the testcases in this module as a testsuite ''' return TestLoader().loadTestsFromTestCase(TestUtils)
def suite(): suite = TestLoader().loadTestsFromNames( ['specific_argparse_poslessed', 'specific_posless']) return suite
from unittest import TextTestRunner from unittest.suite import TestSuite from unittest.loader import TestLoader from test_case_06 import TestCase06 if __name__ == "__main__": suite = TestSuite() loader = TestLoader() suite.addTests(loader.loadTestsFromTestCase(TestCase06)) # run the suite debug_enabled = False if debug_enabled: """ NOTE Using buffer=False and failfast=True together ensures that any exception occurring during test runs is printed to stderr immediately instead of being hold back until all test cases finished. However at least failfast has to be disabled if test cases contain tests that are expected to fail. """ failfast = True buffer = False else: failfast = False buffer = True runner = TextTestRunner(failfast=failfast, buffer=buffer, verbosity=2) runner.run(suite)
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)
from unittest import TextTestRunner from unittest.suite import TestSuite from unittest.loader import TestLoader from test_case_01 import TestCase01 from test_case_02 import TestCase02 from test_case_03 import TestCase03 from test_case_04 import TestCase04 from test_case_05 import TestCase05 from test_case_06 import TestCase06 from test_simulation import TestSimulation if __name__ == "__main__": suite = TestSuite() loader = TestLoader() suite.addTests(loader.loadTestsFromTestCase(TestCase01)) suite.addTests(loader.loadTestsFromTestCase(TestCase02)) suite.addTests(loader.loadTestsFromTestCase(TestCase03)) suite.addTests(loader.loadTestsFromTestCase(TestCase04)) suite.addTests(loader.loadTestsFromTestCase(TestCase05)) suite.addTests(loader.loadTestsFromTestCase(TestCase06)) # run the suite debug_enabled = False if debug_enabled: """ NOTE Using buffer=False and failfast=True together ensures that any exception occurring during test runs is printed to stderr immediately instead of being hold back until all test cases finished. However at least failfast has to be disabled if test cases contain tests that are expected to fail. """ failfast = True buffer = False
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): self.loader = TestLoader()
def load_tests(loader, tests, pattern): #pylint: disable=W0613 ''' Returns all of the testcases in this module as a testsuite ''' return TestLoader().loadTestsFromTestCase(TestBookData)
inst = LucteriosInstance("inst_psql", self.path_dir) inst.set_database( "postgresql:name=" + self.data['dbname'] + ",user=puser,password=123456,host=localhost") inst.add() inst.filename = join(self.path_dir, "inst_h.arc") self.assertEqual(True, inst.restore()) def test_migration(self): self.assertEqual([], self.luct_glo.listing()) inst = LucteriosInstance("inst_psql", self.path_dir) inst.set_database( "postgresql:name=" + self.data['dbname'] + ",user=puser,password=123456,host=localhost") inst.add() self.assertEqual(["inst_psql"], self.luct_glo.listing()) mirg = MigrateFromV1("inst_psql", self.path_dir, "") mirg.filename = join( dirname(self.path_dir), 'data', 'archive_demo.bkf') mirg.restore() if __name__ == "__main__": suite = TestSuite() loader = TestLoader() # suite.addTest(loader.loadTestsFromTestCase(TestAdminSQLite)) # suite.addTest(loader.loadTestsFromTestCase(TestAdminMySQL)) # suite.addTest(loader.loadTestsFromTestCase(TestAdminPostGreSQL)) suite.addTest(loader.loadTestsFromTestCase(TestGlobal)) JUXDTestRunner(verbosity=1).run(suite) else: setup_from_none()
''' 方式一:通过TestSuite类 ''' # 实例化一个TestSuite对象 # suite = TestSuite() # 通过addTest(test)方法,test参数格式是:测试用例类名('用例方法名') # suite.addTest(TestRegister('test_01')) # suite.addTest(TestFriendlyLink('test_01')) # 通过addTests(tests)方法,tests代表的是含有单元测试脚本的可迭代对象 # suite.addTests([TestRegister('test_01'), TestFriendlyLink('test_01'), # TestFriendlyLink('test_02')]) ''' 方式二:通过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") # 第二部分:执行脚本 '''
import os import sys import argparse from unittest.loader import TestLoader from unittest.runner import TextTestRunner from pmworker import setup_logging 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 + "*"
''' 方式一:通过TestSuite类 ''' # 实例化一个TestSuite对象 # suite = TestSuite() # 通过addTest(test)方法,test参数格式是:测试用例类名('用例方法名') # suite.addTest(TestRegister('test_01')) # suite.addTest(TestFriendlyLink('test_01')) # 通过addTests(tests)方法,tests代表的是含有单元测试脚本的可迭代对象 # suite.addTests([TestRegister('test_01'), TestFriendlyLink('test_01'), # TestFriendlyLink('test_02')]) ''' 方式二:通过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类
import sys import unittest import cv2 import numpy as np import threading from PIL import ImageGrab from functools import wraps from time import sleep, time from appium.webdriver.common.mobileby import MobileBy as By from selenium.webdriver.support import expected_conditions as ec from selenium.webdriver.support.ui import WebDriverWait from unittest.loader import TestLoader from HtmlTestRunner.result import _HtmlTestResult as htmlResult from globalvar import dependency, ui, info, desireCap from appium import webdriver getTestCase = TestLoader().getTestCaseNames class fetchyaml(object): def locate_method(self, method): if method == 'ID': return By.ID elif method == 'XPATH': return By.XPATH elif method == 'CLASSNAME': return By.CLASS_NAME elif method == 'ANDROID_UI': return By.ANDROID_UIAUTOMATOR elif method == 'IOS_PREDICATE': return By.IOS_PREDICATE elif method == 'ACCESS_ID':