11
sys.path.insert(0, os.path.abspath("."))
13
class TestRunner(object):
15
def _load_unittest(self, relpath):
16
"""Load unit tests from a Python module with the given relative path."""
17
assert relpath.endswith(".py"), (
18
"%s does not appear to be a Python module" % relpath)
19
modpath = relpath.replace(os.path.sep, ".")[:-3]
20
module = __import__(modpath, None, None, [""])
22
# If the module has a 'suite' or 'test_suite' function, use that
24
if hasattr(module, "suite"):
26
elif hasattr(module, "test_suite"):
27
return module.test_suite()
29
return unittest.defaultTestLoader.loadTestsFromModule(module)
31
def _collect_tests(self, testpath, test_pattern):
32
"""Return the set of unittests."""
33
suite = unittest.TestSuite()
35
pattern = re.compile('.*%s.*' % test_pattern)
40
module_suite = self._load_unittest(testpath)
42
for inner_suite in module_suite._tests:
43
for test in inner_suite._tests:
44
if pattern.match(test.id()):
47
suite.addTests(module_suite)
50
# We don't use the dirs variable, so ignore the warning
51
# pylint: disable-msg=W0612
52
for root, dirs, files in os.walk("tests"):
54
path = os.path.join(root, file)
55
if file.endswith(".py") and file.startswith("test_"):
56
module_suite = self._load_unittest(path)
58
for inner_suite in module_suite._tests:
59
for test in inner_suite._tests:
60
if pattern.match(test.id()):
63
suite.addTests(module_suite)
66
def run(self, testpath, test_pattern=None):
68
from twisted.internet import reactor
69
from twisted.trial.reporter import TreeReporter
70
from twisted.trial.runner import TrialRunner
72
workingDirectory = os.path.join(os.getcwd(), "_trial_temp", "tmp")
73
runner = TrialRunner(reporterFactory=TreeReporter, realTimeErrors=True,
74
workingDirectory=workingDirectory)
76
# setup a custom XDG_CACHE_HOME and create the logs directory
77
xdg_cache = os.path.join(os.getcwd(), "_trial_temp", "xdg_cache")
78
os.environ["XDG_CACHE_HOME"] = xdg_cache
79
# setup the ROOT_DIR env var
80
os.environ['ROOT_DIR'] = os.getcwd()
81
if not os.path.exists(xdg_cache):
82
os.makedirs(xdg_cache)
84
suite = self._collect_tests(testpath, test_pattern)
85
result = runner.run(suite)
86
success = result.wasSuccessful()
93
if __name__ == '__main__':
94
from optparse import OptionParser
95
usage = '%prog [options] path'
96
parser = OptionParser(usage=usage)
97
parser.add_option("-t", "--test", dest="test",
98
help = "run specific tests, e.g: className.methodName")
100
(options, args) = parser.parse_args()
103
if not os.path.exists(testpath):
104
print "the path to test does not exists!"
108
TestRunner().run(testpath, options.test)