# coding = utf-8

import os
import re
from subprocess import Popen, PIPE
from time import time
import getopt
import sys

def list_tests(excludes):
    "return module names for tests"
    tests = []
    freewat_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
    for root, dirs, files in os.walk(freewat_dir):
        for file_ in files:
            if re.match(r".*_test.py$", file_):
                # remove the trailing '.py' (3 characters)
                # replace \ or / by dots
                test = '.'.join(
                            os.path.abspath(
                                os.path.join(root, file_)
                            ).replace(freewat_dir, "freewat").split(os.sep))[:-3]
                if test not in excludes:
                    tests.append(test)
    return tests

def test(excludes=['freewat.plotting.tests.plotting_test', 'freewat.plotting.tests.bubble_test']):
    tests = list_tests(excludes)

    for i, test in enumerate(tests):
        sys.stdout.write("% 3d/%d %s "%(i+1, len(tests), test))
        sys.stdout.flush()
        s= time()
        our, err = Popen(["python", "-m", test],
                stdin=PIPE,
                stderr=PIPE,
                stdout=PIPE).communicate()
        if err:
            sys.stdout.write('\n')
            sys.stdout.write(err)
            sys.stdout.write('############## ABORT TESTING ###############\n')
            raise RuntimeError(" %.2f sec\nFAILED\n"%(time() - s))
        
        sys.stdout.write(" %.2f sec\n"%(time() - s))
