xref: /honee/tests/junit.py (revision 3c97163bd94436e90100b170d0f9ec29b4c92b80)
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
37*3c97163bSJames Wrightdef diff_csv_comment_function(test_line: str, true_line: str) -> Optional[str]:
38*3c97163bSJames Wright    test_line_split = test_line.split(':')[0]
39*3c97163bSJames Wright    true_line_split = true_line.split(':')[0]
40*3c97163bSJames Wright    diff_output = ''.join(difflib.unified_diff([test_line_split + '\n'],
41*3c97163bSJames Wright                                               [true_line_split + '\n'],
42*3c97163bSJames Wright                                               tofile='test created file',
43*3c97163bSJames Wright                                               fromfile='expected output'))
44*3c97163bSJames Wright    return diff_output if diff_output else None
45*3c97163bSJames Wright
46*3c97163bSJames Wright
479f354ecaSJames Wrightclass HoneeSuiteSpec(SuiteSpec):
480006be33SJames Wright    def __init__(self, has_torch: bool):
490006be33SJames Wright        self.has_torch: bool = has_torch
50*3c97163bSJames 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        if contains_any(resource, ['occa']) and startswith_any(
1030006be33SJames Wright                test, ['t4', 't5', 'ex', 'mfem', 'nek', 'petsc', 'fluids', 'solids']):
1040006be33SJames Wright            return 'OCCA mode not supported'
1050006be33SJames Wright        if test.startswith('t318') and contains_any(resource, ['/gpu/cuda/ref']):
1060006be33SJames Wright            return 'CUDA ref backend not supported'
1070006be33SJames Wright        if test.startswith('t506') and contains_any(resource, ['/gpu/cuda/shared']):
1080006be33SJames Wright            return 'CUDA shared backend not supported'
1090006be33SJames Wright        for condition in spec.only:
1100006be33SJames Wright            if (condition == 'cpu') and ('gpu' in resource):
1110006be33SJames Wright                return 'CPU only test with GPU backend'
1120006be33SJames Wright            if condition == 'torch' and not self.has_torch:
1130006be33SJames Wright                return 'PyTorch only test without USE_TORCH=1'
1140006be33SJames Wright
1150006be33SJames Wright    def check_post_skip(self, test: str, spec: TestSpec, resource: str, stderr: str) -> Optional[str]:
1160006be33SJames Wright        """Check if a test case should be allowed to fail, based on its stderr output
1170006be33SJames Wright
1180006be33SJames Wright        Args:
1190006be33SJames Wright            test (str): Name of test
1200006be33SJames Wright            spec (TestSpec): Test case specification
1210006be33SJames Wright            resource (str): libCEED backend
1220006be33SJames Wright            stderr (str): Standard error output from test case execution
1230006be33SJames Wright
1240006be33SJames Wright        Returns:
1250006be33SJames Wright            Optional[str]: Skip reason, or `None` if unexpeced error
1260006be33SJames Wright        """
1270006be33SJames Wright        if 'OCCA backend failed to use' in stderr:
1280006be33SJames Wright            return f'OCCA mode not supported'
1290006be33SJames Wright        elif 'Backend does not implement' in stderr:
1300006be33SJames Wright            return f'Backend does not implement'
1310006be33SJames Wright        elif 'Can only provide HOST memory for this backend' in stderr:
1320006be33SJames Wright            return f'Device memory not supported'
1330006be33SJames Wright        elif 'Can only set HOST memory for this backend' in stderr:
1340006be33SJames Wright            return f'Device memory not supported'
1350006be33SJames Wright        elif 'Test not implemented in single precision' in stderr:
1360006be33SJames Wright            return f'Test not implemented in single precision'
1370006be33SJames Wright        elif 'No SYCL devices of the requested type are available' in stderr:
1380006be33SJames Wright            return f'SYCL device type not available'
1390006be33SJames Wright        elif 'You may need to add --download-ctetgen or --download-tetgen' in stderr:
1400006be33SJames Wright            return f'Tet mesh generator not installed for {test}, {spec.name}'
1410006be33SJames Wright        return None
1420006be33SJames Wright
1430006be33SJames Wright    def check_required_failure(self, test: str, spec: TestSpec, resource: str, stderr: str) -> Tuple[str, bool]:
1440006be33SJames Wright        """Check whether a test case is expected to fail and if it failed expectedly
1450006be33SJames Wright
1460006be33SJames Wright        Args:
1470006be33SJames Wright            test (str): Name of test
1480006be33SJames Wright            spec (TestSpec): Test case specification
1490006be33SJames Wright            resource (str): libCEED backend
1500006be33SJames Wright            stderr (str): Standard error output from test case execution
1510006be33SJames Wright
1520006be33SJames Wright        Returns:
1530006be33SJames Wright            tuple[str, bool]: Tuple of the expected failure string and whether it was present in `stderr`
1540006be33SJames Wright        """
1550006be33SJames Wright        test_id: str = test[:4]
1560006be33SJames Wright        fail_str: str = ''
1570006be33SJames Wright        if test_id in ['t006', 't007']:
1580006be33SJames Wright            fail_str = 'No suitable backend:'
1590006be33SJames Wright        elif test_id in ['t008']:
1600006be33SJames Wright            fail_str = 'Available backend resources:'
1610006be33SJames Wright        elif test_id in ['t110', 't111', 't112', 't113', 't114']:
1620006be33SJames Wright            fail_str = 'Cannot grant CeedVector array access'
1630006be33SJames Wright        elif test_id in ['t115']:
1640006be33SJames Wright            fail_str = 'Cannot grant CeedVector read-only array access, the access lock is already in use'
1650006be33SJames Wright        elif test_id in ['t116']:
1660006be33SJames Wright            fail_str = 'Cannot destroy CeedVector, the writable access lock is in use'
1670006be33SJames Wright        elif test_id in ['t117']:
1680006be33SJames Wright            fail_str = 'Cannot restore CeedVector array access, access was not granted'
1690006be33SJames Wright        elif test_id in ['t118']:
1700006be33SJames Wright            fail_str = 'Cannot sync CeedVector, the access lock is already in use'
1710006be33SJames Wright        elif test_id in ['t215']:
1720006be33SJames Wright            fail_str = 'Cannot destroy CeedElemRestriction, a process has read access to the offset data'
1730006be33SJames Wright        elif test_id in ['t303']:
1740006be33SJames Wright            fail_str = 'Length of input/output vectors incompatible with basis dimensions'
1750006be33SJames Wright        elif test_id in ['t408']:
1760006be33SJames Wright            fail_str = 'CeedQFunctionContextGetData(): Cannot grant CeedQFunctionContext data access, a process has read access'
1770006be33SJames Wright        elif test_id in ['t409'] and contains_any(resource, ['memcheck']):
1780006be33SJames Wright            fail_str = 'Context data changed while accessed in read-only mode'
1790006be33SJames Wright
1800006be33SJames Wright        return fail_str, fail_str in stderr
1810006be33SJames Wright
1820006be33SJames Wright    def check_allowed_stdout(self, test: str) -> bool:
1830006be33SJames Wright        """Check whether a test is allowed to print console output
1840006be33SJames Wright
1850006be33SJames Wright        Args:
1860006be33SJames Wright            test (str): Name of test
1870006be33SJames Wright
1880006be33SJames Wright        Returns:
1890006be33SJames Wright            bool: True if the test is allowed to print console output
1900006be33SJames Wright        """
1910006be33SJames Wright        return test[:4] in ['t003']
1920006be33SJames Wright
1930006be33SJames Wright
1940006be33SJames Wrightif __name__ == '__main__':
1950006be33SJames Wright    args = create_argparser().parse_args()
1960006be33SJames Wright
1970006be33SJames Wright    # run tests
1980006be33SJames Wright    if 'smartsim' in args.test:
1990006be33SJames Wright        has_smartsim: bool = args.smartredis_dir and Path(args.smartredis_dir).is_dir()
2000006be33SJames Wright        test_cases = []
2010006be33SJames Wright
2020006be33SJames Wright        if args.mode is RunMode.TAP:
2030006be33SJames Wright            print(f'1..1')
2040006be33SJames Wright        if has_smartsim:
2050006be33SJames Wright            from smartsim_regression_framework import SmartSimTest
2060006be33SJames Wright
207aa34f9e7SJames Wright            test_framework = SmartSimTest(Path(__file__).parent / 'smartsim_test_dir')
2080006be33SJames Wright            test_framework.setup()
2090006be33SJames Wright
2100006be33SJames Wright            is_new_subtest = True
2110006be33SJames Wright            subtest_ok = True
2120006be33SJames Wright            for i, backend in enumerate(args.ceed_backends):
2130006be33SJames Wright                test_cases.append(test_framework.test_junit(backend))
2140006be33SJames Wright                if is_new_subtest and args.mode == RunMode.TAP:
2150006be33SJames Wright                    is_new_subtest = False
2160006be33SJames Wright                    print(f'# Subtest: {test_cases[0].category}')
2170006be33SJames Wright                    print(f'    1..{len(args.ceed_backends)}')
2180006be33SJames Wright                print(test_case_output_string(test_cases[i], TestSpec("SmartSim Tests"), args.mode, backend, '', i))
2190006be33SJames Wright            if args.mode == RunMode.TAP:
2200006be33SJames Wright                print(f'{"" if subtest_ok else "not "}ok 1 - {test_cases[0].category}')
2210006be33SJames Wright            test_framework.teardown()
2220006be33SJames Wright        elif args.mode is RunMode.TAP:
2230006be33SJames Wright            print(f'ok 1 - # SKIP SmartSim not installed')
2240006be33SJames Wright        result: TestSuite = TestSuite('SmartSim Tests', test_cases)
2250006be33SJames Wright    else:
2260006be33SJames Wright        result: TestSuite = run_tests(
2270006be33SJames Wright            args.test,
2280006be33SJames Wright            args.ceed_backends,
2290006be33SJames Wright            args.mode,
2300006be33SJames Wright            args.nproc,
2319f354ecaSJames Wright            HoneeSuiteSpec(args.has_torch),
2320006be33SJames Wright            args.pool_size)
2330006be33SJames Wright
2340006be33SJames Wright    # write output and check for failures
2350006be33SJames Wright    if args.mode is RunMode.JUNIT:
2360006be33SJames Wright        write_junit_xml(result, args.output, args.junit_batch)
2370006be33SJames Wright        if has_failures(result):
2380006be33SJames Wright            sys.exit(1)
239