#!/usr/bin/env python

import fnmatch
import glob
import importlib.util as imputil
import os
import os.path as op
import sys
import time
import traceback


if __name__ == '__main__':
    thisdir     = op.dirname(__file__)
    results     = []

    filepat = '*'
    testpat = '*'

    # for local execution
    # if len(sys.argv) >= 2: filepat = f'*{sys.argv[1]}*'
    # if len(sys.argv) >= 3: testpat = f'*{sys.argv[2]}*'

    testscripts = list(glob.glob(op.join(thisdir, f'test_{filepat}.py')))

    for testscript in testscripts:

        print('=' * len(testscript))
        print(testscript)
        print('=' * len(testscript))
        modname = op.splitext(op.basename(testscript))[0]

        spec   = imputil.spec_from_file_location(modname, testscript)
        module = imputil.module_from_spec(spec)
        spec.loader.exec_module(module)

        funcs = dir(module)
        funcs = [f for f in funcs if fnmatch.fnmatch(f, f'test_{testpat}')]

        for funcname in funcs:
            func  = getattr(module, funcname)
            title = f'RUNNING {funcname}'
            print('-' * len(title))
            print(title)
            print('-' * len(title))

            start = time.time()

            try:
                func()
                result = 'PASSED'
            except Exception:
                print(traceback.format_exc())
                failed = True
                result = 'FAILED'

            end = time.time()

            result = f'{result} {funcname} {end - start:0.2f} seconds'

            results.append(result)

            print('-' * len(result))
            print(result)
            print('-' * len(result))

    for result in results:
        print(result)

    if any(r.startswith('FAILED') for r in results):
        raise SystemExit(1)
    else:
        raise SystemExit(0)
