xref: /libCEED/tests/junit.py (revision 9647a07ed4cccf5520ee61cfc49faed91542e405)
1#!/usr/bin/env python3
2
3import os
4import sys
5sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), 'junit-xml')))
6from junit_xml import TestCase, TestSuite
7
8def parse_testargs(file):
9    if os.path.splitext(file)[1] in ['.c', '.cpp']:
10        return sum([[line.split()[1:]] for line in open(file).readlines()
11                    if line.startswith('//TESTARGS')], [])
12    elif os.path.splitext(file)[1] == '.usr':
13        return sum([[line.split()[2:]] for line in open(file).readlines()
14                    if line.startswith('C TESTARGS')])
15    raise RuntimeError('Unrecognized extension for file: {}'.format(file))
16
17def get_source(test):
18    if test.startswith('petsc-'):
19        return os.path.join('examples', 'petsc', test[6:] + '.c')
20    elif test.startswith('mfem-'):
21        return os.path.join('examples', 'mfem', test[5:] + '.cpp')
22    elif test.startswith('nek-'):
23        return os.path.join('examples', 'nek', 'bps', test[4:] + '.usr')
24    elif test.startswith('fluids-'):
25        return os.path.join('examples', 'fluids', test[7:] + '.c')
26    elif test.startswith('solids-'):
27        return os.path.join('examples', 'solids', test[7:] + '.c')
28    elif test.startswith('ex'):
29        return os.path.join('examples', 'ceed', test + '.c')
30
31def get_testargs(test):
32    source = get_source(test)
33    if source is None:
34        return [['{ceed_resource}']]
35    return parse_testargs(source)
36
37def check_required_failure(case, stderr, required):
38    if required in stderr:
39        case.status = 'fails with required: {}'.format(required)
40    else:
41        case.add_failure_info('required: {}'.format(required))
42
43def contains_any(resource, substrings):
44    return any((sub in resource for sub in substrings))
45
46def skip_rule(test, resource):
47    return any((
48        test.startswith('fluids-') and contains_any(resource, ['occa', 'gpu']) and not contains_any(resource, ['/gpu/cuda/gen']),
49        test.startswith('solids-') and contains_any(resource, ['occa']),
50        test.startswith('petsc-multigrid') and contains_any(resource, ['occa']),
51        test.startswith('t507') and contains_any(resource, ['occa']),
52        ))
53
54def run(test, backends):
55    import subprocess
56    import time
57    import difflib
58    allargs = get_testargs(test)
59
60    testcases = []
61    for args in allargs:
62        for ceed_resource in backends:
63            rargs = [os.path.join('build', test)] + args.copy()
64            rargs[rargs.index('{ceed_resource}')] = ceed_resource
65
66            if skip_rule(test, ceed_resource):
67                case = TestCase('{} {}'.format(test, ceed_resource),
68                                elapsed_sec=0,
69                                timestamp=time.strftime('%Y-%m-%d %H:%M:%S %Z', time.localtime(start)),
70                                stdout='',
71                                stderr='')
72                case.add_skipped_info('Pre-run skip rule')
73            else:
74                start = time.time()
75                proc = subprocess.run(rargs,
76                                      stdout=subprocess.PIPE,
77                                      stderr=subprocess.PIPE)
78                proc.stdout = proc.stdout.decode('utf-8')
79                proc.stderr = proc.stderr.decode('utf-8')
80
81                case = TestCase('{} {}'.format(test, ceed_resource),
82                                elapsed_sec=time.time()-start,
83                                timestamp=time.strftime('%Y-%m-%d %H:%M:%S %Z', time.localtime(start)),
84                                stdout=proc.stdout,
85                                stderr=proc.stderr)
86                ref_stdout = os.path.join('tests/output', test + '.out')
87
88            if not case.is_skipped() and proc.stderr:
89                if 'OCCA backend failed to use' in proc.stderr:
90                    case.add_skipped_info('occa mode not supported {} {}'.format(test, ceed_resource))
91                elif 'Backend does not implement' in proc.stderr:
92                    case.add_skipped_info('not implemented {} {}'.format(test, ceed_resource))
93                elif 'Can only provide to HOST memory' in proc.stderr:
94                    case.add_skipped_info('device memory not supported {} {}'.format(test, ceed_resource))
95
96            if not case.is_skipped():
97                if test[:4] in 't110 t111 t112 t113 t114'.split():
98                    check_required_failure(case, proc.stderr, 'Cannot grant CeedVector array access')
99                if test[:4] in 't115'.split():
100                    check_required_failure(case, proc.stderr, 'Cannot grant CeedVector read-only array access, the access lock is already in use')
101                if test[:4] in 't116'.split():
102                    check_required_failure(case, proc.stderr, 'Cannot destroy CeedVector, the access lock is in use')
103                if test[:4] in 't117'.split():
104                    check_required_failure(case, proc.stderr, 'Cannot restore CeedVector array access, access was not granted')
105                if test[:4] in 't118'.split():
106                    check_required_failure(case, proc.stderr, 'Cannot sync CeedVector, the access lock is already in use')
107                if test[:4] in 't215'.split():
108                    check_required_failure(case, proc.stderr, 'Cannot destroy CeedElemRestriction, a process has read access to the offset data')
109                if test[:4] in 't303'.split():
110                    check_required_failure(case, proc.stderr, 'Length of input/output vectors incompatible with basis dimensions')
111
112            if not case.is_skipped() and not case.status:
113                if proc.stderr:
114                    case.add_failure_info('stderr', proc.stderr)
115                elif proc.returncode != 0:
116                    case.add_error_info('returncode = {}'.format(proc.returncode))
117                elif os.path.isfile(ref_stdout):
118                    with open(ref_stdout) as ref:
119                        diff = list(difflib.unified_diff(ref.readlines(),
120                                                         proc.stdout.splitlines(keepends=True),
121                                                         fromfile=ref_stdout,
122                                                         tofile='New'))
123                    if diff:
124                        case.add_failure_info('stdout', output=''.join(diff))
125                elif proc.stdout and test[:4] not in 't003':
126                    case.add_failure_info('stdout', output=proc.stdout)
127            testcases.append(case)
128        return TestSuite(test, testcases)
129
130if __name__ == '__main__':
131    import argparse
132    parser = argparse.ArgumentParser('Test runner with JUnit output')
133    parser.add_argument('--output', help='Output file to write test', default=None)
134    parser.add_argument('--gather', help='Gather all *.junit files into XML', action='store_true')
135    parser.add_argument('test', help='Test executable', nargs='?')
136    args = parser.parse_args()
137
138    if args.gather:
139        gather()
140    else:
141        backends = os.environ['BACKENDS'].split()
142
143        result = run(args.test, backends)
144        output = (os.path.join('build', args.test + '.junit')
145                  if args.output is None
146                  else args.output)
147        with open(output, 'w') as fd:
148            TestSuite.to_file(fd, [result])
149        for t in result.test_cases:
150            failures = len([c for c in result.test_cases if c.is_failure()])
151            errors = len([c for c in result.test_cases if c.is_error()])
152            if failures + errors > 0:
153                sys.exit(1)
154