xref: /libCEED/tests/junit.py (revision 3d94f746edeb9e950d1b846371e33c33d610bdbc)
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
8*3d94f746Srezgarshakeri
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
24*3d94f746Srezgarshakeri
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
43*3d94f746Srezgarshakeri
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
50*3d94f746Srezgarshakeri
51bdb0bdbbSJed Browndef check_required_failure(case, stderr, required):
52bdb0bdbbSJed Brown    if required in stderr:
53bdb0bdbbSJed Brown        case.status = 'fails with required: {}'.format(required)
54bdb0bdbbSJed Brown    else:
55bdb0bdbbSJed Brown        case.add_failure_info('required: {}'.format(required))
56bdb0bdbbSJed Brown
57*3d94f746Srezgarshakeri
58b974e86eSJed Browndef contains_any(resource, substrings):
59b974e86eSJed Brown    return any((sub in resource for sub in substrings))
60b974e86eSJed Brown
61*3d94f746Srezgarshakeri
62b974e86eSJed Browndef skip_rule(test, resource):
63b974e86eSJed Brown    return any((
6412070e41Snbeams        test.startswith('fluids-') and contains_any(resource, ['occa']),
65ccaff030SJeremy L Thompson        test.startswith('solids-') and contains_any(resource, ['occa']),
665dc4928cSjeremylt        test.startswith('nek') and contains_any(resource, ['occa']),
671da99368SJeremy L Thompson        test.startswith('t507') and contains_any(resource, ['occa']),
6812070e41Snbeams        test.startswith('t318') and contains_any(resource, ['/gpu/cuda/ref']),
6912070e41Snbeams        test.startswith('t506') and contains_any(resource, ['/gpu/cuda/shared']),
70b974e86eSJed Brown        ))
71b974e86eSJed Brown
72*3d94f746Srezgarshakeri
738ec9d54bSJed Browndef run(test, backends):
748ec9d54bSJed Brown    import subprocess
758ec9d54bSJed Brown    import time
768ec9d54bSJed Brown    import difflib
775435e910SJed Brown    source = get_source(test)
78*3d94f746Srezgarshakeri    all_args = get_testargs(source)
79288c0443SJeremy L Thompson
80*3d94f746Srezgarshakeri    test_cases = []
812777116bSjeremylt    my_env = os.environ.copy()
82*3d94f746Srezgarshakeri    my_env["CEED_ERROR_HANDLER"] = 'exit'
83*3d94f746Srezgarshakeri    for args, name in all_args:
848ec9d54bSJed Brown        for ceed_resource in backends:
858ec9d54bSJed Brown            rargs = [os.path.join('build', test)] + args.copy()
868ec9d54bSJed Brown            rargs[rargs.index('{ceed_resource}')] = ceed_resource
87b974e86eSJed Brown
88b974e86eSJed Brown            if skip_rule(test, ceed_resource):
89b974e86eSJed Brown                case = TestCase('{} {}'.format(test, ceed_resource),
90b974e86eSJed Brown                                elapsed_sec=0,
9137e4ed59SJed Brown                                timestamp=time.strftime('%Y-%m-%d %H:%M:%S %Z', time.localtime()),
92b974e86eSJed Brown                                stdout='',
93b974e86eSJed Brown                                stderr='')
94b974e86eSJed Brown                case.add_skipped_info('Pre-run skip rule')
95b974e86eSJed Brown            else:
968ec9d54bSJed Brown                start = time.time()
978ec9d54bSJed Brown                proc = subprocess.run(rargs,
988ec9d54bSJed Brown                                      stdout=subprocess.PIPE,
992777116bSjeremylt                                      stderr=subprocess.PIPE,
1002777116bSjeremylt                                      env=my_env)
10173132ccbSJed Brown                proc.stdout = proc.stdout.decode('utf-8')
10273132ccbSJed Brown                proc.stderr = proc.stderr.decode('utf-8')
1038ec9d54bSJed Brown
104dc8efd83SLeila Ghaffari                case = TestCase('{} {} {}'.format(test, *name, ceed_resource),
1055435e910SJed Brown                                classname=os.path.dirname(source),
1068ec9d54bSJed Brown                                elapsed_sec=time.time() - start,
1078ec9d54bSJed Brown                                timestamp=time.strftime('%Y-%m-%d %H:%M:%S %Z', time.localtime(start)),
1088ec9d54bSJed Brown                                stdout=proc.stdout,
1098ec9d54bSJed Brown                                stderr=proc.stderr)
110288c0443SJeremy L Thompson                ref_stdout = os.path.join('tests/output', test + '.out')
111bdb0bdbbSJed Brown
112b974e86eSJed Brown            if not case.is_skipped() and proc.stderr:
1138ec9d54bSJed Brown                if 'OCCA backend failed to use' in proc.stderr:
1149bcbe8bdSJed Brown                    case.add_skipped_info('occa mode not supported {} {}'.format(test, ceed_resource))
1158ec9d54bSJed Brown                elif 'Backend does not implement' in proc.stderr:
1169bcbe8bdSJed Brown                    case.add_skipped_info('not implemented {} {}'.format(test, ceed_resource))
1179c774eddSJeremy L Thompson                elif 'Can only provide HOST memory for this backend' in proc.stderr:
118cbac262cSjeremylt                    case.add_skipped_info('device memory not supported {} {}'.format(test, ceed_resource))
11980a9ef05SNatalie Beams                elif 'Test not implemented in single precision' in proc.stderr:
12080a9ef05SNatalie Beams                    case.add_skipped_info('not implemented {} {}'.format(test, ceed_resource))
121bdb0bdbbSJed Brown
1228ec9d54bSJed Brown            if not case.is_skipped():
1232bbc7fe8Sjeremylt                if test[:4] in 't006 t007'.split():
1242bbc7fe8Sjeremylt                    check_required_failure(case, proc.stderr, 'No suitable backend:')
12522e44211Sjeremylt                if test[:4] in 't008'.split():
12692ee7d1cSjeremylt                    check_required_failure(case, proc.stderr, 'Available backend resources:')
1279f4513dfSjeremylt                if test[:4] in 't110 t111 t112 t113 t114'.split():
128bdb0bdbbSJed Brown                    check_required_failure(case, proc.stderr, 'Cannot grant CeedVector array access')
1299f4513dfSjeremylt                if test[:4] in 't115'.split():
1309f4513dfSjeremylt                    check_required_failure(case, proc.stderr, 'Cannot grant CeedVector read-only array access, the access lock is already in use')
1319f4513dfSjeremylt                if test[:4] in 't116'.split():
132187168c7SJeremy L Thompson                    check_required_failure(case, proc.stderr, 'Cannot destroy CeedVector, the writable access lock is in use')
1339f4513dfSjeremylt                if test[:4] in 't117'.split():
134bdb0bdbbSJed Brown                    check_required_failure(case, proc.stderr, 'Cannot restore CeedVector array access, access was not granted')
1359f4513dfSjeremylt                if test[:4] in 't118'.split():
1369f4513dfSjeremylt                    check_required_failure(case, proc.stderr, 'Cannot sync CeedVector, the access lock is already in use')
137430758c8SJeremy L Thompson                if test[:4] in 't215'.split():
138430758c8SJeremy L Thompson                    check_required_failure(case, proc.stderr, 'Cannot destroy CeedElemRestriction, a process has read access to the offset data')
13952bfb9bbSJeremy L Thompson                if test[:4] in 't303'.split():
140bdb0bdbbSJed Brown                    check_required_failure(case, proc.stderr, 'Length of input/output vectors incompatible with basis dimensions')
14128bfd0b7SJeremy L Thompson                if test[:4] in 't408'.split():
14228bfd0b7SJeremy L Thompson                    check_required_failure(case, proc.stderr, 'CeedQFunctionContextGetData(): Cannot grant CeedQFunctionContext data access, a process has read access')
1432ae780f2SJeremy L Thompson                if test[:4] in 't409'.split() and contains_any(ceed_resource, ['memcheck']):
1442ae780f2SJeremy L Thompson                    check_required_failure(case, proc.stderr, 'Context data changed while accessed in read-only mode')
145bdb0bdbbSJed Brown
146bdb0bdbbSJed Brown            if not case.is_skipped() and not case.status:
147bdb0bdbbSJed Brown                if proc.stderr:
148bdb0bdbbSJed Brown                    case.add_failure_info('stderr', proc.stderr)
149bdb0bdbbSJed Brown                elif proc.returncode != 0:
1509bcbe8bdSJed Brown                    case.add_error_info('returncode = {}'.format(proc.returncode))
1518ec9d54bSJed Brown                elif os.path.isfile(ref_stdout):
1528ec9d54bSJed Brown                    with open(ref_stdout) as ref:
1538ec9d54bSJed Brown                        diff = list(difflib.unified_diff(ref.readlines(),
1548ec9d54bSJed Brown                                                         proc.stdout.splitlines(keepends=True),
1558ec9d54bSJed Brown                                                         fromfile=ref_stdout,
1568ec9d54bSJed Brown                                                         tofile='New'))
1578ec9d54bSJed Brown                    if diff:
1588ec9d54bSJed Brown                        case.add_failure_info('stdout', output=''.join(diff))
1590a0da059Sjeremylt                elif proc.stdout and test[:4] not in 't003':
1608ec9d54bSJed Brown                    case.add_failure_info('stdout', output=proc.stdout)
161*3d94f746Srezgarshakeri            case.args = ' '.join(rargs)
162*3d94f746Srezgarshakeri            test_cases.append(case)
163*3d94f746Srezgarshakeri    return TestSuite(test, test_cases)
1648ec9d54bSJed Brown
1658ec9d54bSJed Brownif __name__ == '__main__':
1668ec9d54bSJed Brown    import argparse
167*3d94f746Srezgarshakeri    parser = argparse.ArgumentParser('Test runner with JUnit and TAP output')
168*3d94f746Srezgarshakeri    parser.add_argument('--mode', help='Output mode, JUnit or TAP', default="JUnit")
1698ec9d54bSJed Brown    parser.add_argument('--output', help='Output file to write test', default=None)
1708ec9d54bSJed Brown    parser.add_argument('--gather', help='Gather all *.junit files into XML', action='store_true')
1718ec9d54bSJed Brown    parser.add_argument('test', help='Test executable', nargs='?')
1728ec9d54bSJed Brown    args = parser.parse_args()
1738ec9d54bSJed Brown
1748ec9d54bSJed Brown    if args.gather:
1758ec9d54bSJed Brown        gather()
1768ec9d54bSJed Brown    else:
1778ec9d54bSJed Brown        backends = os.environ['BACKENDS'].split()
1788ec9d54bSJed Brown
1798ec9d54bSJed Brown        result = run(args.test, backends)
180add335c8SJeremy L Thompson
181*3d94f746Srezgarshakeri        if args.mode.lower() == "junit":
182add335c8SJeremy L Thompson            junit_batch = ''
183add335c8SJeremy L Thompson            try:
184add335c8SJeremy L Thompson                junit_batch = '-' + os.environ['JUNIT_BATCH']
185add335c8SJeremy L Thompson            except:
186add335c8SJeremy L Thompson                pass
187add335c8SJeremy L Thompson            output = (os.path.join('build', args.test + junit_batch + '.junit')
1888ec9d54bSJed Brown                      if args.output is None
1898ec9d54bSJed Brown                      else args.output)
190add335c8SJeremy L Thompson
1918ec9d54bSJed Brown            with open(output, 'w') as fd:
1928ec9d54bSJed Brown                TestSuite.to_file(fd, [result])
193*3d94f746Srezgarshakeri        elif args.mode.lower() == "tap":
194*3d94f746Srezgarshakeri            print('1..' + str(len(result.test_cases)))
195*3d94f746Srezgarshakeri            for i in range(len(result.test_cases)):
196*3d94f746Srezgarshakeri                test_case = result.test_cases[i]
197*3d94f746Srezgarshakeri                test_index = str(i + 1)
198*3d94f746Srezgarshakeri                print('# Test: ' + test_case.name.split(' ')[1])
199*3d94f746Srezgarshakeri                print('# $ ' + test_case.args)
200*3d94f746Srezgarshakeri                if test_case.is_error():
201*3d94f746Srezgarshakeri                    message = test_case.is_error() if isinstance(test_case.is_error(), str) else test_case.errors[0]['message']
202*3d94f746Srezgarshakeri                    print('not ok {} - ERROR: {}'.format(test_index, message.strip()))
203*3d94f746Srezgarshakeri                    print(test_case.errors[0]['output'].strip())
204*3d94f746Srezgarshakeri                elif test_case.is_failure():
205*3d94f746Srezgarshakeri                    message = test_case.is_failure() if isinstance(test_case.is_failure(), str) else test_case.failures[0]['message']
206*3d94f746Srezgarshakeri                    print('not ok {} - FAIL: {}'.format(test_index, message.strip()))
207*3d94f746Srezgarshakeri                    print(test_case.failures[0]['output'].strip())
208*3d94f746Srezgarshakeri                elif test_case.is_skipped():
209*3d94f746Srezgarshakeri                    message = test_case.is_skipped() if isinstance(test_case.is_skipped(), str) else test_case.skipped[0]['message']
210*3d94f746Srezgarshakeri                    print('ok {} - SKIP: {}'.format(test_index, message.strip()))
211*3d94f746Srezgarshakeri                else:
212*3d94f746Srezgarshakeri                    print('ok {} - PASS'.format(test_index))
213*3d94f746Srezgarshakeri        else:
214*3d94f746Srezgarshakeri            raise Exception("output mode not recognized")
215add335c8SJeremy L Thompson
2164d57a9fcSJed Brown        for t in result.test_cases:
2174d57a9fcSJed Brown            failures = len([c for c in result.test_cases if c.is_failure()])
2184d57a9fcSJed Brown            errors = len([c for c in result.test_cases if c.is_error()])
2194d57a9fcSJed Brown            if failures + errors > 0:
2204d57a9fcSJed Brown                sys.exit(1)
221