xref: /libCEED/tests/junit.py (revision 2ae780f285b973adc2f17a8658b271f19558a5ad)
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
88ec9d54bSJed Browndef parse_testargs(file):
98ec9d54bSJed Brown    if os.path.splitext(file)[1] in ['.c', '.cpp']:
10dc8efd83SLeila Ghaffari        return sum([[[line.split()[1:], [line.split()[0].strip('//TESTARGS(name=').strip(')')]]]
11dc8efd83SLeila Ghaffari                    for line in open(file).readlines()
128ec9d54bSJed Brown                    if line.startswith('//TESTARGS')], [])
138ec9d54bSJed Brown    elif os.path.splitext(file)[1] == '.usr':
14dc8efd83SLeila Ghaffari        return sum([[[line.split()[1:], [line.split()[0].strip('C_TESTARGS(name=').strip(')')]]]
15dc8efd83SLeila Ghaffari                    for line in open(file).readlines()
161b685ca3Sjeth8984                    if line.startswith('C_TESTARGS')], [])
175435e910SJed Brown    elif os.path.splitext(file)[1] in ['.f90']:
185435e910SJed Brown        return sum([[[line.split()[1:], [line.split()[0].strip('C_TESTARGS(name=').strip(')')]]]
195435e910SJed Brown                    for line in open(file).readlines()
205435e910SJed Brown                    if line.startswith('! TESTARGS')], [])
219bcbe8bdSJed Brown    raise RuntimeError('Unrecognized extension for file: {}'.format(file))
228ec9d54bSJed Brown
238ec9d54bSJed Browndef get_source(test):
248ec9d54bSJed Brown    if test.startswith('petsc-'):
258ec9d54bSJed Brown        return os.path.join('examples', 'petsc', test[6:] + '.c')
268ec9d54bSJed Brown    elif test.startswith('mfem-'):
278ec9d54bSJed Brown        return os.path.join('examples', 'mfem', test[5:] + '.cpp')
288ec9d54bSJed Brown    elif test.startswith('nek-'):
2986a4271fSThilina Rathnayake        return os.path.join('examples', 'nek', 'bps', test[4:] + '.usr')
30ccaff030SJeremy L Thompson    elif test.startswith('fluids-'):
31ccaff030SJeremy L Thompson        return os.path.join('examples', 'fluids', test[7:] + '.c')
32ccaff030SJeremy L Thompson    elif test.startswith('solids-'):
33ccaff030SJeremy L Thompson        return os.path.join('examples', 'solids', test[7:] + '.c')
348ec9d54bSJed Brown    elif test.startswith('ex'):
358ec9d54bSJed Brown        return os.path.join('examples', 'ceed', test + '.c')
365435e910SJed Brown    elif test.endswith('-f'):
375435e910SJed Brown        return os.path.join('tests', test + '.f90')
385435e910SJed Brown    else:
395435e910SJed Brown        return os.path.join('tests', test + '.c')
408ec9d54bSJed Brown
415435e910SJed Browndef get_testargs(source):
425435e910SJed Brown    args = parse_testargs(source)
435435e910SJed Brown    if not args:
445435e910SJed Brown        return [(['{ceed_resource}'], [''])]
455435e910SJed Brown    return args
468ec9d54bSJed Brown
47bdb0bdbbSJed Browndef check_required_failure(case, stderr, required):
48bdb0bdbbSJed Brown    if required in stderr:
49bdb0bdbbSJed Brown        case.status = 'fails with required: {}'.format(required)
50bdb0bdbbSJed Brown    else:
51bdb0bdbbSJed Brown        case.add_failure_info('required: {}'.format(required))
52bdb0bdbbSJed Brown
53b974e86eSJed Browndef contains_any(resource, substrings):
54b974e86eSJed Brown    return any((sub in resource for sub in substrings))
55b974e86eSJed Brown
56b974e86eSJed Browndef skip_rule(test, resource):
57b974e86eSJed Brown    return any((
5812070e41Snbeams        test.startswith('fluids-') and contains_any(resource, ['occa']),
59ccaff030SJeremy L Thompson        test.startswith('solids-') and contains_any(resource, ['occa']),
605dc4928cSjeremylt        test.startswith('nek') and contains_any(resource, ['occa']),
611da99368SJeremy L Thompson        test.startswith('t507') and contains_any(resource, ['occa']),
6212070e41Snbeams        test.startswith('t318') and contains_any(resource, ['/gpu/cuda/ref']),
6312070e41Snbeams        test.startswith('t506') and contains_any(resource, ['/gpu/cuda/shared']),
64b974e86eSJed Brown        ))
65b974e86eSJed Brown
668ec9d54bSJed Browndef run(test, backends):
678ec9d54bSJed Brown    import subprocess
688ec9d54bSJed Brown    import time
698ec9d54bSJed Brown    import difflib
705435e910SJed Brown    source = get_source(test)
715435e910SJed Brown    allargs = get_testargs(source)
72288c0443SJeremy L Thompson
738ec9d54bSJed Brown    testcases = []
742777116bSjeremylt    my_env = os.environ.copy()
752777116bSjeremylt    my_env["CEED_ERROR_HANDLER"] = 'exit';
76dc8efd83SLeila Ghaffari    for args, name in allargs:
778ec9d54bSJed Brown        for ceed_resource in backends:
788ec9d54bSJed Brown            rargs = [os.path.join('build', test)] + args.copy()
798ec9d54bSJed Brown            rargs[rargs.index('{ceed_resource}')] = ceed_resource
80b974e86eSJed Brown
81b974e86eSJed Brown            if skip_rule(test, ceed_resource):
82b974e86eSJed Brown                case = TestCase('{} {}'.format(test, ceed_resource),
83b974e86eSJed Brown                                elapsed_sec=0,
8437e4ed59SJed Brown                                timestamp=time.strftime('%Y-%m-%d %H:%M:%S %Z', time.localtime()),
85b974e86eSJed Brown                                stdout='',
86b974e86eSJed Brown                                stderr='')
87b974e86eSJed Brown                case.add_skipped_info('Pre-run skip rule')
88b974e86eSJed Brown            else:
898ec9d54bSJed Brown                start = time.time()
908ec9d54bSJed Brown                proc = subprocess.run(rargs,
918ec9d54bSJed Brown                                      stdout=subprocess.PIPE,
922777116bSjeremylt                                      stderr=subprocess.PIPE,
932777116bSjeremylt                                      env=my_env)
9473132ccbSJed Brown                proc.stdout = proc.stdout.decode('utf-8')
9573132ccbSJed Brown                proc.stderr = proc.stderr.decode('utf-8')
968ec9d54bSJed Brown
97dc8efd83SLeila Ghaffari                case = TestCase('{} {} {}'.format(test, *name, ceed_resource),
985435e910SJed Brown                                classname=os.path.dirname(source),
998ec9d54bSJed Brown                                elapsed_sec=time.time()-start,
1008ec9d54bSJed Brown                                timestamp=time.strftime('%Y-%m-%d %H:%M:%S %Z', time.localtime(start)),
1018ec9d54bSJed Brown                                stdout=proc.stdout,
1028ec9d54bSJed Brown                                stderr=proc.stderr)
103288c0443SJeremy L Thompson                ref_stdout = os.path.join('tests/output', test + '.out')
104bdb0bdbbSJed Brown
105b974e86eSJed Brown            if not case.is_skipped() and proc.stderr:
1068ec9d54bSJed Brown                if 'OCCA backend failed to use' in proc.stderr:
1079bcbe8bdSJed Brown                    case.add_skipped_info('occa mode not supported {} {}'.format(test, ceed_resource))
1088ec9d54bSJed Brown                elif 'Backend does not implement' in proc.stderr:
1099bcbe8bdSJed Brown                    case.add_skipped_info('not implemented {} {}'.format(test, ceed_resource))
1109c774eddSJeremy L Thompson                elif 'Can only provide HOST memory for this backend' in proc.stderr:
111cbac262cSjeremylt                    case.add_skipped_info('device memory not supported {} {}'.format(test, ceed_resource))
11280a9ef05SNatalie Beams                elif 'Test not implemented in single precision' in proc.stderr:
11380a9ef05SNatalie Beams                    case.add_skipped_info('not implemented {} {}'.format(test, ceed_resource))
114bdb0bdbbSJed Brown
1158ec9d54bSJed Brown            if not case.is_skipped():
1162bbc7fe8Sjeremylt                if test[:4] in 't006 t007'.split():
1172bbc7fe8Sjeremylt                    check_required_failure(case, proc.stderr, 'No suitable backend:')
11822e44211Sjeremylt                if test[:4] in 't008'.split():
11992ee7d1cSjeremylt                    check_required_failure(case, proc.stderr, 'Available backend resources:')
1209f4513dfSjeremylt                if test[:4] in 't110 t111 t112 t113 t114'.split():
121bdb0bdbbSJed Brown                    check_required_failure(case, proc.stderr, 'Cannot grant CeedVector array access')
1229f4513dfSjeremylt                if test[:4] in 't115'.split():
1239f4513dfSjeremylt                    check_required_failure(case, proc.stderr, 'Cannot grant CeedVector read-only array access, the access lock is already in use')
1249f4513dfSjeremylt                if test[:4] in 't116'.split():
125187168c7SJeremy L Thompson                    check_required_failure(case, proc.stderr, 'Cannot destroy CeedVector, the writable access lock is in use')
1269f4513dfSjeremylt                if test[:4] in 't117'.split():
127bdb0bdbbSJed Brown                    check_required_failure(case, proc.stderr, 'Cannot restore CeedVector array access, access was not granted')
1289f4513dfSjeremylt                if test[:4] in 't118'.split():
1299f4513dfSjeremylt                    check_required_failure(case, proc.stderr, 'Cannot sync CeedVector, the access lock is already in use')
130430758c8SJeremy L Thompson                if test[:4] in 't215'.split():
131430758c8SJeremy L Thompson                    check_required_failure(case, proc.stderr, 'Cannot destroy CeedElemRestriction, a process has read access to the offset data')
13252bfb9bbSJeremy L Thompson                if test[:4] in 't303'.split():
133bdb0bdbbSJed Brown                    check_required_failure(case, proc.stderr, 'Length of input/output vectors incompatible with basis dimensions')
13428bfd0b7SJeremy L Thompson                if test[:4] in 't408'.split():
13528bfd0b7SJeremy L Thompson                    check_required_failure(case, proc.stderr, 'CeedQFunctionContextGetData(): Cannot grant CeedQFunctionContext data access, a process has read access')
136*2ae780f2SJeremy L Thompson                if test[:4] in 't409'.split() and contains_any(ceed_resource, ['memcheck']):
137*2ae780f2SJeremy L Thompson                    check_required_failure(case, proc.stderr, 'Context data changed while accessed in read-only mode')
138bdb0bdbbSJed Brown
139bdb0bdbbSJed Brown            if not case.is_skipped() and not case.status:
140bdb0bdbbSJed Brown                if proc.stderr:
141bdb0bdbbSJed Brown                    case.add_failure_info('stderr', proc.stderr)
142bdb0bdbbSJed Brown                elif proc.returncode != 0:
1439bcbe8bdSJed Brown                    case.add_error_info('returncode = {}'.format(proc.returncode))
1448ec9d54bSJed Brown                elif os.path.isfile(ref_stdout):
1458ec9d54bSJed Brown                    with open(ref_stdout) as ref:
1468ec9d54bSJed Brown                        diff = list(difflib.unified_diff(ref.readlines(),
1478ec9d54bSJed Brown                                                         proc.stdout.splitlines(keepends=True),
1488ec9d54bSJed Brown                                                         fromfile=ref_stdout,
1498ec9d54bSJed Brown                                                         tofile='New'))
1508ec9d54bSJed Brown                    if diff:
1518ec9d54bSJed Brown                        case.add_failure_info('stdout', output=''.join(diff))
1520a0da059Sjeremylt                elif proc.stdout and test[:4] not in 't003':
1538ec9d54bSJed Brown                    case.add_failure_info('stdout', output=proc.stdout)
1548ec9d54bSJed Brown            testcases.append(case)
1558ec9d54bSJed Brown    return TestSuite(test, testcases)
1568ec9d54bSJed Brown
1578ec9d54bSJed Brownif __name__ == '__main__':
1588ec9d54bSJed Brown    import argparse
1598ec9d54bSJed Brown    parser = argparse.ArgumentParser('Test runner with JUnit output')
1608ec9d54bSJed Brown    parser.add_argument('--output', help='Output file to write test', default=None)
1618ec9d54bSJed Brown    parser.add_argument('--gather', help='Gather all *.junit files into XML', action='store_true')
1628ec9d54bSJed Brown    parser.add_argument('test', help='Test executable', nargs='?')
1638ec9d54bSJed Brown    args = parser.parse_args()
1648ec9d54bSJed Brown
1658ec9d54bSJed Brown    if args.gather:
1668ec9d54bSJed Brown        gather()
1678ec9d54bSJed Brown    else:
1688ec9d54bSJed Brown        backends = os.environ['BACKENDS'].split()
1698ec9d54bSJed Brown
1708ec9d54bSJed Brown        result = run(args.test, backends)
171add335c8SJeremy L Thompson
172add335c8SJeremy L Thompson        junit_batch = ''
173add335c8SJeremy L Thompson        try:
174add335c8SJeremy L Thompson            junit_batch = '-' + os.environ['JUNIT_BATCH']
175add335c8SJeremy L Thompson        except:
176add335c8SJeremy L Thompson            pass
177add335c8SJeremy L Thompson        output = (os.path.join('build', args.test + junit_batch + '.junit')
1788ec9d54bSJed Brown                  if args.output is None
1798ec9d54bSJed Brown                  else args.output)
180add335c8SJeremy L Thompson
1818ec9d54bSJed Brown        with open(output, 'w') as fd:
1828ec9d54bSJed Brown            TestSuite.to_file(fd, [result])
183add335c8SJeremy L Thompson
1844d57a9fcSJed Brown        for t in result.test_cases:
1854d57a9fcSJed Brown            failures = len([c for c in result.test_cases if c.is_failure()])
1864d57a9fcSJed Brown            errors = len([c for c in result.test_cases if c.is_error()])
1874d57a9fcSJed Brown            if failures + errors > 0:
1884d57a9fcSJed Brown                sys.exit(1)
189