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