def main(): __DIR__ = os.path.dirname(os.path.abspath(__file__)) USE_XML_RUNNER = True # target: path to the directory used to store the generated XML files. # terminal_path: path to the file used to store the standard output of the # test execution. top_directory = os.path.join(__DIR__, 'test', 'my_package') target = os.path.join(gettempdir(), 'result') terminal_path = os.path.join(gettempdir(), 'terminal') print(f'XML files will be generated under the directory "{target}".') print(f'Path to the terminal file: "{terminal_path}".') with open(terminal_path, 'w') as terminal: test_suite: TestSuite = defaultTestLoader.discover( start_dir=f'{top_directory}', top_level_dir=__DIR__, pattern='*_test.py') print(f'Number of unit tests: {test_suite.countTestCases()}') if USE_XML_RUNNER: test_result = xmlrunner.XMLTestRunner( output=target, verbosity=0, stream=terminal).run(test_suite) else: result = TestResult() test_suite.run(result) test_case: TestCase message: str for test_case, message in result.failures: print(test_case.id() + ':') print('\n'.join([f'\t{m}' for m in message.split('\n')]))
def step_impl(context): """This will take a VERY long time unless you comment out some lines in the list of enabled_tests below """ appsuite_env = 'al_visitor_site' test_names = [ appsuite_env + '.tests.' + test for test in get_visitor_site_tests() ] tests = unittest.TestLoader().loadTestsFromNames(test_names) xmlrunner.XMLTestRunner(verbosity=2, output='reports').run(tests)
def testall(*args): """Big red button does all the things""" suiteconf = applications['appsuites'][args[0][0]] os.environ['BASE_URL'] = suiteconf['base_url'] print("Starting Python Flask Selenium Test Framework") print("Test environment: %s" % args[0][0]) print("Base URL: ", suiteconf['base_url']) tests = unittest.TestLoader().discover('%s/tests' % args[0][0]) xmlrunner.XMLTestRunner(verbosity=2, output='reports').run(tests)
def runtest(*args): import sys if len(args[0]): print("Starting Python Flask Selenium Test Framework") print("Visitor site: ", os.environ['VISITOR_SITE_URL']) print("Running test, %s" % args[0][0]) test_suite_name = args[0][0].replace('test_', '').replace('.py', '') tests = unittest.TestLoader().discover('tests', pattern='test_' + test_suite_name + '.py') xmlrunner.XMLTestRunner(verbosity=2, output='reports').run(tests) else: print("No test selected")
def main(): __DIR__ = os.path.dirname(os.path.abspath(__file__)) parser = argparse.ArgumentParser(description='Unit test runner') parser.add_argument('--verbose', dest='verbose', action='store_true', default=False, help=' '.join(['Verbosity mode'])) args = parser.parse_args() try: conf = Config(args.__getattribute__('verbose')) except Exception as e: print(f'ERROR: {e}') sys.exit(1) # target: path to the directory used to store the generated XML files. # terminal_path: path to the file used to store the standard output of the # test execution. top_directory = os.path.join(__DIR__, 'tests', 'unit', 'tests') target = os.path.join(__DIR__, 'tests', 'unit', 'result') terminal_path = os.path.join(gettempdir(), 'terminal') if conf.verbose: print(f'XML files will be generated under the directory "{target}".') print(f'Path to the terminal file: "{terminal_path}".') with open(terminal_path, 'w') as terminal: test_suite: TestSuite = defaultTestLoader.discover(start_dir=top_directory, top_level_dir=top_directory, pattern='*_test.py') if conf.verbose: print(f'Number of unit tests: {test_suite.countTestCases()}') result = xmlrunner.XMLTestRunner(output=target, verbosity=1, stream=terminal).run(test_suite) # failure: a test that failed. # error: a Python related error. if len(result.failures) > 0 or len(result.errors) > 0: if conf.verbose: print(f'FAILURE (see file "{terminal_path}")') sys.exit(1) else: if conf.verbose: print('SUCCESS') sys.exit(0)
def suites(*args): """Display list of test suites and run the selected suite""" suiteconf = applications['appsuites'][args[0][0]] os.environ['BASE_URL'] = suiteconf['base_url'] print("Starting Python Flask Selenium Test Framework") print("Test environment: %s" % args[0][0]) print("Base URL: ", suiteconf['base_url']) print("Choose a test suite to run below: \n") test_suite_list = [testname[5:(len(testname) - 3)] for testname in os.listdir(('%s/tests' % args[0][0]))\ if testname[:5] == 'test_'] count = 0 suite_menu = {} suite_test_menu = {} for test_suite in test_suite_list: count += 1 print("%s : %s" % (count, test_suite)) suite_menu[count] = test_suite selected_suite = int(input("Enter test suite (0 exits): ")) tests = unittest.TestLoader().discover( ('%s/tests' % args[0][0]), pattern='test_' + suite_menu[selected_suite] + '.py') count = 0 for group in tests: for suite in group: for test in suite: count += 1 print("%s : %s" % (count, str(test).replace('test_', ''))) suite_test_menu[count] = test selected_test = int( input("Enter test number to run (0 exits, %s to run ALL): " % str(count + 1))) if selected_test in suite_test_menu: xmlrunner.XMLTestRunner(verbosity=2, output='reports').run( suite_test_menu[int(selected_test)]) elif selected_test == count + 1: xmlrunner.XMLTestRunner(verbosity=2, output='reports').run(tests)
def run_tests(self): while len(self.queue) > 0: print("Taking from queue...") test_params = self.queue.pop() print(f"Importing {test_params[0]}") m = re.match(r'^(.+)(\.[^.]+)$', test_params[0]) module_object = importlib.import_module(m.group(2), m.group(1)) test_class = getattr(module_object, test_params[1]) loader = TestLoader() suite = TestSuite((loader.loadTestsFromTestCase(test_class))) print(f"Running {test_params[0]}.{test_params[1]}") runner = xmlrunner.XMLTestRunner(output="junit", verbosity=2) runner.run(suite)
def menu(*args): print("Starting Python Flask Selenium Test Framework") print("Visitor site: ", os.environ['VISITOR_SITE_URL']) print("Choose a test to run below: \n") tests = unittest.TestLoader().discover('tests') test_menu = {} count = 0 for group in tests: for suite in group: for test in suite: count += 1 print("%s : %s" % (count, str(test).replace('test_', ''))) test_menu[count] = test selected_test = int(input("Enter test number to run: ")) if selected_test in test_menu: xmlrunner.XMLTestRunner(verbosity=2, output='reports').run( test_menu[int(selected_test)])
def runtestsuite(*args): """runs a test suite - if file name is test_thisIsATest.py, use thisIsATest command syntax is: manage.py envname testname """ try: if len(args[0]) and len(args[0][1]): suiteconf = applications['appsuites'][args[0][0]] os.environ['BASE_URL'] = suiteconf['base_url'] print("Starting Python Flask Selenium Test Framework") print("Test environment: %s" % args[0][0]) print("Base URL: ", suiteconf['base_url']) print("Running test, %s" % args[0][1]) test_suite_name = args[0][1].replace('test_', '').replace('.py', '') tests = unittest.TestLoader().discover( ('%s/tests' % args[0][0]), pattern='test_' + test_suite_name + '.py') xmlrunner.XMLTestRunner(verbosity=2, output='reports').run(tests) except IndexError: print("Usage: manage.py runtestsuite <env_name> <test_class>") print("example: manage.py runtestsuite al_visitor_site AA404")
def menu(*args): """Shows menu consisting of all individual tests""" suiteconf = applications['appsuites'][args[0][0]] os.environ['BASE_URL'] = suiteconf['base_url'] print("Starting Python Flask Selenium Test Framework") print("Test environment: %s" % args[0][0]) print("Base URL: ", suiteconf['base_url']) print("Choose a test to run below: \n") tests = unittest.TestLoader().discover('%s/tests' % args[0][0]) test_menu = {} count = 0 for group in tests: for suite in group: for test in suite: count += 1 print("%s : %s" % (count, str(test).replace('test_', ''))) test_menu[count] = test selected_test = int(input("Enter test number to run (0 exits): ")) if selected_test in test_menu: xmlrunner.XMLTestRunner(verbosity=2, output='reports').run( test_menu[int(selected_test)])
def runtest(*args): """Runs a single test from a test file""" try: if len(args[0]) and len(args[0][1]): suiteconf = applications['appsuites'][args[0][0]] os.environ['BASE_URL'] = suiteconf['base_url'] print("Starting Python Flask Selenium Test Framework") print("Test environment: %s" % args[0][0]) print("Base URL: ", suiteconf['base_url']) suite = args[0][1] print("Running test, %s" % suite) tests = unittest.TestLoader().loadTestsFromName(args[0][0] + '.tests.' + args[0][1]) xmlrunner.XMLTestRunner(verbosity=2, output='reports').run(tests) except IndexError: print( "Usage: manage.py runtest <env_name> <test_file_basename>.<test_class>.<test_name>" ) print( "Example: manage.py runtest al_visitor_site test_AA404.AA404.test_aa404" )
def test_redirects(*args): print("Starting Python Flask Selenium Test Framework") print("Visitor site: ", os.environ['VISITOR_SITE_URL']) tests = unittest.TestLoader().discover('tests', pattern='test_Redirects.py') xmlrunner.XMLTestRunner(verbosity=2, output='reports').run(tests)
import unittest from xmlrunner import xmlrunner from ddtexample import testddt search_tests = unittest.TestLoader().loadTestsFromTestCase(testddt) test_suite = unittest.TestSuite([search_tests]) xmlrunner.XMLTestRunner(verbosity=2, output='test-reports').run(test_suite)
def test_CHmyQNAPcndePort_CHPublicNondePortSSLON_login(self): '''myQNAPcloud.cn -> Login PASS''' settings.login1(self, IP_or_Host="atext8082.myqnapcloud.cn", AC="admin", PWD="80682695") def test_CHmyQNAPcndePort_CHPublicNondePortSSLOFF_login(self): '''myQNAPcloud.cn -> Login PASS''' settings.login1(self, IP_or_Host="atext8082.myqnapcloud.cn", AC="admin", PWD="80682695") """ #@classmethod def tearDown(self): print("close") #self.driver.quit() if __name__ == '__main__': suite = unittest.TestSuite() #tests = ["test_minus1", "test_uu", "test_add", "test_mul", "test_minus"] for i in range(settings.loop_times): suite.addTests(unittest.makeSuite(Login)) # suite.addTests(unittest.TestLoader().loadTestsFromTestCase(yu)) #suite = unittest.TestSuite(map(yu, tests)) # suite.addTests(suite1) print(suite) xmlrunner.XMLTestRunner(verbosity=2, output="xmltest").run(suite) """ result = BeautifulReport(suite) result.report(description=des, filename=report_title, log_path=report) """
with Timer("Wuppertal"): result = analyzer_2.is_error_mode(start, end, "Wuppertal") self.assertEqual(result, False, f"Expected False but was {result} for Wuppertal with start {start} and end {end}.") def test_scenario_3_analyzing(self): # Part 3 analyzer_3 = WaterPumpAnalyzer() for data in error_examples.two_locations_two_errors: analyzer_3.handle_message(data) start = arrow.get(datetime(2019, 12, 3), tz.gettz('Europe/Berlin')).date() end = arrow.get(datetime(2019, 12, 4), tz.gettz('Europe/Berlin')).date() with Timer("Vienna"): result = analyzer_3.is_error_mode(start, end, "Vienna") self.assertEqual(result, True, f"Expected True but was {result} for Vienna with start {start} and end {end}. Energy consumption is higher than 20% of the average, but there was no rain!") with Timer("Bremen"): result = analyzer_3.is_error_mode(start, end, "Bremen") self.assertEqual(result, True, f"Expected True but was {result} for Bremen with start {start} and end {end}. Energy consumption is higher than 20% of the average, but there was no rain!") if __name__ == '__main__': with open('results.xml', 'w') as output: main( testRunner=xmlrunner.XMLTestRunner(output=output), failfast=False, buffer=False, catchbreak=False )
import os import sys import unittest from xmlrunner import xmlrunner def additional_tests(): setup_file = sys.modules['__main__'].__file__ print setup_file setup_dir = os.path.abspath(os.path.dirname(setup_file)) print setup_dir return unittest.defaultTestLoader.discover(setup_dir) if __name__ == '__main__': testsuit = additional_tests() result = xmlrunner.XMLTestRunner(output='test-reports').run(testsuit) if not result.wasSuccessful(): exit(1) exit(0)
import unittest from chain_monitor_test import ChainMonitorTest from xmlrunner import xmlrunner chain_monitor_test = unittest.TestLoader().loadTestsFromTestCase( ChainMonitorTest) smoke_tests = unittest.TestSuite([chain_monitor_test]) xmlrunner.XMLTestRunner(verbosity=2, output=r'test_script\test_report').run(smoke_tests)
import unittest from xmlrunner import xmlrunner from accountSignupTest import MbrTest mbr_test_job = unittest.TestLoader().loadTestsFromTestCase(MbrTest) mbr_test_job_job = unittest.TestSuite([mbr_test_job]) xmlrunner.XMLTestRunner(verbosity=2, output='test-reports').run(mbr_test_job_job)
import unittest from magentocommerce_test.homepage import HomePage from magentocommerce_test.basetestcase import BaseTestCase from magentocommerce_test.search import SearchResults from xmlrunner import xmlrunner class SearchProductTest(BaseTestCase): def SearchForProduct(self): homepage=HomePage(self.driver) search_results=homepage.search.searchFor("美赞臣") print(search_results.product_count," 对比 ") self.assertEqual(30,search_results.product_count) product=search_results.open_product_page('美赞臣(MeadJohnson)蓝臻婴儿配方奶粉 2段(6-12月龄) 900克(罐装) 荷兰原装进口 20倍乳铁蛋白') self.assertIn("美赞臣(MeadJohnson)蓝臻婴儿配方奶粉 2段(6-12月龄) 900克(罐装) 荷兰原装进口 20倍乳铁蛋白",product.name) print("价格=",product.price," 名字=",product.name) self.assertEqual("428.00",product.price) if __name__=="__main__": # unittest.main(verbosity=2) searchTest=unittest.TestLoader().loadTestsFromTestCase(SearchProductTest) suite=unittest.TestSuite([searchTest]) xmlrunner.XMLTestRunner(verbosity=2,output="test_reports").run(suite)
# 获取工程路径和测试报告路径 file_path = os.path.dirname(os.path.realpath(__file__)) project_path = os.path.dirname(os.path.realpath(file_path)) print project_path report_path = os.path.join(project_path, 'Report') print report_path # project_path = "C:\\Users\\user\\PycharmProjects\\AutoTest\\" # ---将用例添加到测试套件--- def creatsuite(): testunit = unittest.TestSuite() test_dir = project_path + "\TestCase" discover = unittest.defaultTestLoader.discover(test_dir, pattern="test_*.py", top_level_dir=None) for test_suite in discover: for test_case in test_suite: testunit.addTest(test_case) print(testunit) return testunit if __name__ == "__main__": suite = creatsuite() # runner = xmlrunner.XMLTestRunner(output='report')#输入到report文件夹中 runner = xmlrunner.XMLTestRunner(output=report_path + "\\") #输入到Report文件夹中 runner.run(suite)
import unittest from xmlrunner import xmlrunner from searchtests import SearchTests from homepagetests import HomePageTest # get all tests from SearchProductTest and HomePageTest class search_tests = unittest.TestLoader().loadTestsFromTestCase(SearchTests) home_page_tests = unittest.TestLoader().loadTestsFromTestCase(HomePageTest) # create a test suite combining search_test and home_page_test smoke_tests = unittest.TestSuite([home_page_tests, search_tests]) # run the suite xmlrunner.XMLTestRunner(verbosity=2, output='test-reports').run(smoke_tests)
from pathlib import Path from azureml.core import Workspace from azureml.pipeline.wrapper import Module from azureml.pipeline.wrapper.dsl._utils import _change_working_dir from xmlrunner import xmlrunner sys.path.insert(0, str(Path(__file__).parent.parent)) from basic_module import basic_module class TestModuleRunRelativePath(unittest.TestCase): @classmethod def setUpClass(cls) -> None: cls.workspace = Workspace.from_config( str(Path(__file__).parent.parent / 'config.json')) def test_relative(self): local_module = Module.from_func(self.workspace, basic_module) module = local_module() with _change_working_dir(Path(__file__).parent.parent): module.set_inputs(input_dir='data/basic_module/inputs/input_dir') module.set_parameters(str_param='local_test') status = module.run(use_docker=False) self.assertEqual(status, 'Completed', 'Module run failed.') if __name__ == '__main__': unittest.main(testRunner=xmlrunner.XMLTestRunner())