Created
March 18, 2015 19:21
-
-
Save PamelaM/6e85c69320bd2efc07cd 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
""" | |
Sample Output | |
$ python generatedtests.py -v | |
test_actual_one (__main__.ActualTest) ... ok | |
test_actual_two (__main__.ActualTest) ... FAIL | |
====================================================================== | |
FAIL: test_actual_two (__main__.ActualTest) | |
---------------------------------------------------------------------- | |
Traceback (most recent call last): | |
File "tmp.py", line 9, in test | |
self._test_func(*args, **kwargs) | |
File "tmp.py", line 27, in _test_func | |
self.assertIn("one", kwargs) | |
AssertionError: 'one' not found in {'two': 2} | |
---------------------------------------------------------------------- | |
Ran 2 tests in 0.001s | |
FAILED (failures=1) | |
""" | |
import unittest | |
class GeneratedTestBase(unittest.TestCase): | |
""" Base class that generates test functions """ | |
@classmethod | |
def make_test_func(cls, *args, **kwargs): | |
def test(self): | |
self._test_func(*args, **kwargs) | |
return test | |
# -- Has to be called before instantiation of GeneratedTestBase object because | |
# unittest test discovery occurs before TestCase objects are instantiated | |
@classmethod | |
def generate_test_functions(cls, name_prefix, tests_dictionary): | |
# -- Add a test for each term in check_search.SEARCH_TERMS | |
for test_name, (test_args, test_kwargs) in tests_dictionary.items(): | |
test_name = "test_{0}_{1}".format(name_prefix, test_name) | |
test_name = "_".join(test_name.replace("-", " ").split()) | |
test_name = test_name.replace("test_test_", "test_") | |
test_func = cls.make_test_func(*test_args, **test_kwargs) | |
setattr(cls, test_name, test_func) | |
class ActualTest(GeneratedTestBase): | |
def _test_func(self, *args, **kwargs): | |
self.assertIn(args[0], (1,2)) | |
self.assertIn("one", kwargs) | |
tests_to_create = {"one":((1,),{"one":1}), | |
"two":((2,),{"two":2})} | |
ActualTest.generate_test_functions("actual", tests_to_create) | |
if __name__ == '__main__': | |
unittest.main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment