xref: /libCEED/tests/junit.py (revision 4a2fcf2f23f434bb0916c52d9de7e8090662285d)
18ec9d54bSJed Brown#!/usr/bin/env python3
28ec9d54bSJed Brown
38ec9d54bSJed Brownimport os
48ec9d54bSJed Brownimport sys
58ec9d54bSJed Brownsys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), 'junit-xml')))
68ec9d54bSJed Brownfrom junit_xml import TestCase, TestSuite
78ec9d54bSJed Brown
83d94f746Srezgarshakeri
98ec9d54bSJed Browndef parse_testargs(file):
108ec9d54bSJed Brown    if os.path.splitext(file)[1] in ['.c', '.cpp']:
11dc8efd83SLeila Ghaffari        return sum([[[line.split()[1:], [line.split()[0].strip('//TESTARGS(name=').strip(')')]]]
12dc8efd83SLeila Ghaffari                    for line in open(file).readlines()
138ec9d54bSJed Brown                    if line.startswith('//TESTARGS')], [])
148ec9d54bSJed Brown    elif os.path.splitext(file)[1] == '.usr':
15dc8efd83SLeila Ghaffari        return sum([[[line.split()[1:], [line.split()[0].strip('C_TESTARGS(name=').strip(')')]]]
16dc8efd83SLeila Ghaffari                    for line in open(file).readlines()
171b685ca3Sjeth8984                    if line.startswith('C_TESTARGS')], [])
185435e910SJed Brown    elif os.path.splitext(file)[1] in ['.f90']:
195435e910SJed Brown        return sum([[[line.split()[1:], [line.split()[0].strip('C_TESTARGS(name=').strip(')')]]]
205435e910SJed Brown                    for line in open(file).readlines()
215435e910SJed Brown                    if line.startswith('! TESTARGS')], [])
229bcbe8bdSJed Brown    raise RuntimeError('Unrecognized extension for file: {}'.format(file))
238ec9d54bSJed Brown
243d94f746Srezgarshakeri
258ec9d54bSJed Browndef get_source(test):
268ec9d54bSJed Brown    if test.startswith('petsc-'):
278ec9d54bSJed Brown        return os.path.join('examples', 'petsc', test[6:] + '.c')
288ec9d54bSJed Brown    elif test.startswith('mfem-'):
298ec9d54bSJed Brown        return os.path.join('examples', 'mfem', test[5:] + '.cpp')
308ec9d54bSJed Brown    elif test.startswith('nek-'):
3186a4271fSThilina Rathnayake        return os.path.join('examples', 'nek', 'bps', test[4:] + '.usr')
32ccaff030SJeremy L Thompson    elif test.startswith('fluids-'):
33ccaff030SJeremy L Thompson        return os.path.join('examples', 'fluids', test[7:] + '.c')
34ccaff030SJeremy L Thompson    elif test.startswith('solids-'):
35ccaff030SJeremy L Thompson        return os.path.join('examples', 'solids', test[7:] + '.c')
368ec9d54bSJed Brown    elif test.startswith('ex'):
378ec9d54bSJed Brown        return os.path.join('examples', 'ceed', test + '.c')
385435e910SJed Brown    elif test.endswith('-f'):
395435e910SJed Brown        return os.path.join('tests', test + '.f90')
405435e910SJed Brown    else:
415435e910SJed Brown        return os.path.join('tests', test + '.c')
428ec9d54bSJed Brown
433d94f746Srezgarshakeri
445435e910SJed Browndef get_testargs(source):
455435e910SJed Brown    args = parse_testargs(source)
465435e910SJed Brown    if not args:
475435e910SJed Brown        return [(['{ceed_resource}'], [''])]
485435e910SJed Brown    return args
498ec9d54bSJed Brown
503d94f746Srezgarshakeri
51*4a2fcf2fSJeremy L Thompsondef check_required_failure(test_case, stderr, required):
52bdb0bdbbSJed Brown    if required in stderr:
53*4a2fcf2fSJeremy L Thompson        test_case.status = 'fails with required: {}'.format(required)
54bdb0bdbbSJed Brown    else:
55*4a2fcf2fSJeremy L Thompson        test_case.add_failure_info('required: {}'.format(required))
56bdb0bdbbSJed Brown
573d94f746Srezgarshakeri
58b974e86eSJed Browndef contains_any(resource, substrings):
59b974e86eSJed Brown    return any((sub in resource for sub in substrings))
60b974e86eSJed Brown
613d94f746Srezgarshakeri
62b974e86eSJed Browndef skip_rule(test, resource):
63b974e86eSJed Brown    return any((
640be03a92SJeremy L Thompson        test.startswith('t4') and contains_any(resource, ['occa']),
650be03a92SJeremy L Thompson        test.startswith('t5') and contains_any(resource, ['occa']),
660be03a92SJeremy L Thompson        test.startswith('ex') and contains_any(resource, ['occa']),
670be03a92SJeremy L Thompson        test.startswith('mfem') and contains_any(resource, ['occa']),
680be03a92SJeremy L Thompson        test.startswith('nek') and contains_any(resource, ['occa']),
690be03a92SJeremy L Thompson        test.startswith('petsc-') and contains_any(resource, ['occa']),
7012070e41Snbeams        test.startswith('fluids-') and contains_any(resource, ['occa']),
71ccaff030SJeremy L Thompson        test.startswith('solids-') and contains_any(resource, ['occa']),
7212070e41Snbeams        test.startswith('t318') and contains_any(resource, ['/gpu/cuda/ref']),
7312070e41Snbeams        test.startswith('t506') and contains_any(resource, ['/gpu/cuda/shared']),
74b974e86eSJed Brown        ))
75b974e86eSJed Brown
763d94f746Srezgarshakeri
77*4a2fcf2fSJeremy L Thompsondef run(test, backends, mode):
788ec9d54bSJed Brown    import subprocess
798ec9d54bSJed Brown    import time
808ec9d54bSJed Brown    import difflib
815435e910SJed Brown    source = get_source(test)
823d94f746Srezgarshakeri    all_args = get_testargs(source)
83288c0443SJeremy L Thompson
84*4a2fcf2fSJeremy L Thompson    if mode.lower() == "tap":
85*4a2fcf2fSJeremy L Thompson        print('1..' + str(len(all_args) * len(backends)))
86*4a2fcf2fSJeremy L Thompson
873d94f746Srezgarshakeri    test_cases = []
882777116bSjeremylt    my_env = os.environ.copy()
893d94f746Srezgarshakeri    my_env["CEED_ERROR_HANDLER"] = 'exit'
90*4a2fcf2fSJeremy L Thompson    index = 1
913d94f746Srezgarshakeri    for args, name in all_args:
928ec9d54bSJed Brown        for ceed_resource in backends:
938ec9d54bSJed Brown            rargs = [os.path.join('build', test)] + args.copy()
948ec9d54bSJed Brown            rargs[rargs.index('{ceed_resource}')] = ceed_resource
95b974e86eSJed Brown
96*4a2fcf2fSJeremy L Thompson            # run test
97b974e86eSJed Brown            if skip_rule(test, ceed_resource):
98*4a2fcf2fSJeremy L Thompson                test_case = TestCase('{} {}'.format(test, ceed_resource),
99b974e86eSJed Brown                                     elapsed_sec=0,
10037e4ed59SJed Brown                                     timestamp=time.strftime('%Y-%m-%d %H:%M:%S %Z', time.localtime()),
101b974e86eSJed Brown                                     stdout='',
102b974e86eSJed Brown                                     stderr='')
103*4a2fcf2fSJeremy L Thompson                test_case.add_skipped_info('Pre-run skip rule')
104b974e86eSJed Brown            else:
1058ec9d54bSJed Brown                start = time.time()
1068ec9d54bSJed Brown                proc = subprocess.run(rargs,
1078ec9d54bSJed Brown                                      stdout=subprocess.PIPE,
1082777116bSjeremylt                                      stderr=subprocess.PIPE,
1092777116bSjeremylt                                      env=my_env)
11073132ccbSJed Brown                proc.stdout = proc.stdout.decode('utf-8')
11173132ccbSJed Brown                proc.stderr = proc.stderr.decode('utf-8')
1128ec9d54bSJed Brown
113*4a2fcf2fSJeremy L Thompson                test_case = TestCase('{} {} {}'.format(test, *name, ceed_resource),
1145435e910SJed Brown                                     classname=os.path.dirname(source),
1158ec9d54bSJed Brown                                     elapsed_sec=time.time() - start,
1168ec9d54bSJed Brown                                     timestamp=time.strftime('%Y-%m-%d %H:%M:%S %Z', time.localtime(start)),
1178ec9d54bSJed Brown                                     stdout=proc.stdout,
1188ec9d54bSJed Brown                                     stderr=proc.stderr)
119288c0443SJeremy L Thompson                ref_stdout = os.path.join('tests/output', test + '.out')
120bdb0bdbbSJed Brown
121*4a2fcf2fSJeremy L Thompson            # check for allowed errors
122*4a2fcf2fSJeremy L Thompson            if not test_case.is_skipped() and proc.stderr:
1238ec9d54bSJed Brown                if 'OCCA backend failed to use' in proc.stderr:
124*4a2fcf2fSJeremy L Thompson                    test_case.add_skipped_info('occa mode not supported {} {}'.format(test, ceed_resource))
1258ec9d54bSJed Brown                elif 'Backend does not implement' in proc.stderr:
126*4a2fcf2fSJeremy L Thompson                    test_case.add_skipped_info('not implemented {} {}'.format(test, ceed_resource))
1279c774eddSJeremy L Thompson                elif 'Can only provide HOST memory for this backend' in proc.stderr:
128*4a2fcf2fSJeremy L Thompson                    test_case.add_skipped_info('device memory not supported {} {}'.format(test, ceed_resource))
12980a9ef05SNatalie Beams                elif 'Test not implemented in single precision' in proc.stderr:
130*4a2fcf2fSJeremy L Thompson                    test_case.add_skipped_info('not implemented {} {}'.format(test, ceed_resource))
131bdb0bdbbSJed Brown
132*4a2fcf2fSJeremy L Thompson            # check required failures
133*4a2fcf2fSJeremy L Thompson            if not test_case.is_skipped():
1342bbc7fe8Sjeremylt                if test[:4] in 't006 t007'.split():
135*4a2fcf2fSJeremy L Thompson                    check_required_failure(test_case, proc.stderr, 'No suitable backend:')
13622e44211Sjeremylt                if test[:4] in 't008'.split():
137*4a2fcf2fSJeremy L Thompson                    check_required_failure(test_case, proc.stderr, 'Available backend resources:')
1389f4513dfSjeremylt                if test[:4] in 't110 t111 t112 t113 t114'.split():
139*4a2fcf2fSJeremy L Thompson                    check_required_failure(test_case, proc.stderr, 'Cannot grant CeedVector array access')
1409f4513dfSjeremylt                if test[:4] in 't115'.split():
141*4a2fcf2fSJeremy L Thompson                    check_required_failure(test_case, proc.stderr, 'Cannot grant CeedVector read-only array access, the access lock is already in use')
1429f4513dfSjeremylt                if test[:4] in 't116'.split():
143*4a2fcf2fSJeremy L Thompson                    check_required_failure(test_case, proc.stderr, 'Cannot destroy CeedVector, the writable access lock is in use')
1449f4513dfSjeremylt                if test[:4] in 't117'.split():
145*4a2fcf2fSJeremy L Thompson                    check_required_failure(test_case, proc.stderr, 'Cannot restore CeedVector array access, access was not granted')
1469f4513dfSjeremylt                if test[:4] in 't118'.split():
147*4a2fcf2fSJeremy L Thompson                    check_required_failure(test_case, proc.stderr, 'Cannot sync CeedVector, the access lock is already in use')
148430758c8SJeremy L Thompson                if test[:4] in 't215'.split():
149*4a2fcf2fSJeremy L Thompson                    check_required_failure(test_case, proc.stderr, 'Cannot destroy CeedElemRestriction, a process has read access to the offset data')
15052bfb9bbSJeremy L Thompson                if test[:4] in 't303'.split():
151*4a2fcf2fSJeremy L Thompson                    check_required_failure(test_case, proc.stderr, 'Length of input/output vectors incompatible with basis dimensions')
15228bfd0b7SJeremy L Thompson                if test[:4] in 't408'.split():
153*4a2fcf2fSJeremy L Thompson                    check_required_failure(test_case, proc.stderr, 'CeedQFunctionContextGetData(): Cannot grant CeedQFunctionContext data access, a process has read access')
1542ae780f2SJeremy L Thompson                if test[:4] in 't409'.split() and contains_any(ceed_resource, ['memcheck']):
155*4a2fcf2fSJeremy L Thompson                    check_required_failure(test_case, proc.stderr, 'Context data changed while accessed in read-only mode')
156bdb0bdbbSJed Brown
157*4a2fcf2fSJeremy L Thompson            # classify other results
158*4a2fcf2fSJeremy L Thompson            if not test_case.is_skipped() and not test_case.status:
159bdb0bdbbSJed Brown                if proc.stderr:
160*4a2fcf2fSJeremy L Thompson                    test_case.add_failure_info('stderr', proc.stderr)
161bdb0bdbbSJed Brown                elif proc.returncode != 0:
162*4a2fcf2fSJeremy L Thompson                    test_case.add_error_info('returncode = {}'.format(proc.returncode))
1638ec9d54bSJed Brown                elif os.path.isfile(ref_stdout):
1648ec9d54bSJed Brown                    with open(ref_stdout) as ref:
1658ec9d54bSJed Brown                        diff = list(difflib.unified_diff(ref.readlines(),
1668ec9d54bSJed Brown                                                         proc.stdout.splitlines(keepends=True),
1678ec9d54bSJed Brown                                                         fromfile=ref_stdout,
1688ec9d54bSJed Brown                                                         tofile='New'))
1698ec9d54bSJed Brown                    if diff:
170*4a2fcf2fSJeremy L Thompson                        test_case.add_failure_info('stdout', output=''.join(diff))
1710a0da059Sjeremylt                elif proc.stdout and test[:4] not in 't003':
172*4a2fcf2fSJeremy L Thompson                    test_case.add_failure_info('stdout', output=proc.stdout)
173*4a2fcf2fSJeremy L Thompson
174*4a2fcf2fSJeremy L Thompson            # store result
175*4a2fcf2fSJeremy L Thompson            test_case.args = ' '.join(rargs)
176*4a2fcf2fSJeremy L Thompson            test_cases.append(test_case)
177*4a2fcf2fSJeremy L Thompson
178*4a2fcf2fSJeremy L Thompson            if mode.lower() == "tap":
179*4a2fcf2fSJeremy L Thompson                # print incremental output if TAP mode
180*4a2fcf2fSJeremy L Thompson                print('# Test: {}'.format(test_case.name.split(' ')[1]))
181*4a2fcf2fSJeremy L Thompson                print('# $ {}'.format(test_case.args))
182*4a2fcf2fSJeremy L Thompson                if test_case.is_error():
183*4a2fcf2fSJeremy L Thompson                    print('not ok {} - ERROR: {}'.format(index, test_case.errors[0]['message'].strip()))
184*4a2fcf2fSJeremy L Thompson                    print(test_case.errors[0]['output'].strip())
185*4a2fcf2fSJeremy L Thompson                elif test_case.is_failure():
186*4a2fcf2fSJeremy L Thompson                    print('not ok {} - FAIL: {}'.format(index, test_case.failures[0]['message'].strip()))
187*4a2fcf2fSJeremy L Thompson                    print(test_case.failures[0]['output'].strip())
188*4a2fcf2fSJeremy L Thompson                elif test_case.is_skipped():
189*4a2fcf2fSJeremy L Thompson                    print('ok {} - SKIP: {}'.format(index, test_case.skipped[0]['message'].strip()))
190*4a2fcf2fSJeremy L Thompson                else:
191*4a2fcf2fSJeremy L Thompson                    print('ok {} - PASS'.format(index))
192*4a2fcf2fSJeremy L Thompson                sys.stdout.flush()
193*4a2fcf2fSJeremy L Thompson            else:
194*4a2fcf2fSJeremy L Thompson                # print error or failure information if JUNIT mode
195*4a2fcf2fSJeremy L Thompson                if test_case.is_error():
196*4a2fcf2fSJeremy L Thompson                    print('Test: {} {}'.format(test_case.name.split(' ')[0], test_case.name.split(' ')[1]))
197*4a2fcf2fSJeremy L Thompson                    print('ERROR: {}'.format(test_case.errors[0]['message'].strip()))
198*4a2fcf2fSJeremy L Thompson                    print(test_case.errors[0]['output'].strip())
199*4a2fcf2fSJeremy L Thompson                elif test_case.is_failure():
200*4a2fcf2fSJeremy L Thompson                    print('Test: {} {}'.format(test_case.name.split(' ')[0], test_case.name.split(' ')[1]))
201*4a2fcf2fSJeremy L Thompson                    print('FAIL: {}'.format(test_case.failures[0]['message'].strip()))
202*4a2fcf2fSJeremy L Thompson                    print(test_case.failures[0]['output'].strip())
203*4a2fcf2fSJeremy L Thompson                sys.stdout.flush()
204*4a2fcf2fSJeremy L Thompson            index += 1
205*4a2fcf2fSJeremy L Thompson
2063d94f746Srezgarshakeri    return TestSuite(test, test_cases)
2078ec9d54bSJed Brown
2088ec9d54bSJed Brownif __name__ == '__main__':
2098ec9d54bSJed Brown    import argparse
2103d94f746Srezgarshakeri    parser = argparse.ArgumentParser('Test runner with JUnit and TAP output')
2113d94f746Srezgarshakeri    parser.add_argument('--mode', help='Output mode, JUnit or TAP', default="JUnit")
2128ec9d54bSJed Brown    parser.add_argument('--output', help='Output file to write test', default=None)
2138ec9d54bSJed Brown    parser.add_argument('--gather', help='Gather all *.junit files into XML', action='store_true')
2148ec9d54bSJed Brown    parser.add_argument('test', help='Test executable', nargs='?')
2158ec9d54bSJed Brown    args = parser.parse_args()
2168ec9d54bSJed Brown
2178ec9d54bSJed Brown    if args.gather:
2188ec9d54bSJed Brown        gather()
2198ec9d54bSJed Brown    else:
2208ec9d54bSJed Brown        backends = os.environ['BACKENDS'].split()
2218ec9d54bSJed Brown
222*4a2fcf2fSJeremy L Thompson        # run tests
223*4a2fcf2fSJeremy L Thompson        result = run(args.test, backends, args.mode)
224add335c8SJeremy L Thompson
225*4a2fcf2fSJeremy L Thompson        # build output
2263d94f746Srezgarshakeri        if args.mode.lower() == "junit":
227add335c8SJeremy L Thompson            junit_batch = ''
228add335c8SJeremy L Thompson            try:
229add335c8SJeremy L Thompson                junit_batch = '-' + os.environ['JUNIT_BATCH']
230add335c8SJeremy L Thompson            except:
231add335c8SJeremy L Thompson                pass
232add335c8SJeremy L Thompson            output = (os.path.join('build', args.test + junit_batch + '.junit')
2338ec9d54bSJed Brown                      if args.output is None
2348ec9d54bSJed Brown                      else args.output)
235add335c8SJeremy L Thompson
2368ec9d54bSJed Brown            with open(output, 'w') as fd:
2378ec9d54bSJed Brown                TestSuite.to_file(fd, [result])
238*4a2fcf2fSJeremy L Thompson        elif args.mode.lower() != "tap":
2393d94f746Srezgarshakeri            raise Exception("output mode not recognized")
240add335c8SJeremy L Thompson
241*4a2fcf2fSJeremy L Thompson        # check return code
2424d57a9fcSJed Brown        for t in result.test_cases:
2434d57a9fcSJed Brown            failures = len([c for c in result.test_cases if c.is_failure()])
2444d57a9fcSJed Brown            errors = len([c for c in result.test_cases if c.is_error()])
24539656d8bSJeremy L Thompson            if failures + errors > 0 and args.mode.lower() != "tap":
2464d57a9fcSJed Brown                sys.exit(1)
247