1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 """
20 Test utilities
21
22 Allows testing whole test hierarchies.
23
24 Note: It involves copying testall.py files around, etc, I'm sure there are
25 better ways of doing this, for my projects it was good enough though.
26
27 Functions:
28
29 - `test_suite_from_package`: Recursively get test suite of all tests in a
30 package
31
32 - `run`: Run test and print results to stderr
33 """
34
35 __docformat__ = 'reStructuredText'
36
37 import unittest
38 import os
39 import logging
40
41 _logger = logging.getLogger("pytilities.testing")
42
43
44
45
46
48 """
49 Recursively get test suite of all tests in a package and its child packages
50
51 For this to work correctly you must build a specific hierarchy of test
52 packages. Each package to be test should contain a test package. Each test
53 package must contain a testall.py file, you can find them all over
54 pytilities, just copy one of them, no changes are required. For example::
55
56 pytilities
57 test
58 testall.py
59 event
60 test
61 testall.py
62 ...
63
64 Note that this may not work as expected::
65 proj
66 test
67 p
68 b
69 test
70
71 Running tests from proj.test will not run tests from b. You must 'fill in
72 the gaps', i.e. p needs a test package as well to prevent the recursion to
73 stop at p.
74
75 Parameters:
76
77 `module_file` :: string
78 the testall.py file path. (use
79 __file__)
80
81 `module_name`:: string
82 name of the calling module. (use __name__)
83
84 Usage example:
85 See pytilities.test (or any other test package)
86 """
87 package = ".".join(module_name.split(".")[:-1])
88 current_dir = os.path.dirname(module_file)
89 parent_dir = os.path.join(current_dir, "..")
90 parent_package = ".".join(package.split(".")[:-1])
91 test_loader = unittest.defaultTestLoader
92
93 _logger.debug(" ".join((module_file, module_name, package,
94 parent_package, current_dir)))
95 _logger.debug(module_name)
96
97
98 test_suite = test_loader.loadTestsFromNames(
99 ".".join((parent_package, f, "test", "testall", "test_suite"))
100 for f in os.listdir(parent_dir)
101 if f[0] != "_" and f != "test"
102 and os.path.isdir(os.path.join(parent_dir, f, "test")))
103
104 _logger.debug([package + "." + os.path.splitext(f)[0]
105 for f in os.listdir(current_dir)
106 if f[0] != "_" and f != "testall.py" and f[-3:] == ".py"])
107
108
109 test_suite.addTest(
110 test_loader.loadTestsFromNames(
111 package + "." + os.path.splitext(f)[0]
112 for f in os.listdir(current_dir)
113 if f[0] != "_" and f != "testall.py" and f[-3:] == ".py"))
114
115 return test_suite
116
118 """
119 Run test and print results to stderr
120
121 Parameters:
122
123 `test`
124 the TestCase to run
125 """
126 runner = unittest.TextTestRunner()
127 return runner.run(test)
128