xref: /honee/tests/junit.py (revision 7fadd0e27f7bd032b2a6897b128f73ff0e277155)
1#!/usr/bin/env python3
2from junit_common import *
3
4
5def create_argparser() -> argparse.ArgumentParser:
6    """Creates argument parser to read command line arguments
7
8    Returns:
9        argparse.ArgumentParser: Created `ArgumentParser`
10    """
11    parser = argparse.ArgumentParser('Test runner with JUnit and TAP output')
12    parser.add_argument(
13        '-c',
14        '--ceed-backends',
15        type=str,
16        nargs='*',
17        default=['/cpu/self'],
18        help='libCEED backend to use with convergence tests')
19    parser.add_argument(
20        '-m',
21        '--mode',
22        type=RunMode,
23        action=CaseInsensitiveEnumAction,
24        help='Output mode, junit or tap',
25        default=RunMode.JUNIT)
26    parser.add_argument('-n', '--nproc', type=int, default=1, help='number of MPI processes')
27    parser.add_argument('-o', '--output', type=Optional[Path], default=None, help='Output file to write test')
28    parser.add_argument('-b', '--junit-batch', type=str, default='', help='Name of JUnit batch for output file')
29    parser.add_argument('-np', '--pool-size', type=int, default=1, help='Number of test cases to run in parallel')
30    parser.add_argument('-s', '--smartredis_dir', type=str, default='', help='path to SmartSim library, if present')
31    parser.add_argument('--has_torch', type=bool, default=False, help='Whether to build with torch')
32    parser.add_argument('test', help='Test executable', nargs='?')
33
34    return parser
35
36
37# Necessary functions for running tests
38class CeedSuiteSpec(SuiteSpec):
39    def __init__(self, has_torch: bool):
40        self.has_torch: bool = has_torch
41
42    def get_source_path(self, test: str) -> Path:
43        """Compute path to test source file
44
45        Args:
46            test (str): Name of test
47
48        Returns:
49            Path: Path to source file
50        """
51        if test.startswith('navierstokes'):
52            return (Path('examples') / 'navierstokes').with_suffix('.c')
53        else:
54            return (Path('tests') / test).with_suffix('.c')
55
56    # get path to executable
57    def get_run_path(self, test: str) -> Path:
58        """Compute path to built test executable file
59
60        Args:
61            test (str): Name of test
62
63        Returns:
64            Path: Path to test executable
65        """
66        return Path('build') / test
67
68    def get_output_path(self, test: str, output_file: str) -> Path:
69        """Compute path to expected output file
70
71        Args:
72            test (str): Name of test
73            output_file (str): File name of output file
74
75        Returns:
76            Path: Path to expected output file
77        """
78        return Path('tests') / 'output' / output_file
79
80    def check_pre_skip(self, test: str, spec: TestSpec, resource: str, nproc: int) -> Optional[str]:
81        """Check if a test case should be skipped prior to running, returning the reason for skipping
82
83        Args:
84            test (str): Name of test
85            spec (TestSpec): Test case specification
86            resource (str): libCEED backend
87            nproc (int): Number of MPI processes to use when running test case
88
89        Returns:
90            Optional[str]: Skip reason, or `None` if test case should not be skipped
91        """
92        if contains_any(resource, ['occa']) and startswith_any(
93                test, ['t4', 't5', 'ex', 'mfem', 'nek', 'petsc', 'fluids', 'solids']):
94            return 'OCCA mode not supported'
95        if test.startswith('t318') and contains_any(resource, ['/gpu/cuda/ref']):
96            return 'CUDA ref backend not supported'
97        if test.startswith('t506') and contains_any(resource, ['/gpu/cuda/shared']):
98            return 'CUDA shared backend not supported'
99        for condition in spec.only:
100            if (condition == 'cpu') and ('gpu' in resource):
101                return 'CPU only test with GPU backend'
102            if condition == 'torch' and not self.has_torch:
103                return 'PyTorch only test without USE_TORCH=1'
104
105    def check_post_skip(self, test: str, spec: TestSpec, resource: str, stderr: str) -> Optional[str]:
106        """Check if a test case should be allowed to fail, based on its stderr output
107
108        Args:
109            test (str): Name of test
110            spec (TestSpec): Test case specification
111            resource (str): libCEED backend
112            stderr (str): Standard error output from test case execution
113
114        Returns:
115            Optional[str]: Skip reason, or `None` if unexpeced error
116        """
117        if 'OCCA backend failed to use' in stderr:
118            return f'OCCA mode not supported'
119        elif 'Backend does not implement' in stderr:
120            return f'Backend does not implement'
121        elif 'Can only provide HOST memory for this backend' in stderr:
122            return f'Device memory not supported'
123        elif 'Can only set HOST memory for this backend' in stderr:
124            return f'Device memory not supported'
125        elif 'Test not implemented in single precision' in stderr:
126            return f'Test not implemented in single precision'
127        elif 'No SYCL devices of the requested type are available' in stderr:
128            return f'SYCL device type not available'
129        elif 'You may need to add --download-ctetgen or --download-tetgen' in stderr:
130            return f'Tet mesh generator not installed for {test}, {spec.name}'
131        return None
132
133    def check_required_failure(self, test: str, spec: TestSpec, resource: str, stderr: str) -> Tuple[str, bool]:
134        """Check whether a test case is expected to fail and if it failed expectedly
135
136        Args:
137            test (str): Name of test
138            spec (TestSpec): Test case specification
139            resource (str): libCEED backend
140            stderr (str): Standard error output from test case execution
141
142        Returns:
143            tuple[str, bool]: Tuple of the expected failure string and whether it was present in `stderr`
144        """
145        test_id: str = test[:4]
146        fail_str: str = ''
147        if test_id in ['t006', 't007']:
148            fail_str = 'No suitable backend:'
149        elif test_id in ['t008']:
150            fail_str = 'Available backend resources:'
151        elif test_id in ['t110', 't111', 't112', 't113', 't114']:
152            fail_str = 'Cannot grant CeedVector array access'
153        elif test_id in ['t115']:
154            fail_str = 'Cannot grant CeedVector read-only array access, the access lock is already in use'
155        elif test_id in ['t116']:
156            fail_str = 'Cannot destroy CeedVector, the writable access lock is in use'
157        elif test_id in ['t117']:
158            fail_str = 'Cannot restore CeedVector array access, access was not granted'
159        elif test_id in ['t118']:
160            fail_str = 'Cannot sync CeedVector, the access lock is already in use'
161        elif test_id in ['t215']:
162            fail_str = 'Cannot destroy CeedElemRestriction, a process has read access to the offset data'
163        elif test_id in ['t303']:
164            fail_str = 'Length of input/output vectors incompatible with basis dimensions'
165        elif test_id in ['t408']:
166            fail_str = 'CeedQFunctionContextGetData(): Cannot grant CeedQFunctionContext data access, a process has read access'
167        elif test_id in ['t409'] and contains_any(resource, ['memcheck']):
168            fail_str = 'Context data changed while accessed in read-only mode'
169
170        return fail_str, fail_str in stderr
171
172    def check_allowed_stdout(self, test: str) -> bool:
173        """Check whether a test is allowed to print console output
174
175        Args:
176            test (str): Name of test
177
178        Returns:
179            bool: True if the test is allowed to print console output
180        """
181        return test[:4] in ['t003']
182
183
184if __name__ == '__main__':
185    args = create_argparser().parse_args()
186
187    # run tests
188    if 'smartsim' in args.test:
189        has_smartsim: bool = args.smartredis_dir and Path(args.smartredis_dir).is_dir()
190        test_cases = []
191
192        if args.mode is RunMode.TAP:
193            print(f'1..1')
194        if has_smartsim:
195            from smartsim_regression_framework import SmartSimTest
196
197            test_framework = SmartSimTest(Path(__file__).parent / 'smartsim_test_dir')
198            test_framework.setup()
199
200            is_new_subtest = True
201            subtest_ok = True
202            for i, backend in enumerate(args.ceed_backends):
203                test_cases.append(test_framework.test_junit(backend))
204                if is_new_subtest and args.mode == RunMode.TAP:
205                    is_new_subtest = False
206                    print(f'# Subtest: {test_cases[0].category}')
207                    print(f'    1..{len(args.ceed_backends)}')
208                print(test_case_output_string(test_cases[i], TestSpec("SmartSim Tests"), args.mode, backend, '', i))
209            if args.mode == RunMode.TAP:
210                print(f'{"" if subtest_ok else "not "}ok 1 - {test_cases[0].category}')
211            test_framework.teardown()
212        elif args.mode is RunMode.TAP:
213            print(f'ok 1 - # SKIP SmartSim not installed')
214        result: TestSuite = TestSuite('SmartSim Tests', test_cases)
215    else:
216        result: TestSuite = run_tests(
217            args.test,
218            args.ceed_backends,
219            args.mode,
220            args.nproc,
221            CeedSuiteSpec(args.has_torch),
222            args.pool_size)
223
224    # write output and check for failures
225    if args.mode is RunMode.JUNIT:
226        write_junit_xml(result, args.output, args.junit_batch)
227        if has_failures(result):
228            sys.exit(1)
229