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