xref: /libCEED/tests/junit.py (revision 0be03a92683d319639505fd4b3dce80b3bae318f)
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
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
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((
64*0be03a92SJeremy L Thompson        test.startswith('t4') and contains_any(resource, ['occa']),
65*0be03a92SJeremy L Thompson        test.startswith('t5') and contains_any(resource, ['occa']),
66*0be03a92SJeremy L Thompson        test.startswith('ex') and contains_any(resource, ['occa']),
67*0be03a92SJeremy L Thompson        test.startswith('mfem') and contains_any(resource, ['occa']),
68*0be03a92SJeremy L Thompson        test.startswith('nek') and contains_any(resource, ['occa']),
69*0be03a92SJeremy 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
778ec9d54bSJed Browndef run(test, backends):
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
843d94f746Srezgarshakeri    test_cases = []
852777116bSjeremylt    my_env = os.environ.copy()
863d94f746Srezgarshakeri    my_env["CEED_ERROR_HANDLER"] = 'exit'
873d94f746Srezgarshakeri    for args, name in all_args:
888ec9d54bSJed Brown        for ceed_resource in backends:
898ec9d54bSJed Brown            rargs = [os.path.join('build', test)] + args.copy()
908ec9d54bSJed Brown            rargs[rargs.index('{ceed_resource}')] = ceed_resource
91b974e86eSJed Brown
92b974e86eSJed Brown            if skip_rule(test, ceed_resource):
93b974e86eSJed Brown                case = TestCase('{} {}'.format(test, ceed_resource),
94b974e86eSJed Brown                                elapsed_sec=0,
9537e4ed59SJed Brown                                timestamp=time.strftime('%Y-%m-%d %H:%M:%S %Z', time.localtime()),
96b974e86eSJed Brown                                stdout='',
97b974e86eSJed Brown                                stderr='')
98b974e86eSJed Brown                case.add_skipped_info('Pre-run skip rule')
99b974e86eSJed Brown            else:
1008ec9d54bSJed Brown                start = time.time()
1018ec9d54bSJed Brown                proc = subprocess.run(rargs,
1028ec9d54bSJed Brown                                      stdout=subprocess.PIPE,
1032777116bSjeremylt                                      stderr=subprocess.PIPE,
1042777116bSjeremylt                                      env=my_env)
10573132ccbSJed Brown                proc.stdout = proc.stdout.decode('utf-8')
10673132ccbSJed Brown                proc.stderr = proc.stderr.decode('utf-8')
1078ec9d54bSJed Brown
108dc8efd83SLeila Ghaffari                case = TestCase('{} {} {}'.format(test, *name, ceed_resource),
1095435e910SJed Brown                                classname=os.path.dirname(source),
1108ec9d54bSJed Brown                                elapsed_sec=time.time() - start,
1118ec9d54bSJed Brown                                timestamp=time.strftime('%Y-%m-%d %H:%M:%S %Z', time.localtime(start)),
1128ec9d54bSJed Brown                                stdout=proc.stdout,
1138ec9d54bSJed Brown                                stderr=proc.stderr)
114288c0443SJeremy L Thompson                ref_stdout = os.path.join('tests/output', test + '.out')
115bdb0bdbbSJed Brown
116b974e86eSJed Brown            if not case.is_skipped() and proc.stderr:
1178ec9d54bSJed Brown                if 'OCCA backend failed to use' in proc.stderr:
1189bcbe8bdSJed Brown                    case.add_skipped_info('occa mode not supported {} {}'.format(test, ceed_resource))
1198ec9d54bSJed Brown                elif 'Backend does not implement' in proc.stderr:
1209bcbe8bdSJed Brown                    case.add_skipped_info('not implemented {} {}'.format(test, ceed_resource))
1219c774eddSJeremy L Thompson                elif 'Can only provide HOST memory for this backend' in proc.stderr:
122cbac262cSjeremylt                    case.add_skipped_info('device memory not supported {} {}'.format(test, ceed_resource))
12380a9ef05SNatalie Beams                elif 'Test not implemented in single precision' in proc.stderr:
12480a9ef05SNatalie Beams                    case.add_skipped_info('not implemented {} {}'.format(test, ceed_resource))
125bdb0bdbbSJed Brown
1268ec9d54bSJed Brown            if not case.is_skipped():
1272bbc7fe8Sjeremylt                if test[:4] in 't006 t007'.split():
1282bbc7fe8Sjeremylt                    check_required_failure(case, proc.stderr, 'No suitable backend:')
12922e44211Sjeremylt                if test[:4] in 't008'.split():
13092ee7d1cSjeremylt                    check_required_failure(case, proc.stderr, 'Available backend resources:')
1319f4513dfSjeremylt                if test[:4] in 't110 t111 t112 t113 t114'.split():
132bdb0bdbbSJed Brown                    check_required_failure(case, proc.stderr, 'Cannot grant CeedVector array access')
1339f4513dfSjeremylt                if test[:4] in 't115'.split():
1349f4513dfSjeremylt                    check_required_failure(case, proc.stderr, 'Cannot grant CeedVector read-only array access, the access lock is already in use')
1359f4513dfSjeremylt                if test[:4] in 't116'.split():
136187168c7SJeremy L Thompson                    check_required_failure(case, proc.stderr, 'Cannot destroy CeedVector, the writable access lock is in use')
1379f4513dfSjeremylt                if test[:4] in 't117'.split():
138bdb0bdbbSJed Brown                    check_required_failure(case, proc.stderr, 'Cannot restore CeedVector array access, access was not granted')
1399f4513dfSjeremylt                if test[:4] in 't118'.split():
1409f4513dfSjeremylt                    check_required_failure(case, proc.stderr, 'Cannot sync CeedVector, the access lock is already in use')
141430758c8SJeremy L Thompson                if test[:4] in 't215'.split():
142430758c8SJeremy L Thompson                    check_required_failure(case, proc.stderr, 'Cannot destroy CeedElemRestriction, a process has read access to the offset data')
14352bfb9bbSJeremy L Thompson                if test[:4] in 't303'.split():
144bdb0bdbbSJed Brown                    check_required_failure(case, proc.stderr, 'Length of input/output vectors incompatible with basis dimensions')
14528bfd0b7SJeremy L Thompson                if test[:4] in 't408'.split():
14628bfd0b7SJeremy L Thompson                    check_required_failure(case, proc.stderr, 'CeedQFunctionContextGetData(): Cannot grant CeedQFunctionContext data access, a process has read access')
1472ae780f2SJeremy L Thompson                if test[:4] in 't409'.split() and contains_any(ceed_resource, ['memcheck']):
1482ae780f2SJeremy L Thompson                    check_required_failure(case, proc.stderr, 'Context data changed while accessed in read-only mode')
149bdb0bdbbSJed Brown
150bdb0bdbbSJed Brown            if not case.is_skipped() and not case.status:
151bdb0bdbbSJed Brown                if proc.stderr:
152bdb0bdbbSJed Brown                    case.add_failure_info('stderr', proc.stderr)
153bdb0bdbbSJed Brown                elif proc.returncode != 0:
1549bcbe8bdSJed Brown                    case.add_error_info('returncode = {}'.format(proc.returncode))
1558ec9d54bSJed Brown                elif os.path.isfile(ref_stdout):
1568ec9d54bSJed Brown                    with open(ref_stdout) as ref:
1578ec9d54bSJed Brown                        diff = list(difflib.unified_diff(ref.readlines(),
1588ec9d54bSJed Brown                                                         proc.stdout.splitlines(keepends=True),
1598ec9d54bSJed Brown                                                         fromfile=ref_stdout,
1608ec9d54bSJed Brown                                                         tofile='New'))
1618ec9d54bSJed Brown                    if diff:
1628ec9d54bSJed Brown                        case.add_failure_info('stdout', output=''.join(diff))
1630a0da059Sjeremylt                elif proc.stdout and test[:4] not in 't003':
1648ec9d54bSJed Brown                    case.add_failure_info('stdout', output=proc.stdout)
1653d94f746Srezgarshakeri            case.args = ' '.join(rargs)
1663d94f746Srezgarshakeri            test_cases.append(case)
1673d94f746Srezgarshakeri    return TestSuite(test, test_cases)
1688ec9d54bSJed Brown
1698ec9d54bSJed Brownif __name__ == '__main__':
1708ec9d54bSJed Brown    import argparse
1713d94f746Srezgarshakeri    parser = argparse.ArgumentParser('Test runner with JUnit and TAP output')
1723d94f746Srezgarshakeri    parser.add_argument('--mode', help='Output mode, JUnit or TAP', default="JUnit")
1738ec9d54bSJed Brown    parser.add_argument('--output', help='Output file to write test', default=None)
1748ec9d54bSJed Brown    parser.add_argument('--gather', help='Gather all *.junit files into XML', action='store_true')
1758ec9d54bSJed Brown    parser.add_argument('test', help='Test executable', nargs='?')
1768ec9d54bSJed Brown    args = parser.parse_args()
1778ec9d54bSJed Brown
1788ec9d54bSJed Brown    if args.gather:
1798ec9d54bSJed Brown        gather()
1808ec9d54bSJed Brown    else:
1818ec9d54bSJed Brown        backends = os.environ['BACKENDS'].split()
1828ec9d54bSJed Brown
1838ec9d54bSJed Brown        result = run(args.test, backends)
184add335c8SJeremy L Thompson
1853d94f746Srezgarshakeri        if args.mode.lower() == "junit":
186add335c8SJeremy L Thompson            junit_batch = ''
187add335c8SJeremy L Thompson            try:
188add335c8SJeremy L Thompson                junit_batch = '-' + os.environ['JUNIT_BATCH']
189add335c8SJeremy L Thompson            except:
190add335c8SJeremy L Thompson                pass
191add335c8SJeremy L Thompson            output = (os.path.join('build', args.test + junit_batch + '.junit')
1928ec9d54bSJed Brown                      if args.output is None
1938ec9d54bSJed Brown                      else args.output)
194add335c8SJeremy L Thompson
1958ec9d54bSJed Brown            with open(output, 'w') as fd:
1968ec9d54bSJed Brown                TestSuite.to_file(fd, [result])
1973d94f746Srezgarshakeri        elif args.mode.lower() == "tap":
1983d94f746Srezgarshakeri            print('1..' + str(len(result.test_cases)))
1993d94f746Srezgarshakeri            for i in range(len(result.test_cases)):
2003d94f746Srezgarshakeri                test_case = result.test_cases[i]
2013d94f746Srezgarshakeri                test_index = str(i + 1)
2023d94f746Srezgarshakeri                print('# Test: ' + test_case.name.split(' ')[1])
2033d94f746Srezgarshakeri                print('# $ ' + test_case.args)
2043d94f746Srezgarshakeri                if test_case.is_error():
2053d94f746Srezgarshakeri                    message = test_case.is_error() if isinstance(test_case.is_error(), str) else test_case.errors[0]['message']
2063d94f746Srezgarshakeri                    print('not ok {} - ERROR: {}'.format(test_index, message.strip()))
2073d94f746Srezgarshakeri                    print(test_case.errors[0]['output'].strip())
2083d94f746Srezgarshakeri                elif test_case.is_failure():
2093d94f746Srezgarshakeri                    message = test_case.is_failure() if isinstance(test_case.is_failure(), str) else test_case.failures[0]['message']
2103d94f746Srezgarshakeri                    print('not ok {} - FAIL: {}'.format(test_index, message.strip()))
2113d94f746Srezgarshakeri                    print(test_case.failures[0]['output'].strip())
2123d94f746Srezgarshakeri                elif test_case.is_skipped():
2133d94f746Srezgarshakeri                    message = test_case.is_skipped() if isinstance(test_case.is_skipped(), str) else test_case.skipped[0]['message']
2143d94f746Srezgarshakeri                    print('ok {} - SKIP: {}'.format(test_index, message.strip()))
2153d94f746Srezgarshakeri                else:
2163d94f746Srezgarshakeri                    print('ok {} - PASS'.format(test_index))
2173d94f746Srezgarshakeri        else:
2183d94f746Srezgarshakeri            raise Exception("output mode not recognized")
219add335c8SJeremy L Thompson
2204d57a9fcSJed Brown        for t in result.test_cases:
2214d57a9fcSJed Brown            failures = len([c for c in result.test_cases if c.is_failure()])
2224d57a9fcSJed Brown            errors = len([c for c in result.test_cases if c.is_error()])
2234d57a9fcSJed Brown            if failures + errors > 0:
2244d57a9fcSJed Brown                sys.exit(1)
225