run.py 2.11 KB
Newer Older
1
import inspect
2

3

4
class SelfTest:
5
6
7
8
9
10
11
12
13
14
15
16
17
    def setup(self):
        print("setup")

    def teardown(self):
        print("teardown")

    def test1(self):
        print("test1")

    def test2(self):
        print("test2")


18
def runner(tests, namespace):
19
    """ Runs only some selected tests from a test suite. To run all
20
    tests in a module, call ``runner("", globals())`` from within
21
    that module.
di68kap's avatar
di68kap committed
22

23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
    Args:
        tests: Either a string or a list of strings that contains the
            names of test or test classes. Each test and, in the case
            of a test class, all tests within the test class will be
            run.
        namespace: The namespace for running the test, usually 
            ``globals()`` should be used.
    """
    def instantiate(cls_name):
        exec("obj = " + cls_name + "()", namespace)
        obj = namespace["obj"]
        if "setup" in dir(obj):
            obj.setup()
        return obj

38
39
40
41
42
43
44
45
46
47
    if tests:
        if isinstance(tests, str):
            tests = tests.split(" ")
    else:
        # collect all test classes, in case no methods or classes have been passed explicitly
        tests = []
        for name in namespace.keys():
            if name.lower().startswith('test') and inspect.isclass(namespace[name]):
                tests.append(name)

48
    obj = None
49
    for test in tests:
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
        try:
            if test.find('.') >= 0:
                cls_name, method_name = test.split('.')
                obj = instantiate(cls_name)
                print("Running " + cls_name + "." + method_name)
                exec('obj.' + method_name + '()')
            else:
                obj = instantiate(test)
                for name in dir(obj):
                    if name.lower().startswith("test"):
                        print("Running " + test + "." + name)
                        exec('obj.' + name + '()')
        finally:
            if "teardown" in dir(obj):
                obj.teardown()
65
66

if __name__ == "__main__":
67
68
    # runner("", globals())
    # runner("TestSelf.test1 TestSelf", globals())
69
    import os
70
71
72

    os.chdir('..')
    print("Running nosetests:")
73
    os.system("nosetests")