The Python standard library comes with an extensive set of regression tests. I had need to import and run some of these tests from my own code, but the test directory is not in Python's path. This simple helper function solves the problem.
Python, 9 lines
1 2 3 4 5 6 7 8 9
import os, sys def locate_regression_tests(): for path in sys.path: if os.path.isdir(path): path = os.path.join(path, 'test') if os.path.isdir(path): return path raise RuntimeError('unable to locate standard regression tests')
If you try to import Python's regression tests, it will fail:
>>> import test_dict Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named test_dict
But using this helper, you can import the regression tests to run them programmatically, or create new tests:
>>> sys.path.append(locate_regression_tests()) >>> import test_dict >>> test_dict.test_main() # lots of output printed here...
Tags: import, path, regression, testing
Ah, I didn't notice that the test suite is actually a package, so while you can't directly import the modules, you can do this:
So this helper is actually redundant, although the basic idea of searching the path for a location is still sound.