Created
August 13, 2010 11:40
-
-
Save shawnchin/522733 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import inspect | |
import logging | |
import unittest | |
from glob import glob | |
def locate_suites(test_dirname="tests", test_file_prefix="test_"): | |
""" | |
Recursively search the test_dirname directory for *.py files that starts | |
with test_file_prefix and returns all test suites found within them. | |
Append the following to models.py to automatically discover tests: | |
def suite(): | |
from test_utils import locate_suites | |
return locate_suites() | |
""" | |
suites = [] | |
current_dir = os.path.realpath(os.path.dirname(__file__)) | |
test_dir = os.path.join(current_dir, test_dirname) | |
app_name = current_dir.split(os.sep)[-1] | |
for dirname,dirs,files in os.walk(test_dir): | |
relative_dir = dirname[len(current_dir)+1:] | |
mod_prefix = relative_dir.replace(os.path.sep, ".") | |
for filename in files: | |
if filename[-3:] != ".py" or filename[:len(test_file_prefix)] != test_file_prefix: | |
continue | |
mod_name = os.path.basename(filename)[:-3] | |
import_string = "%s.%s.%s" % (app_name, mod_prefix, mod_name) | |
try: | |
mod = __import__(import_string, globals(), locals(), [mod_name]) | |
except ImportError: | |
logging.error("Could not import %s" % (import_string,)) | |
continue | |
logging.debug("Loading test cases from %s" % os.path.join(relative_dir, filename)) | |
for name,obj in inspect.getmembers(mod, inspect.isclass): | |
suites.append(unittest.TestLoader().loadTestsFromTestCase(obj)) | |
return unittest.TestSuite(suites) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment