def _create_test_runner(self, component: str) -> None: """ Creates the test runner to use for test execution. Args: component: Name of the component to test. """ logger = logging.getLogger('suisei.sde') logger.debug('Creating test runner for component %s...', component) try: from tap import TAPTestRunner self._test_runner = TAPTestRunner( verbosity=self._application.Configuration.get_ut_verbosity( component)) self._test_runner.set_outdir( self._application.Configuration.get_ut_outdir(component)) self._test_runner.set_format( self._application.Configuration.get_ut_log_format(component)) except ImportError: logger.warning('The TAP test runner is not installed on the host ' 'system, falling back to the default unit test ' 'runner.') self._test_runner = unittest.TextTestRunner( verbosity=self._application.Configuration.get_ut_verbosity( component)) logger.debug('Test runner created successfully.')
def tracker_test_main(): """Entry point which must be called by all functional test modules.""" if cfg.tests_verbose(): # Output all logs to stderr logging.basicConfig(stream=sys.stderr, level=logging.DEBUG) else: # Output only messages from Tracker daemons under test. See # tracker.git/utils/trackertestutils/dbusdaemon.py. handler_stderr = logging.StreamHandler(stream=sys.stderr) handler_stderr.addFilter(logging.Filter('sandbox-session-bus.stderr')) handler_stdout = logging.StreamHandler(stream=sys.stderr) handler_stdout.addFilter(logging.Filter('sandbox-session-bus.stdout')) logging.basicConfig(level=logging.INFO, handlers=[handler_stderr, handler_stdout], format='%(message)s') runner = None if cfg.tap_protocol_enabled(): try: from tap import TAPTestRunner runner = TAPTestRunner() runner.set_stream(True) except ImportError as e: log.error('No TAP test runner found: %s', e) raise ut.main(testRunner=runner, failfast=True, verbosity=2)
def tracker_test_main(): """Entry point that all functional-test modules must call.""" if cfg.tests_verbose(): # Output all logs to stderr logging.basicConfig(stream=sys.stderr, level=logging.DEBUG) else: # Output some messages from D-Bus daemon to stderr by default. In practice, # only errors and warnings should be output here unless the environment # contains G_MESSAGES_DEBUG=. handler_stderr = logging.StreamHandler(stream=sys.stderr) handler_stderr.addFilter(logging.Filter('sandbox-session-bus.stderr')) handler_stdout = logging.StreamHandler(stream=sys.stderr) handler_stdout.addFilter(logging.Filter('sandbox-session-bus.stdout')) logging.basicConfig(level=logging.INFO, handlers=[handler_stderr, handler_stdout], format='%(message)s') runner = None if cfg.tap_protocol_enabled(): try: from tap import TAPTestRunner runner = TAPTestRunner() runner.set_stream(True) except ImportError as e: log.error('No TAP test runner found: %s', e) raise ut.main(testRunner=runner, verbosity=2)
def test_runner_uses_combined(self): """Test that output is combined.""" # Save previous combined in case **this** execution was using it. previous_combined = _tracker.combined TAPTestRunner.set_combined(True) self.assertTrue(_tracker.combined) _tracker.combined = previous_combined
def test_runner_stream_to_devnull_for_streaming(self): previous_streaming = _tracker.streaming previous_stream = _tracker.stream runner = TAPTestRunner() runner.set_stream(True) self.assertTrue(runner.stream.stream.name, os.devnull) _tracker.streaming = previous_streaming _tracker.stream = previous_stream
def test_runner_uses_format(self): """Test that format is set on TAPTestResult FORMAT.""" # Save the previous format in case **this** execution was using it. previous_format = TAPTestResult.FORMAT fmt = "{method_name}: {short_description}" TAPTestRunner.set_format(fmt) self.assertEqual(fmt, TAPTestResult.FORMAT) TAPTestResult.FORMAT = previous_format
def test_runner_uses_header(self): """Test that the case header can be turned off.""" # Save previous header in case **this** execution was using it. previous_header = _tracker.header TAPTestRunner.set_header(False) self.assertFalse(_tracker.header) TAPTestRunner.set_header(True) self.assertTrue(_tracker.header) _tracker.header = previous_header
def test_runner_sets_tracker_for_streaming(self): """The tracker is set for streaming mode.""" previous_streaming = _tracker.streaming previous_stream = _tracker.stream runner = TAPTestRunner() runner.set_stream(True) self.assertTrue(_tracker.streaming) self.assertTrue(_tracker.stream, sys.stdout) _tracker.streaming = previous_streaming _tracker.stream = previous_stream
def test_bad_format_string(self, fake_exit): """A bad format string exits the runner.""" previous_format = TAPTestResult.FORMAT bad_format = "Not gonna work {sort_desc}" TAPTestRunner.set_format(bad_format) result = TAPTestResult(None, True, 1) test = mock.Mock() result._description(test) self.assertTrue(fake_exit.called) TAPTestResult.FORMAT = previous_format
def run_suite(suite): if cfg.tap_protocol_enabled(): try: from tap import TAPTestRunner runner = TAPTestRunner() runner.set_stream(True) except ImportError as e: log.error('No TAP test runner found: %s', e) raise else: runner = ut.TextTestRunner(verbosity=1) result = runner.run(suite) sys.exit(not result.wasSuccessful())
def test_runner_uses_outdir(self): """Test that the test runner sets the TAPTestResult OUTDIR so that TAP files will be written to that location. Setting class attributes to get the right behavior is a dirty hack, but the unittest classes aren't very extensible. """ # Save the previous outdir in case **this** execution was using it. previous_outdir = TAPTestResult outdir = tempfile.mkdtemp() TAPTestRunner.set_outdir(outdir) self.assertEqual(outdir, TAPTestResult.OUTDIR) TAPTestResult.OUTDIR = previous_outdir
def test_runner_uses_outdir(self): """Test that the test runner sets the outdir so that TAP files will be written to that location. Setting class attributes to get the right behavior is a dirty hack, but the unittest classes aren't very extensible. """ # Save the previous outdir in case **this** execution was using it. previous_outdir = _tracker.outdir outdir = tempfile.mkdtemp() TAPTestRunner.set_outdir(outdir) self.assertEqual(outdir, _tracker.outdir) _tracker.outdir = previous_outdir
# Copyright (c) 2015, Matt Layman import os import unittest from tap import TAPTestRunner if __name__ == '__main__': tests_dir = os.path.dirname(os.path.abspath(__file__)) loader = unittest.TestLoader() tests = loader.discover(tests_dir) runner = TAPTestRunner() runner.set_outdir('testout') runner.set_format('Hi: {method_name} - {short_description}') runner.run(tests)
# -*- coding: utf-8; -*- # # Copyright © 2014, Nicolas CANIART <*****@*****.**> # import os import sys from unittest import TestLoader try: from tap import TAPTestRunner as TestRunner tap_output = os.path.join(os.path.dirname(__file__), 'tap') TestRunner.set_outdir(tap_output) except ImportError: from unittest import TextTestRunner as TestRunner path = os.path.dirname(__file__) res = TestRunner(verbosity=2).run( TestLoader().discover('./', pattern='test_*.py')) sys.exit(not res.wasSuccessful()) # vim: syntax=python:sws=4:sw=4:et:
def execute(self): runner = TAPTestRunner() runner.set_outdir('logs/TAP/') runner.set_format('{method_name} and {short_description}') runner.set_combined(True) runner.run(self.suite)
# Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. from tap import TAPTestRunner import unittest import sys if __name__ == '__main__': loader = unittest.TestLoader() tests = loader.discover(sys.argv[1]) runner = TAPTestRunner() runner.set_stream(True) runner.set_format('{method_name}') sys.exit(0 if runner.run(tests).wasSuccessful() else 1)
# Copyright (c) 2018, Matt Layman and contributors import os import unittest from tap import TAPTestRunner if __name__ == "__main__": tests_dir = os.path.dirname(os.path.abspath(__file__)) loader = unittest.TestLoader() tests = loader.discover(tests_dir) runner = TAPTestRunner() runner.set_outdir("testout") runner.set_format("Hi: {method_name} - {short_description}") runner.run(tests)
# Copyright (c) 2015, Matt Layman import os import unittest from tap import TAPTestRunner if __name__ == '__main__': tests_dir = os.path.dirname(os.path.abspath(__file__)) loader = unittest.TestLoader() tests = loader.discover(tests_dir) runner = TAPTestRunner() runner.run(tests)
stderr=subprocess.DEVNULL)) for setup in setups: setup.wait() if setup.returncode != 0: raise Exception('Setup failed') def run_teardowns(tests): teardowns = [] for test in tests: test_dir = path_from_name(test[0], 'plain') if os.path.isfile(os.path.join(test_dir, 'teardown.sh')): teardowns.append(subprocess.Popen('./teardown.sh', cwd=test_dir, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)) for teardown in teardowns: teardown.wait() if __name__ == '__main__': tests = get_test_cases() run_setups(tests) suite = unittest.TestSuite() for test in tests: suite.addTest(test[1]()) runner = TAPTestRunner() runner.set_format('{method_name}') runner.set_stream(True) runner.run(suite) run_teardowns(tests)
# -*- coding: utf-8; -*- # # Copyright © 2014-2015, Nicolas CANIART <*****@*****.**> # import os import sys from unittest import TestLoader path = os.path.dirname(__file__) try: from tap import TAPTestRunner as TestRunner TestRunner.set_outdir(os.path.join(path, 'tap')) except ImportError: from unittest import TextTestRunner as TestRunner res = TestRunner(verbosity=2).run( TestLoader().discover('./', pattern='test_*.py')) sys.exit(not res.wasSuccessful()) # vim: syntax=python:sws=4:sw=4:et:
# -*- coding: utf-8; -*- # # Copyright © 2014-2015, Nicolas CANIART <*****@*****.**> # import os import sys from unittest import TestLoader path = os.path.dirname(__file__) try: from tap import TAPTestRunner as TestRunner TestRunner.set_outdir(os.path.join(path, 'tap')) except ImportError: from unittest import TextTestRunner as TestRunner res = TestRunner(verbosity=2).run(TestLoader().discover('./', pattern='test_*.py')) sys.exit(not res.wasSuccessful()) # vim: syntax=python:sws=4:sw=4:et:
) args = argparser.parse_args() loader = unittest.TestLoader() start_dir = args.start_dir pattern = args.pattern failfast = args.failfast test_case = args.test_case if test_case: sys.path.append(start_dir) tests = loader.loadTestsFromName(test_case) elif pattern: tests = loader.discover(start_dir, pattern) else: # This will never happen because the mutual exclusion group has the # `required` parameter set to True. So one or the other must be set or # else it will fail to parse. sys.exit(1) if tests.countTestCases() < 1: print("No tests matching '%s' found in '%s'" % (pattern, start_dir)) sys.exit(1) runner = TAPTestRunner(failfast=failfast) runner.set_stream(True) runner.set_format('{method_name}') sys.exit(0 if runner.run(tests).wasSuccessful() else 1)
def test_has_tap_test_result(self): runner = TAPTestRunner() self.assertEqual(runner.resultclass, TAPTestResult)
# Copyright (c) 2014, Matt Layman import os import unittest from tap import TAPTestRunner if __name__ == '__main__': tests_dir = os.path.dirname(os.path.abspath(__file__)) loader = unittest.TestLoader() tests = loader.discover(tests_dir) runner = TAPTestRunner() runner.run(tests)
# Copyright (c) 2019, Matt Layman and contributors import os import unittest from tap import TAPTestRunner if __name__ == "__main__": tests_dir = os.path.dirname(os.path.abspath(__file__)) loader = unittest.TestLoader() tests = loader.discover(tests_dir) runner = TAPTestRunner() runner.set_outdir("testout") runner.set_format("Hi: {method_name} - {short_description}") runner.run(tests)
setup.wait() if setup.returncode != 0: raise Exception('Setup failed') def run_teardowns(tests): teardowns = [] for test in tests: test_dir = path_from_name(test[0], 'plain') if os.path.isfile(os.path.join(test_dir, 'teardown.sh')): teardowns.append( subprocess.Popen('./teardown.sh', cwd=test_dir, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)) for teardown in teardowns: teardown.wait() if __name__ == '__main__': tests = get_test_cases() run_setups(tests) suite = unittest.TestSuite() for test in tests: suite.addTest(test[1]()) runner = TAPTestRunner() runner.set_format('{method_name}') runner.set_stream(True) runner.run(suite) run_teardowns(tests)
class UnitTestExecutor(Executor): """ Executor implementation to run the unit tests of a component. """ def __init__(self, component: str, application: SdeApplication) -> None: """ Creates a new UnitTestExecutor instance. Args: component: The component which will be tested. application: The SDE application instance. measure_coverage: Whether or not unit test coverage should be measured. """ super().__init__(application) self._test_runner = None """ The test runner used to execute the test. """ self._component = component """ The component to test. """ def execute(self) -> None: """ Executes the tests. """ logger = logging.getLogger('suisei.sde') # Prepare the test directory self._prepare_directory() components = [] if self._component != 'all': components.append(self._component) else: components = self._application.Configuration.Components for component in components: logger.debug('Executing unit tests for component %s', component) self._create_test_runner(component) test_suite = self._build_test_suite(component) self._test_runner.run(test_suite) logger.debug('All tests executed.') @staticmethod def _prepare_directory() -> None: """ Prepare the .testfiles directory. Create it if it doesn't exist and remove all files from it if it already exists. """ test_directory = os.path.abspath('./.testfiles/') if os.path.isdir(test_directory): # There is already a .testfiles directory, clean it up import shutil shutil.rmtree(test_directory) # Create an empty .testfiles directory os.makedirs(test_directory) def _create_test_runner(self, component: str) -> None: """ Creates the test runner to use for test execution. Args: component: Name of the component to test. """ logger = logging.getLogger('suisei.sde') logger.debug('Creating test runner for component %s...', component) try: from tap import TAPTestRunner self._test_runner = TAPTestRunner( verbosity=self._application.Configuration.get_ut_verbosity( component)) self._test_runner.set_outdir( self._application.Configuration.get_ut_outdir(component)) self._test_runner.set_format( self._application.Configuration.get_ut_log_format(component)) except ImportError: logger.warning('The TAP test runner is not installed on the host ' 'system, falling back to the default unit test ' 'runner.') self._test_runner = unittest.TextTestRunner( verbosity=self._application.Configuration.get_ut_verbosity( component)) logger.debug('Test runner created successfully.') def _build_test_suite(self, component: str) -> unittest.TestSuite: """ Builds the test suite for the given component. If test coverage is not measured, then we can just use Python's built-in test discovery tool to gather the tests to run. When test coverage is measured all tests need to be imported manually here to avoid coverage missing imports and function definitions. Args: component: Name of the component to test. """ logger = logging.getLogger('suisei.sde') logger.debug('Building test suite to execute...') test_loader = unittest.TestLoader() unit_test_path = \ self._application.Configuration.get_test_file_path(component) logger.debug('Path to search for test files: %s', unit_test_path) logger.debug('Using Python\'s internal test discovery...') test_suite = test_loader.discover(start_dir=unit_test_path, pattern='test_*.py') return test_suite