xref: /honee/tests/junit.py (revision 149fb5361f5198e41f87e8815a7e9dbfee84a96a)
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
370006be33SJames Wright# Necessary functions for running tests
380006be33SJames Wrightclass CeedSuiteSpec(SuiteSpec):
390006be33SJames Wright    def __init__(self, has_torch: bool):
400006be33SJames Wright        self.has_torch: bool = has_torch
410006be33SJames Wright
420006be33SJames Wright    def get_source_path(self, test: str) -> Path:
430006be33SJames Wright        """Compute path to test source file
440006be33SJames Wright
450006be33SJames Wright        Args:
460006be33SJames Wright            test (str): Name of test
470006be33SJames Wright
480006be33SJames Wright        Returns:
490006be33SJames Wright            Path: Path to source file
500006be33SJames Wright        """
51*149fb536SJames Wright        if test.startswith('navierstokes'):
52*149fb536SJames Wright            return (Path('examples') / 'navierstokes').with_suffix('.c')
53*149fb536SJames Wright        else:
54*149fb536SJames Wright            return (Path('tests') / test).with_suffix('.c')
550006be33SJames Wright
560006be33SJames Wright    # get path to executable
570006be33SJames Wright    def get_run_path(self, test: str) -> Path:
580006be33SJames Wright        """Compute path to built test executable file
590006be33SJames Wright
600006be33SJames Wright        Args:
610006be33SJames Wright            test (str): Name of test
620006be33SJames Wright
630006be33SJames Wright        Returns:
640006be33SJames Wright            Path: Path to test executable
650006be33SJames Wright        """
660006be33SJames Wright        return Path('build') / test
670006be33SJames Wright
680006be33SJames Wright    def get_output_path(self, test: str, output_file: str) -> Path:
690006be33SJames Wright        """Compute path to expected output file
700006be33SJames Wright
710006be33SJames Wright        Args:
720006be33SJames Wright            test (str): Name of test
730006be33SJames Wright            output_file (str): File name of output file
740006be33SJames Wright
750006be33SJames Wright        Returns:
760006be33SJames Wright            Path: Path to expected output file
770006be33SJames Wright        """
780006be33SJames Wright        return Path('tests') / 'output' / output_file
790006be33SJames Wright
800006be33SJames Wright    def check_pre_skip(self, test: str, spec: TestSpec, resource: str, nproc: int) -> Optional[str]:
810006be33SJames Wright        """Check if a test case should be skipped prior to running, returning the reason for skipping
820006be33SJames Wright
830006be33SJames Wright        Args:
840006be33SJames Wright            test (str): Name of test
850006be33SJames Wright            spec (TestSpec): Test case specification
860006be33SJames Wright            resource (str): libCEED backend
870006be33SJames Wright            nproc (int): Number of MPI processes to use when running test case
880006be33SJames Wright
890006be33SJames Wright        Returns:
900006be33SJames Wright            Optional[str]: Skip reason, or `None` if test case should not be skipped
910006be33SJames Wright        """
920006be33SJames Wright        if contains_any(resource, ['occa']) and startswith_any(
930006be33SJames Wright                test, ['t4', 't5', 'ex', 'mfem', 'nek', 'petsc', 'fluids', 'solids']):
940006be33SJames Wright            return 'OCCA mode not supported'
950006be33SJames Wright        if test.startswith('t318') and contains_any(resource, ['/gpu/cuda/ref']):
960006be33SJames Wright            return 'CUDA ref backend not supported'
970006be33SJames Wright        if test.startswith('t506') and contains_any(resource, ['/gpu/cuda/shared']):
980006be33SJames Wright            return 'CUDA shared backend not supported'
990006be33SJames Wright        for condition in spec.only:
1000006be33SJames Wright            if (condition == 'cpu') and ('gpu' in resource):
1010006be33SJames Wright                return 'CPU only test with GPU backend'
1020006be33SJames Wright            if condition == 'torch' and not self.has_torch:
1030006be33SJames Wright                return 'PyTorch only test without USE_TORCH=1'
1040006be33SJames Wright
1050006be33SJames Wright    def check_post_skip(self, test: str, spec: TestSpec, resource: str, stderr: str) -> Optional[str]:
1060006be33SJames Wright        """Check if a test case should be allowed to fail, based on its stderr output
1070006be33SJames Wright
1080006be33SJames Wright        Args:
1090006be33SJames Wright            test (str): Name of test
1100006be33SJames Wright            spec (TestSpec): Test case specification
1110006be33SJames Wright            resource (str): libCEED backend
1120006be33SJames Wright            stderr (str): Standard error output from test case execution
1130006be33SJames Wright
1140006be33SJames Wright        Returns:
1150006be33SJames Wright            Optional[str]: Skip reason, or `None` if unexpeced error
1160006be33SJames Wright        """
1170006be33SJames Wright        if 'OCCA backend failed to use' in stderr:
1180006be33SJames Wright            return f'OCCA mode not supported'
1190006be33SJames Wright        elif 'Backend does not implement' in stderr:
1200006be33SJames Wright            return f'Backend does not implement'
1210006be33SJames Wright        elif 'Can only provide HOST memory for this backend' in stderr:
1220006be33SJames Wright            return f'Device memory not supported'
1230006be33SJames Wright        elif 'Can only set HOST memory for this backend' in stderr:
1240006be33SJames Wright            return f'Device memory not supported'
1250006be33SJames Wright        elif 'Test not implemented in single precision' in stderr:
1260006be33SJames Wright            return f'Test not implemented in single precision'
1270006be33SJames Wright        elif 'No SYCL devices of the requested type are available' in stderr:
1280006be33SJames Wright            return f'SYCL device type not available'
1290006be33SJames Wright        elif 'You may need to add --download-ctetgen or --download-tetgen' in stderr:
1300006be33SJames Wright            return f'Tet mesh generator not installed for {test}, {spec.name}'
1310006be33SJames Wright        return None
1320006be33SJames Wright
1330006be33SJames Wright    def check_required_failure(self, test: str, spec: TestSpec, resource: str, stderr: str) -> Tuple[str, bool]:
1340006be33SJames Wright        """Check whether a test case is expected to fail and if it failed expectedly
1350006be33SJames Wright
1360006be33SJames Wright        Args:
1370006be33SJames Wright            test (str): Name of test
1380006be33SJames Wright            spec (TestSpec): Test case specification
1390006be33SJames Wright            resource (str): libCEED backend
1400006be33SJames Wright            stderr (str): Standard error output from test case execution
1410006be33SJames Wright
1420006be33SJames Wright        Returns:
1430006be33SJames Wright            tuple[str, bool]: Tuple of the expected failure string and whether it was present in `stderr`
1440006be33SJames Wright        """
1450006be33SJames Wright        test_id: str = test[:4]
1460006be33SJames Wright        fail_str: str = ''
1470006be33SJames Wright        if test_id in ['t006', 't007']:
1480006be33SJames Wright            fail_str = 'No suitable backend:'
1490006be33SJames Wright        elif test_id in ['t008']:
1500006be33SJames Wright            fail_str = 'Available backend resources:'
1510006be33SJames Wright        elif test_id in ['t110', 't111', 't112', 't113', 't114']:
1520006be33SJames Wright            fail_str = 'Cannot grant CeedVector array access'
1530006be33SJames Wright        elif test_id in ['t115']:
1540006be33SJames Wright            fail_str = 'Cannot grant CeedVector read-only array access, the access lock is already in use'
1550006be33SJames Wright        elif test_id in ['t116']:
1560006be33SJames Wright            fail_str = 'Cannot destroy CeedVector, the writable access lock is in use'
1570006be33SJames Wright        elif test_id in ['t117']:
1580006be33SJames Wright            fail_str = 'Cannot restore CeedVector array access, access was not granted'
1590006be33SJames Wright        elif test_id in ['t118']:
1600006be33SJames Wright            fail_str = 'Cannot sync CeedVector, the access lock is already in use'
1610006be33SJames Wright        elif test_id in ['t215']:
1620006be33SJames Wright            fail_str = 'Cannot destroy CeedElemRestriction, a process has read access to the offset data'
1630006be33SJames Wright        elif test_id in ['t303']:
1640006be33SJames Wright            fail_str = 'Length of input/output vectors incompatible with basis dimensions'
1650006be33SJames Wright        elif test_id in ['t408']:
1660006be33SJames Wright            fail_str = 'CeedQFunctionContextGetData(): Cannot grant CeedQFunctionContext data access, a process has read access'
1670006be33SJames Wright        elif test_id in ['t409'] and contains_any(resource, ['memcheck']):
1680006be33SJames Wright            fail_str = 'Context data changed while accessed in read-only mode'
1690006be33SJames Wright
1700006be33SJames Wright        return fail_str, fail_str in stderr
1710006be33SJames Wright
1720006be33SJames Wright    def check_allowed_stdout(self, test: str) -> bool:
1730006be33SJames Wright        """Check whether a test is allowed to print console output
1740006be33SJames Wright
1750006be33SJames Wright        Args:
1760006be33SJames Wright            test (str): Name of test
1770006be33SJames Wright
1780006be33SJames Wright        Returns:
1790006be33SJames Wright            bool: True if the test is allowed to print console output
1800006be33SJames Wright        """
1810006be33SJames Wright        return test[:4] in ['t003']
1820006be33SJames Wright
1830006be33SJames Wright
1840006be33SJames Wrightif __name__ == '__main__':
1850006be33SJames Wright    args = create_argparser().parse_args()
1860006be33SJames Wright
1870006be33SJames Wright    # run tests
1880006be33SJames Wright    if 'smartsim' in args.test:
1890006be33SJames Wright        has_smartsim: bool = args.smartredis_dir and Path(args.smartredis_dir).is_dir()
1900006be33SJames Wright        test_cases = []
1910006be33SJames Wright
1920006be33SJames Wright        if args.mode is RunMode.TAP:
1930006be33SJames Wright            print(f'1..1')
1940006be33SJames Wright        if has_smartsim:
1950006be33SJames Wright            from smartsim_regression_framework import SmartSimTest
1960006be33SJames Wright
197aa34f9e7SJames Wright            test_framework = SmartSimTest(Path(__file__).parent / 'smartsim_test_dir')
1980006be33SJames Wright            test_framework.setup()
1990006be33SJames Wright
2000006be33SJames Wright            is_new_subtest = True
2010006be33SJames Wright            subtest_ok = True
2020006be33SJames Wright            for i, backend in enumerate(args.ceed_backends):
2030006be33SJames Wright                test_cases.append(test_framework.test_junit(backend))
2040006be33SJames Wright                if is_new_subtest and args.mode == RunMode.TAP:
2050006be33SJames Wright                    is_new_subtest = False
2060006be33SJames Wright                    print(f'# Subtest: {test_cases[0].category}')
2070006be33SJames Wright                    print(f'    1..{len(args.ceed_backends)}')
2080006be33SJames Wright                print(test_case_output_string(test_cases[i], TestSpec("SmartSim Tests"), args.mode, backend, '', i))
2090006be33SJames Wright            if args.mode == RunMode.TAP:
2100006be33SJames Wright                print(f'{"" if subtest_ok else "not "}ok 1 - {test_cases[0].category}')
2110006be33SJames Wright            test_framework.teardown()
2120006be33SJames Wright        elif args.mode is RunMode.TAP:
2130006be33SJames Wright            print(f'ok 1 - # SKIP SmartSim not installed')
2140006be33SJames Wright        result: TestSuite = TestSuite('SmartSim Tests', test_cases)
2150006be33SJames Wright    else:
2160006be33SJames Wright        result: TestSuite = run_tests(
2170006be33SJames Wright            args.test,
2180006be33SJames Wright            args.ceed_backends,
2190006be33SJames Wright            args.mode,
2200006be33SJames Wright            args.nproc,
2210006be33SJames Wright            CeedSuiteSpec(args.has_torch),
2220006be33SJames Wright            args.pool_size)
2230006be33SJames Wright
2240006be33SJames Wright    # write output and check for failures
2250006be33SJames Wright    if args.mode is RunMode.JUNIT:
2260006be33SJames Wright        write_junit_xml(result, args.output, args.junit_batch)
2270006be33SJames Wright        if has_failures(result):
2280006be33SJames Wright            sys.exit(1)
229