xref: /honee/tests/junit.py (revision c4a0f6c70b78c252d6743c2c37342b2b816e62bf)
10006be33SJames Wright#!/usr/bin/env python3
20006be33SJames Wrightfrom junit_common import *
30006be33SJames Wright
40006be33SJames Wright
50006be33SJames Wrightdef create_argparser() -> argparse.ArgumentParser:
60006be33SJames Wright    """Creates argument parser to read command line arguments
70006be33SJames Wright
80006be33SJames Wright    Returns:
90006be33SJames Wright        argparse.ArgumentParser: Created `ArgumentParser`
100006be33SJames Wright    """
110006be33SJames Wright    parser = argparse.ArgumentParser('Test runner with JUnit and TAP output')
120006be33SJames Wright    parser.add_argument(
130006be33SJames Wright        '-c',
140006be33SJames Wright        '--ceed-backends',
150006be33SJames Wright        type=str,
160006be33SJames Wright        nargs='*',
170006be33SJames Wright        default=['/cpu/self'],
180006be33SJames Wright        help='libCEED backend to use with convergence tests')
190006be33SJames Wright    parser.add_argument(
200006be33SJames Wright        '-m',
210006be33SJames Wright        '--mode',
220006be33SJames Wright        type=RunMode,
230006be33SJames Wright        action=CaseInsensitiveEnumAction,
240006be33SJames Wright        help='Output mode, junit or tap',
250006be33SJames Wright        default=RunMode.JUNIT)
260006be33SJames Wright    parser.add_argument('-n', '--nproc', type=int, default=1, help='number of MPI processes')
270006be33SJames Wright    parser.add_argument('-o', '--output', type=Optional[Path], default=None, help='Output file to write test')
280006be33SJames Wright    parser.add_argument('-b', '--junit-batch', type=str, default='', help='Name of JUnit batch for output file')
290006be33SJames Wright    parser.add_argument('-np', '--pool-size', type=int, default=1, help='Number of test cases to run in parallel')
300006be33SJames Wright    parser.add_argument('-s', '--smartredis_dir', type=str, default='', help='path to SmartSim library, if present')
310006be33SJames Wright    parser.add_argument('--has_torch', type=bool, default=False, help='Whether to build with torch')
320006be33SJames Wright    parser.add_argument('test', help='Test executable', nargs='?')
330006be33SJames Wright
340006be33SJames Wright    return parser
350006be33SJames Wright
360006be33SJames Wright
373c97163bSJames Wrightdef diff_csv_comment_function(test_line: str, true_line: str) -> Optional[str]:
383c97163bSJames Wright    test_line_split = test_line.split(':')[0]
393c97163bSJames Wright    true_line_split = true_line.split(':')[0]
403c97163bSJames Wright    diff_output = ''.join(difflib.unified_diff([test_line_split + '\n'],
413c97163bSJames Wright                                               [true_line_split + '\n'],
423c97163bSJames Wright                                               tofile='test created file',
433c97163bSJames Wright                                               fromfile='expected output'))
443c97163bSJames Wright    return diff_output if diff_output else None
453c97163bSJames Wright
463c97163bSJames Wright
479f354ecaSJames Wrightclass HoneeSuiteSpec(SuiteSpec):
480006be33SJames Wright    def __init__(self, has_torch: bool):
490006be33SJames Wright        self.has_torch: bool = has_torch
503c97163bSJames Wright        self.diff_csv_kwargs: dict = {'comment_func': diff_csv_comment_function, 'rel_tol': 1e-9}
510006be33SJames Wright
520006be33SJames Wright    def get_source_path(self, test: str) -> Path:
530006be33SJames Wright        """Compute path to test source file
540006be33SJames Wright
550006be33SJames Wright        Args:
560006be33SJames Wright            test (str): Name of test
570006be33SJames Wright
580006be33SJames Wright        Returns:
590006be33SJames Wright            Path: Path to source file
600006be33SJames Wright        """
61149fb536SJames Wright        if test.startswith('navierstokes'):
62149fb536SJames Wright            return (Path('examples') / 'navierstokes').with_suffix('.c')
63149fb536SJames Wright        else:
64149fb536SJames Wright            return (Path('tests') / test).with_suffix('.c')
650006be33SJames Wright
660006be33SJames Wright    # get path to executable
670006be33SJames Wright    def get_run_path(self, test: str) -> Path:
680006be33SJames Wright        """Compute path to built test executable file
690006be33SJames Wright
700006be33SJames Wright        Args:
710006be33SJames Wright            test (str): Name of test
720006be33SJames Wright
730006be33SJames Wright        Returns:
740006be33SJames Wright            Path: Path to test executable
750006be33SJames Wright        """
760006be33SJames Wright        return Path('build') / test
770006be33SJames Wright
780006be33SJames Wright    def get_output_path(self, test: str, output_file: str) -> Path:
790006be33SJames Wright        """Compute path to expected output file
800006be33SJames Wright
810006be33SJames Wright        Args:
820006be33SJames Wright            test (str): Name of test
830006be33SJames Wright            output_file (str): File name of output file
840006be33SJames Wright
850006be33SJames Wright        Returns:
860006be33SJames Wright            Path: Path to expected output file
870006be33SJames Wright        """
880006be33SJames Wright        return Path('tests') / 'output' / output_file
890006be33SJames Wright
900006be33SJames Wright    def check_pre_skip(self, test: str, spec: TestSpec, resource: str, nproc: int) -> Optional[str]:
910006be33SJames Wright        """Check if a test case should be skipped prior to running, returning the reason for skipping
920006be33SJames Wright
930006be33SJames Wright        Args:
940006be33SJames Wright            test (str): Name of test
950006be33SJames Wright            spec (TestSpec): Test case specification
960006be33SJames Wright            resource (str): libCEED backend
970006be33SJames Wright            nproc (int): Number of MPI processes to use when running test case
980006be33SJames Wright
990006be33SJames Wright        Returns:
1000006be33SJames Wright            Optional[str]: Skip reason, or `None` if test case should not be skipped
1010006be33SJames Wright        """
1020006be33SJames Wright        for condition in spec.only:
1030006be33SJames Wright            if (condition == 'cpu') and ('gpu' in resource):
1040006be33SJames Wright                return 'CPU only test with GPU backend'
1050006be33SJames Wright            if condition == 'torch' and not self.has_torch:
1060006be33SJames Wright                return 'PyTorch only test without USE_TORCH=1'
1070006be33SJames Wright
1080006be33SJames Wright    def check_post_skip(self, test: str, spec: TestSpec, resource: str, stderr: str) -> Optional[str]:
1090006be33SJames Wright        """Check if a test case should be allowed to fail, based on its stderr output
1100006be33SJames Wright
1110006be33SJames Wright        Args:
1120006be33SJames Wright            test (str): Name of test
1130006be33SJames Wright            spec (TestSpec): Test case specification
1140006be33SJames Wright            resource (str): libCEED backend
1150006be33SJames Wright            stderr (str): Standard error output from test case execution
1160006be33SJames Wright
1170006be33SJames Wright        Returns:
1180006be33SJames Wright            Optional[str]: Skip reason, or `None` if unexpeced error
1190006be33SJames Wright        """
1209d4cbeb3SJames Wright        if 'No SYCL devices of the requested type are available' in stderr:
1210006be33SJames Wright            return f'SYCL device type not available'
122*c4a0f6c7SJames Wright        elif 'Loading meshes requires CGNS support. Reconfigure using --with-cgns-dir' in stderr:
123*c4a0f6c7SJames Wright            return f'CGNS not installed in PETSc for {test}, {spec.name}'
1240006be33SJames Wright        elif 'You may need to add --download-ctetgen or --download-tetgen' in stderr:
1250006be33SJames Wright            return f'Tet mesh generator not installed for {test}, {spec.name}'
1260006be33SJames Wright        return None
1270006be33SJames Wright
1280006be33SJames Wright    def check_required_failure(self, test: str, spec: TestSpec, resource: str, stderr: str) -> Tuple[str, bool]:
1290006be33SJames Wright        """Check whether a test case is expected to fail and if it failed expectedly
1300006be33SJames Wright
1310006be33SJames Wright        Args:
1320006be33SJames Wright            test (str): Name of test
1330006be33SJames Wright            spec (TestSpec): Test case specification
1340006be33SJames Wright            resource (str): libCEED backend
1350006be33SJames Wright            stderr (str): Standard error output from test case execution
1360006be33SJames Wright
1370006be33SJames Wright        Returns:
1380006be33SJames Wright            tuple[str, bool]: Tuple of the expected failure string and whether it was present in `stderr`
1390006be33SJames Wright        """
1409d4cbeb3SJames Wright        return '', True
1410006be33SJames Wright
1420006be33SJames Wright    def check_allowed_stdout(self, test: str) -> bool:
1430006be33SJames Wright        """Check whether a test is allowed to print console output
1440006be33SJames Wright
1450006be33SJames Wright        Args:
1460006be33SJames Wright            test (str): Name of test
1470006be33SJames Wright
1480006be33SJames Wright        Returns:
1490006be33SJames Wright            bool: True if the test is allowed to print console output
1500006be33SJames Wright        """
1519d4cbeb3SJames Wright        return False
1520006be33SJames Wright
1530006be33SJames Wright
1540006be33SJames Wrightif __name__ == '__main__':
1550006be33SJames Wright    args = create_argparser().parse_args()
1560006be33SJames Wright
1570006be33SJames Wright    # run tests
1580006be33SJames Wright    if 'smartsim' in args.test:
1590006be33SJames Wright        has_smartsim: bool = args.smartredis_dir and Path(args.smartredis_dir).is_dir()
1600006be33SJames Wright        test_cases = []
1610006be33SJames Wright
1620006be33SJames Wright        if args.mode is RunMode.TAP:
1630006be33SJames Wright            print(f'1..1')
1640006be33SJames Wright        if has_smartsim:
1650006be33SJames Wright            from smartsim_regression_framework import SmartSimTest
1660006be33SJames Wright
167aa34f9e7SJames Wright            test_framework = SmartSimTest(Path(__file__).parent / 'smartsim_test_dir')
1680006be33SJames Wright            test_framework.setup()
1690006be33SJames Wright
1700006be33SJames Wright            is_new_subtest = True
1710006be33SJames Wright            subtest_ok = True
1720006be33SJames Wright            for i, backend in enumerate(args.ceed_backends):
1730006be33SJames Wright                test_cases.append(test_framework.test_junit(backend))
1740006be33SJames Wright                if is_new_subtest and args.mode == RunMode.TAP:
1750006be33SJames Wright                    is_new_subtest = False
1760006be33SJames Wright                    print(f'# Subtest: {test_cases[0].category}')
1770006be33SJames Wright                    print(f'    1..{len(args.ceed_backends)}')
1780006be33SJames Wright                print(test_case_output_string(test_cases[i], TestSpec("SmartSim Tests"), args.mode, backend, '', i))
1790006be33SJames Wright            if args.mode == RunMode.TAP:
1800006be33SJames Wright                print(f'{"" if subtest_ok else "not "}ok 1 - {test_cases[0].category}')
1810006be33SJames Wright            test_framework.teardown()
1820006be33SJames Wright        elif args.mode is RunMode.TAP:
1830006be33SJames Wright            print(f'ok 1 - # SKIP SmartSim not installed')
1840006be33SJames Wright        result: TestSuite = TestSuite('SmartSim Tests', test_cases)
1850006be33SJames Wright    else:
1860006be33SJames Wright        result: TestSuite = run_tests(
1870006be33SJames Wright            args.test,
1880006be33SJames Wright            args.ceed_backends,
1890006be33SJames Wright            args.mode,
1900006be33SJames Wright            args.nproc,
1919f354ecaSJames Wright            HoneeSuiteSpec(args.has_torch),
1920006be33SJames Wright            args.pool_size)
1930006be33SJames Wright
1940006be33SJames Wright    # write output and check for failures
1950006be33SJames Wright    if args.mode is RunMode.JUNIT:
1960006be33SJames Wright        write_junit_xml(result, args.output, args.junit_batch)
1970006be33SJames Wright        if has_failures(result):
1980006be33SJames Wright            sys.exit(1)
199