<p>I have some kind of test data and want to create a unit test for each item. My first idea was to do it like this:</p>
<pre><code>import unittest

l = [[&quot;foo&quot;, &quot;a&quot;, &quot;a&quot;,], [&quot;bar&quot;, &quot;a&quot;, &quot;b&quot;], [&quot;lee&quot;, &quot;b&quot;, &quot;b&quot;]]

class TestSequence(unittest.TestCase):
    def testsample(self):
        for name, a,b in l:
            print &quot;test&quot;, name
            self.assertEqual(a,b)

if __name__ == '__main__':
    unittest.main()
</code></pre>
<p>The downside of this is that it handles all data in one test. I would like to generate one test for each item on the fly. Any suggestions?</p>

[{'answer_id': 32939, 'author': 'Dmitry Mukhin', 'author_id': 3448, 'author_profile': 'https://Stackoverflow.com/users/3448', 'pm_score': 9, 'selected': True, 'text': '<p>This is called &quot;parametrization&quot;.</p>\n<p>There are several tools that support this approach. E.g.:</p>\n<ul>\n<li><a href="https://docs.pytest.org/en/latest/parametrize.html" rel="noreferrer">pytest\'s decorator</a></li>\n<li><a href="https://github.com/wolever/parameterized" rel="noreferrer">parameterized</a></li>\n</ul>\n<p>The resulting code looks like this:</p>\n<pre><code>from parameterized import parameterized\n\nclass TestSequence(unittest.TestCase):\n    @parameterized.expand([\n        [&quot;foo&quot;, &quot;a&quot;, &quot;a&quot;,],\n        [&quot;bar&quot;, &quot;a&quot;, &quot;b&quot;],\n        [&quot;lee&quot;, &quot;b&quot;, &quot;b&quot;],\n    ])\n    def test_sequence(self, name, a, b):\n        self.assertEqual(a,b)\n</code></pre>\n<p>Which will generate the tests:</p>\n<pre class="lang-none prettyprint-override"><code>test_sequence_0_foo (__main__.TestSequence) ... ok\ntest_sequence_1_bar (__main__.TestSequence) ... FAIL\ntest_sequence_2_lee (__main__.TestSequence) ... ok\n\n======================================================================\nFAIL: test_sequence_1_bar (__main__.TestSequence)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n  File &quot;/usr/local/lib/python2.7/site-packages/parameterized/parameterized.py&quot;, line 233, in &lt;lambda&gt;\n    standalone_func = lambda *a: func(*(a + p.args), **p.kwargs)\n  File &quot;x.py&quot;, line 12, in test_sequence\n    self.assertEqual(a,b)\nAssertionError: \'a\' != \'b\'\n</code></pre>\n<p>For historical reasons I\'ll leave the original answer circa 2008):</p>\n<p>I use something like this:</p>\n<pre><code>import unittest\n\nl = [[&quot;foo&quot;, &quot;a&quot;, &quot;a&quot;,], [&quot;bar&quot;, &quot;a&quot;, &quot;b&quot;], [&quot;lee&quot;, &quot;b&quot;, &quot;b&quot;]]\n\nclass TestSequense(unittest.TestCase):\n    pass\n\ndef test_generator(a, b):\n    def test(self):\n        self.assertEqual(a,b)\n    return test\n\nif __name__ == \'__main__\':\n    for t in l:\n        test_name = \'test_%s\' % t[0]\n        test = test_generator(t[1], t[2])\n        setattr(TestSequense, test_name, test)\n    unittest.main()\n</code></pre>\n'}, {'answer_id': 34094, 'author': 'codeape', 'author_id': 3571, 'author_profile': 'https://Stackoverflow.com/users/3571', 'pm_score': 8, 'selected': False, 'text': '<p><strong>Using <a href="https://docs.python.org/3/library/unittest.html" rel="noreferrer">unittest</a> (since 3.4)</strong></p>\n<p>Since Python 3.4, the standard library <code>unittest</code> package has the <code>subTest</code> context manager.</p>\n<p>See the documentation:</p>\n<ul>\n<li><a href="https://docs.python.org/3/library/unittest.html#distinguishing-test-iterations-using-subtests" rel="noreferrer">26.4.7. Distinguishing test iterations using subtests</a></li>\n<li><a href="https://docs.python.org/3/library/unittest.html#unittest.TestCase.subTest" rel="noreferrer">subTest</a></li>\n</ul>\n<p>Example:</p>\n<pre><code>from unittest import TestCase\n\nparam_list = [(\'a\', \'a\'), (\'a\', \'b\'), (\'b\', \'b\')]\n\nclass TestDemonstrateSubtest(TestCase):\n    def test_works_as_expected(self):\n        for p1, p2 in param_list:\n            with self.subTest():\n                self.assertEqual(p1, p2)\n</code></pre>\n<p>You can also specify a custom message and parameter values to <code>subTest()</code>:</p>\n<pre><code>with self.subTest(msg=&quot;Checking if p1 equals p2&quot;, p1=p1, p2=p2):\n</code></pre>\n<p><strong>Using <a href="https://pypi.org/project/nose/" rel="noreferrer">nose</a></strong></p>\n<p>The <a href="https://nose.readthedocs.org/en/latest/" rel="noreferrer">nose</a> testing framework <a href="https://nose.readthedocs.org/en/latest/writing_tests.html#test-generators" rel="noreferrer">supports this</a>.</p>\n<p>Example (the code below is the entire contents of the file containing the test):</p>\n<pre><code>param_list = [(\'a\', \'a\'), (\'a\', \'b\'), (\'b\', \'b\')]\n\ndef test_generator():\n    for params in param_list:\n        yield check_em, params[0], params[1]\n\ndef check_em(a, b):\n    assert a == b\n</code></pre>\n<p>The output of the nosetests command:</p>\n<pre class="lang-none prettyprint-override"><code>&gt; nosetests -v\ntestgen.test_generator(\'a\', \'a\') ... ok\ntestgen.test_generator(\'a\', \'b\') ... FAIL\ntestgen.test_generator(\'b\', \'b\') ... ok\n\n======================================================================\nFAIL: testgen.test_generator(\'a\', \'b\')\n----------------------------------------------------------------------\nTraceback (most recent call last):\n  File &quot;/usr/lib/python2.5/site-packages/nose-0.10.1-py2.5.egg/nose/case.py&quot;, line 203, in runTest\n    self.test(*self.arg)\n  File &quot;testgen.py&quot;, line 7, in check_em\n    assert a == b\nAssertionError\n\n----------------------------------------------------------------------\nRan 3 tests in 0.006s\n\nFAILED (failures=1)\n</code></pre>\n'}, {'answer_id': 810127, 'author': 'bignose', 'author_id': 70157, 'author_profile': 'https://Stackoverflow.com/users/70157', 'pm_score': 3, 'selected': False, 'text': '<p>You would benefit from trying the <a href="https://launchpad.net/testscenarios" rel="noreferrer">TestScenarios</a> library.</p>\n\n<blockquote>\n  <p>testscenarios provides clean dependency injection for python unittest style tests. This can be used for interface testing (testing many implementations via a single test suite) or for classic dependency injection (provide tests with dependencies externally to the test code itself, allowing easy testing in different situations).</p>\n</blockquote>\n'}, {'answer_id': 20870875, 'author': 'Guy', 'author_id': 1540037, 'author_profile': 'https://Stackoverflow.com/users/1540037', 'pm_score': 6, 'selected': False, 'text': '<p>This can be solved elegantly using Metaclasses:</p>\n\n<pre><code>import unittest\n\nl = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]]\n\nclass TestSequenceMeta(type):\n    def __new__(mcs, name, bases, dict):\n\n        def gen_test(a, b):\n            def test(self):\n                self.assertEqual(a, b)\n            return test\n\n        for tname, a, b in l:\n            test_name = "test_%s" % tname\n            dict[test_name] = gen_test(a,b)\n        return type.__new__(mcs, name, bases, dict)\n\nclass TestSequence(unittest.TestCase):\n    __metaclass__ = TestSequenceMeta\n\nif __name__ == \'__main__\':\n    unittest.main()\n</code></pre>\n'}, {'answer_id': 23508426, 'author': 'Javier', 'author_id': 3339058, 'author_profile': 'https://Stackoverflow.com/users/3339058', 'pm_score': 5, 'selected': False, 'text': '<p><a href="https://docs.python.org/2/library/unittest.html#load-tests-protocol">load_tests</a> is a little known mechanism introduced in 2.7 to dynamically create a TestSuite. With it, you can easily create parametrized tests.</p>\n\n<p>For example:</p>\n\n<pre><code>import unittest\n\nclass GeneralTestCase(unittest.TestCase):\n    def __init__(self, methodName, param1=None, param2=None):\n        super(GeneralTestCase, self).__init__(methodName)\n\n        self.param1 = param1\n        self.param2 = param2\n\n    def runTest(self):\n        pass  # Test that depends on param 1 and 2.\n\n\ndef load_tests(loader, tests, pattern):\n    test_cases = unittest.TestSuite()\n    for p1, p2 in [(1, 2), (3, 4)]:\n        test_cases.addTest(GeneralTestCase(\'runTest\', p1, p2))\n    return test_cases\n</code></pre>\n\n<p>That code will run all the TestCases in the TestSuite returned by load_tests. No other tests are automatically run by the discovery mechanism.</p>\n\n<p>Alternatively, you can also use inheritance as shown in this ticket: <a href="http://bugs.python.org/msg151444">http://bugs.python.org/msg151444</a></p>\n'}, {'answer_id': 25626660, 'author': 'Sergei Voronezhskii', 'author_id': 4000827, 'author_profile': 'https://Stackoverflow.com/users/4000827', 'pm_score': 5, 'selected': False, 'text': '<p>It can be done by using <a href="http://pytest.org" rel="noreferrer">pytest</a>. Just write the file <code>test_me.py</code> with content:</p>\n<pre class="lang-python prettyprint-override"><code>import pytest\n\n@pytest.mark.parametrize(\'name, left, right\', [[\'foo\', \'a\', \'a\'],\n                                               [\'bar\', \'a\', \'b\'],\n                                               [\'baz\', \'b\', \'b\']])\ndef test_me(name, left, right):\n    assert left == right, name\n</code></pre>\n<p>And run your test with command <code>py.test --tb=short test_me.py</code>. Then the output will look like:</p>\n<pre class="lang-none prettyprint-override"><code>=========================== test session starts ============================\nplatform darwin -- Python 2.7.6 -- py-1.4.23 -- pytest-2.6.1\ncollected 3 items\n\ntest_me.py .F.\n\n================================= FAILURES =================================\n_____________________________ test_me[bar-a-b] _____________________________\ntest_me.py:8: in test_me\n    assert left == right, name\nE   AssertionError: bar\n==================== 1 failed, 2 passed in 0.01 seconds ====================\n</code></pre>\n<p>It is simple! Also <a href="http://pytest.org" rel="noreferrer">pytest</a> has more features like <code>fixtures</code>, <code>mark</code>, <code>assert</code>, etc.</p>\n'}, {'answer_id': 27250866, 'author': 'Maroun', 'author_id': 1735406, 'author_profile': 'https://Stackoverflow.com/users/1735406', 'pm_score': 2, 'selected': False, 'text': '<p>You can use the <a href="https://github.com/taykey/nose-ittr" rel="nofollow noreferrer">nose-ittr</a> plugin (<code>pip install nose-ittr</code>).</p>\n<p>It\'s very easy to integrate with existing tests, and minimal changes (if any) are required. It also supports the <em>nose</em> multiprocessing plugin.</p>\n<p>Note that you can also have a customize <code>setup</code> function per test.</p>\n<pre><code>@ittr(number=[1, 2, 3, 4])\ndef test_even(self):\n    assert_equal(self.number % 2, 0)\n</code></pre>\n<p>It is also possible to pass <code>nosetest</code> parameters like with their built-in plugin <code>attrib</code>. This way you can run only a specific test with specific parameter:</p>\n<pre class="lang-none prettyprint-override"><code>nosetest -a number=2\n</code></pre>\n'}, {'answer_id': 28890882, 'author': 'Matt', 'author_id': 452274, 'author_profile': 'https://Stackoverflow.com/users/452274', 'pm_score': 2, 'selected': False, 'text': '<p>I came across <a href="https://pypi.python.org/pypi/ParamUnittest" rel="nofollow noreferrer"><strong>ParamUnittest</strong></a> the other day when looking at the source code for <a href="https://pypi.python.org/pypi/radon" rel="nofollow noreferrer">radon</a> (<a href="https://github.com/rubik/radon/blob/master/radon/tests/test_other_metrics.py" rel="nofollow noreferrer">example usage on the GitHub repository</a>). It should work with other frameworks that extend TestCase (like Nose).</p>\n<p>Here is an example:</p>\n<pre><code>import unittest\nimport paramunittest\n\n\n@paramunittest.parametrized(\n    (\'1\', \'2\'),\n    #(4, 3),    &lt;---- Uncomment to have a failing test\n    (\'2\', \'3\'),\n    ((\'4\', ), {\'b\': \'5\'}),\n    ((), {\'a\': 5, \'b\': 6}),\n    {\'a\': 5, \'b\': 6},\n)\nclass TestBar(TestCase):\n    def setParameters(self, a, b):\n        self.a = a\n        self.b = b\n\n    def testLess(self):\n        self.assertLess(self.a, self.b)\n</code></pre>\n'}, {'answer_id': 29384495, 'author': 'Bernhard', 'author_id': 639054, 'author_profile': 'https://Stackoverflow.com/users/639054', 'pm_score': 6, 'selected': False, 'text': '<p>As of Python 3.4, subtests have been introduced to <em>unittest</em> for this purpose. See <a href="https://docs.python.org/3/library/unittest.html#distinguishing-test-iterations-using-subtests" rel="noreferrer">the documentation</a> for details. TestCase.subTest is a context manager which allows one to isolate asserts in a test so that a failure will be reported with parameter information, but it does not stop the test execution. Here\'s the example from the documentation:</p>\n<pre><code>class NumbersTest(unittest.TestCase):\n\ndef test_even(self):\n    &quot;&quot;&quot;\n    Test that numbers between 0 and 5 are all even.\n    &quot;&quot;&quot;\n    for i in range(0, 6):\n        with self.subTest(i=i):\n            self.assertEqual(i % 2, 0)\n</code></pre>\n<p>The output of a test run would be:</p>\n<pre class="lang-none prettyprint-override"><code>======================================================================\nFAIL: test_even (__main__.NumbersTest) (i=1)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n  File &quot;subtests.py&quot;, line 32, in test_even\n    self.assertEqual(i % 2, 0)\nAssertionError: 1 != 0\n\n======================================================================\nFAIL: test_even (__main__.NumbersTest) (i=3)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n  File &quot;subtests.py&quot;, line 32, in test_even\n    self.assertEqual(i % 2, 0)\nAssertionError: 1 != 0\n\n======================================================================\nFAIL: test_even (__main__.NumbersTest) (i=5)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n  File &quot;subtests.py&quot;, line 32, in test_even\n    self.assertEqual(i % 2, 0)\nAssertionError: 1 != 0\n</code></pre>\n<p>This is also part of <a href="https://pypi.python.org/pypi/unittest2" rel="noreferrer">unittest2</a>, so it is available for earlier versions of Python.</p>\n'}, {'answer_id': 29766722, 'author': 'Mykhaylo Kopytonenko', 'author_id': 2726783, 'author_profile': 'https://Stackoverflow.com/users/2726783', 'pm_score': 4, 'selected': False, 'text': '<p>Use the <a href="https://technomilk.wordpress.com/2012/02/12/multiplying-python-unit-test-cases-with-different-sets-of-data/" rel="noreferrer">ddt</a> library. It adds simple decorators for the test methods:</p>\n\n<pre><code>import unittest\nfrom ddt import ddt, data\nfrom mycode import larger_than_two\n\n@ddt\nclass FooTestCase(unittest.TestCase):\n\n    @data(3, 4, 12, 23)\n    def test_larger_than_two(self, value):\n        self.assertTrue(larger_than_two(value))\n\n    @data(1, -3, 2, 0)\n    def test_not_larger_than_two(self, value):\n        self.assertFalse(larger_than_two(value))\n</code></pre>\n\n<p>This library can be installed with <code>pip</code>. It doesn\'t require <code>nose</code>, and works excellent with the standard library <code>unittest</code> module.</p>\n'}, {'answer_id': 30150971, 'author': 'sleepycal', 'author_id': 1267398, 'author_profile': 'https://Stackoverflow.com/users/1267398', 'pm_score': 1, 'selected': False, 'text': '<p>Just use metaclasses, as seen here;</p>\n\n<pre><code>class DocTestMeta(type):\n    """\n    Test functions are generated in metaclass due to the way some\n    test loaders work. For example, setupClass() won\'t get called\n    unless there are other existing test methods, and will also\n    prevent unit test loader logic being called before the test\n    methods have been defined.\n    """\n    def __init__(self, name, bases, attrs):\n        super(DocTestMeta, self).__init__(name, bases, attrs)\n\n    def __new__(cls, name, bases, attrs):\n        def func(self):\n            """Inner test method goes here"""\n            self.assertTrue(1)\n\n        func.__name__ = \'test_sample\'\n        attrs[func.__name__] = func\n        return super(DocTestMeta, cls).__new__(cls, name, bases, attrs)\n\nclass ExampleTestCase(TestCase):\n    """Our example test case, with no methods defined"""\n    __metaclass__ = DocTestMeta\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>test_sample (ExampleTestCase) ... OK\n</code></pre>\n'}, {'answer_id': 31161347, 'author': 'Kirill Ermolov', 'author_id': 4990113, 'author_profile': 'https://Stackoverflow.com/users/4990113', 'pm_score': 2, 'selected': False, 'text': '<p>I use metaclasses and decorators for generate tests. You can check my implementation <a href="https://github.com/erm0l0v/python_wrap_cases" rel="nofollow noreferrer">python_wrap_cases</a>. This library doesn\'t require any test frameworks.</p>\n<p>Your example:</p>\n<pre><code>import unittest\nfrom python_wrap_cases import wrap_case\n\n\n@wrap_case\nclass TestSequence(unittest.TestCase):\n\n    @wrap_case(&quot;foo&quot;, &quot;a&quot;, &quot;a&quot;)\n    @wrap_case(&quot;bar&quot;, &quot;a&quot;, &quot;b&quot;)\n    @wrap_case(&quot;lee&quot;, &quot;b&quot;, &quot;b&quot;)\n    def testsample(self, name, a, b):\n        print &quot;test&quot;, name\n        self.assertEqual(a, b)\n</code></pre>\n<p>Console output:</p>\n<pre class="lang-none prettyprint-override"><code>testsample_u\'bar\'_u\'a\'_u\'b\' (tests.example.test_stackoverflow.TestSequence) ... test bar\nFAIL\ntestsample_u\'foo\'_u\'a\'_u\'a\' (tests.example.test_stackoverflow.TestSequence) ... test foo\nok\ntestsample_u\'lee\'_u\'b\'_u\'b\' (tests.example.test_stackoverflow.TestSequence) ... test lee\nok\n</code></pre>\n<p>Also you may use <em>generators</em>. For example this code generate all possible combinations of tests with arguments <code>a__list</code> and <code>b__list</code></p>\n<pre><code>import unittest\nfrom python_wrap_cases import wrap_case\n\n\n@wrap_case\nclass TestSequence(unittest.TestCase):\n\n    @wrap_case(a__list=[&quot;a&quot;, &quot;b&quot;], b__list=[&quot;a&quot;, &quot;b&quot;])\n    def testsample(self, a, b):\n        self.assertEqual(a, b)\n</code></pre>\n<p>Console output:</p>\n<pre class="lang-none prettyprint-override"><code>testsample_a(u\'a\')_b(u\'a\') (tests.example.test_stackoverflow.TestSequence) ... ok\ntestsample_a(u\'a\')_b(u\'b\') (tests.example.test_stackoverflow.TestSequence) ... FAIL\ntestsample_a(u\'b\')_b(u\'a\') (tests.example.test_stackoverflow.TestSequence) ... FAIL\ntestsample_a(u\'b\')_b(u\'b\') (tests.example.test_stackoverflow.TestSequence) ... ok\n</code></pre>\n'}, {'answer_id': 33884166, 'author': 'Javier', 'author_id': 3339058, 'author_profile': 'https://Stackoverflow.com/users/3339058', 'pm_score': 3, 'selected': False, 'text': '<p>There\'s also <a href="https://pypi.python.org/pypi/hypothesis" rel="nofollow noreferrer">Hypothesis</a> which adds fuzz or property based testing.</p>\n<p>This is a very powerful testing method.</p>\n'}, {'answer_id': 34382688, 'author': 'Max Malysh', 'author_id': 1977620, 'author_profile': 'https://Stackoverflow.com/users/1977620', 'pm_score': 1, 'selected': False, 'text': '<p>You can use <code>TestSuite</code> and custom <code>TestCase</code> classes. </p>\n\n<pre><code>import unittest\n\nclass CustomTest(unittest.TestCase):\n    def __init__(self, name, a, b):\n        super().__init__()\n        self.name = name\n        self.a = a\n        self.b = b\n\n    def runTest(self):\n        print("test", self.name)\n        self.assertEqual(self.a, self.b)\n\nif __name__ == \'__main__\':\n    suite = unittest.TestSuite()\n    suite.addTest(CustomTest("Foo", 1337, 1337))\n    suite.addTest(CustomTest("Bar", 0xDEAD, 0xC0DE))\n    unittest.TextTestRunner().run(suite)\n</code></pre>\n'}, {'answer_id': 36788233, 'author': 'Danielle Weisz', 'author_id': 6239458, 'author_profile': 'https://Stackoverflow.com/users/6239458', 'pm_score': 1, 'selected': False, 'text': '<p>I\'d been having trouble with a very particular style of parameterized tests.  All our Selenium tests can run locally, but they also should be able to be run remotely against several platforms on SauceLabs.  Basically, I wanted to take a large amount of already-written test cases and parameterize them with the fewest changes to code possible.  Furthermore, I needed to be able to pass the parameters into the setUp method, something which I haven\'t seen any solutions for elsewhere.</p>\n\n<p>Here\'s what I\'ve come up with:</p>\n\n<pre><code>import inspect\nimport types\n\ntest_platforms = [\n    {\'browserName\': "internet explorer", \'platform\': "Windows 7", \'version\': "10.0"},\n    {\'browserName\': "internet explorer", \'platform\': "Windows 7", \'version\': "11.0"},\n    {\'browserName\': "firefox", \'platform\': "Linux", \'version\': "43.0"},\n]\n\n\ndef sauce_labs():\n    def wrapper(cls):\n        return test_on_platforms(cls)\n    return wrapper\n\n\ndef test_on_platforms(base_class):\n    for name, function in inspect.getmembers(base_class, inspect.isfunction):\n        if name.startswith(\'test_\'):\n            for platform in test_platforms:\n                new_name = \'_\'.join(list([name, \'\'.join(platform[\'browserName\'].title().split()), platform[\'version\']]))\n                new_function = types.FunctionType(function.__code__, function.__globals__, new_name,\n                                                  function.__defaults__, function.__closure__)\n                setattr(new_function, \'platform\', platform)\n                setattr(base_class, new_name, new_function)\n            delattr(base_class, name)\n\n    return base_class\n</code></pre>\n\n<p>With this, all I had to do was add a simple decorator @sauce_labs() to each regular old TestCase, and now when running them, they\'re wrapped up and rewritten, so that all the test methods are parameterized and renamed.  LoginTests.test_login(self) runs as LoginTests.test_login_internet_explorer_10.0(self), LoginTests.test_login_internet_explorer_11.0(self), and LoginTests.test_login_firefox_43.0(self), and each one has the parameter self.platform to decide what browser/platform to run against, even in LoginTests.setUp, which is crucial for my task since that\'s where the connection to SauceLabs is initialized.</p>\n\n<p>Anyway, I hope this might be of help to someone looking to do a similar "global" parameterization of their tests!</p>\n'}, {'answer_id': 37470261, 'author': 'pptime', 'author_id': 2590401, 'author_profile': 'https://Stackoverflow.com/users/2590401', 'pm_score': -1, 'selected': False, 'text': "<p>Besides using setattr, we can use <em>load_tests</em> with Python\xa03.2 and later.</p>\n<pre><code>class Test(unittest.TestCase):\n    pass\n\ndef _test(self, file_name):\n    open(file_name, 'r') as f:\n        self.assertEqual('test result',f.read())\n\ndef _generate_test(file_name):\n    def test(self):\n        _test(self, file_name)\n    return test\n\ndef _generate_tests():\n    for file in files:\n        file_name = os.path.splitext(os.path.basename(file))[0]\n        setattr(Test, 'test_%s' % file_name, _generate_test(file))\n\ntest_cases = (Test,)\n\ndef load_tests(loader, tests, pattern):\n    _generate_tests()\n    suite = TestSuite()\n    for test_class in test_cases:\n        tests = loader.loadTestsFromTestCase(test_class)\n        suite.addTests(tests)\n    return suite\n\nif __name__ == '__main__':\n    _generate_tests()\n    unittest.main()\n</code></pre>\n"}, {'answer_id': 38726022, 'author': 'S.Arora', 'author_id': 6665372, 'author_profile': 'https://Stackoverflow.com/users/6665372', 'pm_score': -1, 'selected': False, 'text': '<p>Following is my solution. I find this useful when:</p>\n<ol>\n<li><p>Should work for unittest.Testcase and unittest discover</p>\n</li>\n<li><p>Have a set of tests to be run for different parameter settings.</p>\n</li>\n<li><p>Very simple and no dependency on other packages</p>\n<pre><code> import unittest\n\n class BaseClass(unittest.TestCase):\n     def setUp(self):\n         self.param = 2\n         self.base = 2\n\n     def test_me(self):\n         self.assertGreaterEqual(5, self.param+self.base)\n\n     def test_me_too(self):\n         self.assertLessEqual(3, self.param+self.base)\n\n\n  class Child_One(BaseClass):\n     def setUp(self):\n         BaseClass.setUp(self)\n         self.param = 4\n\n\n  class Child_Two(BaseClass):\n     def setUp(self):\n         BaseClass.setUp(self)\n         self.param = 1\n</code></pre>\n</li>\n</ol>\n'}, {'answer_id': 39350898, 'author': 'mop', 'author_id': 1791024, 'author_profile': 'https://Stackoverflow.com/users/1791024', 'pm_score': 1, 'selected': False, 'text': "<p>This solution works with <code>unittest</code> and <code>nose</code> for Python 2 and Python 3:</p>\n\n<pre><code>#!/usr/bin/env python\nimport unittest\n\ndef make_function(description, a, b):\n    def ghost(self):\n        self.assertEqual(a, b, description)\n    print(description)\n    ghost.__name__ = 'test_{0}'.format(description)\n    return ghost\n\n\nclass TestsContainer(unittest.TestCase):\n    pass\n\ntestsmap = {\n    'foo': [1, 1],\n    'bar': [1, 2],\n    'baz': [5, 5]}\n\ndef generator():\n    for name, params in testsmap.iteritems():\n        test_func = make_function(name, params[0], params[1])\n        setattr(TestsContainer, 'test_{0}'.format(name), test_func)\n\ngenerator()\n\nif __name__ == '__main__':\n    unittest.main()\n</code></pre>\n"}, {'answer_id': 41010565, 'author': 'Arindam Roychowdhury', 'author_id': 1076965, 'author_profile': 'https://Stackoverflow.com/users/1076965', 'pm_score': 2, 'selected': False, 'text': '<pre><code>import unittest\n\ndef generator(test_class, a, b):\n    def test(self):\n        self.assertEqual(a, b)\n    return test\n\ndef add_test_methods(test_class):\n    # The first element of list is variable &quot;a&quot;, then variable &quot;b&quot;, then name of test case that will be used as suffix.\n    test_list = [[2,3, \'one\'], [5,5, \'two\'], [0,0, \'three\']]\n    for case in test_list:\n        test = generator(test_class, case[0], case[1])\n        setattr(test_class, &quot;test_%s&quot; % case[2], test)\n\n\nclass TestAuto(unittest.TestCase):\n    def setUp(self):\n        print \'Setup\'\n        pass\n\n    def tearDown(self):\n        print \'TearDown\'\n        pass\n\n_add_test_methods(TestAuto)  # It\'s better to start with underscore so it is not detected as a test itself\n\nif __name__ == \'__main__\':\n    unittest.main(verbosity=1)\n</code></pre>\n<p>RESULT:</p>\n<pre class="lang-none prettyprint-override"><code>&gt;&gt;&gt;\nSetup\nFTearDown\nSetup\nTearDown\n.Setup\nTearDown\n.\n======================================================================\nFAIL: test_one (__main__.TestAuto)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n  File &quot;D:/inchowar/Desktop/PyTrash/test_auto_3.py&quot;, line 5, in test\n    self.assertEqual(a, b)\nAssertionError: 2 != 3\n\n----------------------------------------------------------------------\nRan 3 tests in 0.019s\n\nFAILED (failures=1)\n</code></pre>\n'}, {'answer_id': 43851514, 'author': 'Patrick Ohly', 'author_id': 222305, 'author_profile': 'https://Stackoverflow.com/users/222305', 'pm_score': 0, 'selected': False, 'text': '<p>The metaclass-based answers still work in Python\xa03, but instead of the <code>__metaclass__</code> attribute, one has to use the <code>metaclass</code> parameter, as in:</p>\n<pre><code>class ExampleTestCase(TestCase,metaclass=DocTestMeta):\n    pass\n</code></pre>\n'}, {'answer_id': 45570424, 'author': 'YvesgereY', 'author_id': 995896, 'author_profile': 'https://Stackoverflow.com/users/995896', 'pm_score': 1, 'selected': False, 'text': '<p>Meta-programming is fun, but it can get in the way. Most solutions here make it difficult to:</p>\n<ul>\n<li>selectively launch a test</li>\n<li>point back to the code given the test\'s name</li>\n</ul>\n<p>So, my first suggestion is to follow the simple/explicit path (works with any test runner):</p>\n<pre><code>import unittest\n\nclass TestSequence(unittest.TestCase):\n\n    def _test_complex_property(self, a, b):\n        self.assertEqual(a,b)\n\n    def test_foo(self):\n        self._test_complex_property(&quot;a&quot;, &quot;a&quot;)\n    def test_bar(self):\n        self._test_complex_property(&quot;a&quot;, &quot;b&quot;)\n    def test_lee(self):\n        self._test_complex_property(&quot;b&quot;, &quot;b&quot;)\n\nif __name__ == \'__main__\':\n    unittest.main()\n</code></pre>\n<p>Since we shouldn\'t repeat ourselves, my second suggestion builds on <a href="https://stackoverflow.com/questions/32899/how-do-you-generate-dynamic-parameterized-unit-tests-in-python/23508426#23508426">Javier\'s answer</a>: embrace property based testing. Hypothesis library:</p>\n<ul>\n<li><p>is &quot;more relentlessly devious about test case generation than us mere humans&quot;</p>\n</li>\n<li><p>will provide simple count-examples</p>\n</li>\n<li><p>works with any test runner</p>\n</li>\n<li><p>has many more interesting features (statistics, additional test output, ...)</p>\n<p>class TestSequence(unittest.TestCase):</p>\n<pre><code>  @given(st.text(), st.text())\n  def test_complex_property(self, a, b):\n      self.assertEqual(a,b)\n</code></pre>\n</li>\n</ul>\n<p>To test your specific examples, just add:</p>\n<pre><code>    @example(&quot;a&quot;, &quot;a&quot;)\n    @example(&quot;a&quot;, &quot;b&quot;)\n    @example(&quot;b&quot;, &quot;b&quot;)\n</code></pre>\n<p>To run only one particular example, you can comment out the other examples (provided example will be run first). You may want to use <code>@given(st.nothing())</code>. Another option is to replace the whole block by:</p>\n<pre><code>    @given(st.just(&quot;a&quot;), st.just(&quot;b&quot;))\n</code></pre>\n<p>OK, you don\'t have distinct test names. But maybe you just need:</p>\n<ul>\n<li>a descriptive name of the property under test.</li>\n<li>which input leads to failure (falsifying example).</li>\n</ul>\n<p><a href="http://hypothesis.works/articles/how-not-to-die-hard-with-hypothesis" rel="nofollow noreferrer">Funnier example</a></p>\n'}, {'answer_id': 48452127, 'author': 'hhquark', 'author_id': 5932228, 'author_profile': 'https://Stackoverflow.com/users/5932228', 'pm_score': 0, 'selected': False, 'text': '<p>I had trouble making these work for <code>setUpClass</code>.</p>\n<p>Here\'s a version of <a href="https://stackoverflow.com/a/23508426/5932228">Javier\'s answer</a> that gives <code>setUpClass</code> access to dynamically allocated attributes.</p>\n<pre><code>import unittest\n\n\nclass GeneralTestCase(unittest.TestCase):\n    @classmethod\n    def setUpClass(cls):\n        print \'\'\n        print cls.p1\n        print cls.p2\n\n    def runTest1(self):\n        self.assertTrue((self.p2 - self.p1) == 1)\n\n    def runTest2(self):\n        self.assertFalse((self.p2 - self.p1) == 2)\n\n\ndef load_tests(loader, tests, pattern):\n    test_cases = unittest.TestSuite()\n    for p1, p2 in [(1, 2), (3, 4)]:\n        clsname = \'TestCase_{}_{}\'.format(p1, p2)\n        dct = {\n            \'p1\': p1,\n            \'p2\': p2,\n        }\n        cls = type(clsname, (GeneralTestCase,), dct)\n        test_cases.addTest(cls(\'runTest1\'))\n        test_cases.addTest(cls(\'runTest2\'))\n    return test_cases\n</code></pre>\n<h3>Outputs</h3>\n<pre class="lang-none prettyprint-override"><code>1\n2\n..\n3\n4\n..\n----------------------------------------------------------------------\nRan 4 tests in 0.000s\n\nOK\n</code></pre>\n'}, {'answer_id': 57378023, 'author': 'bcdan', 'author_id': 3325465, 'author_profile': 'https://Stackoverflow.com/users/3325465', 'pm_score': 1, 'selected': False, 'text': '<p>I have found that this works well for my purposes, especially if I need to generate tests that do slightly difference processes on a collection of data.</p>\n\n<pre><code>import unittest\n\ndef rename(newName):\n    def renamingFunc(func):\n        func.__name__ == newName\n        return func\n    return renamingFunc\n\nclass TestGenerator(unittest.TestCase):\n\n    TEST_DATA = {}\n\n    @classmethod\n    def generateTests(cls):\n        for dataName, dataValue in TestGenerator.TEST_DATA:\n            for func in cls.getTests(dataName, dataValue):\n                setattr(cls, "test_{:s}_{:s}".format(func.__name__, dataName), func)\n\n    @classmethod\n    def getTests(cls):\n        raise(NotImplementedError("This must be implemented"))\n\nclass TestCluster(TestGenerator):\n\n    TEST_CASES = []\n\n    @staticmethod\n    def getTests(dataName, dataValue):\n\n        def makeTest(case):\n\n            @rename("{:s}".format(case["name"]))\n            def test(self):\n                # Do things with self, case, data\n                pass\n\n            return test\n\n        return [makeTest(c) for c in TestCluster.TEST_CASES]\n\nTestCluster.generateTests()\n</code></pre>\n\n<p>The <code>TestGenerator</code> class can be used to spawn different sets of test cases like <code>TestCluster</code>.</p>\n\n<p><code>TestCluster</code> can be thought of as an implementation of the <code>TestGenerator</code> interface.</p>\n'}, {'answer_id': 58974546, 'author': 'thangaraj1980', 'author_id': 2707200, 'author_profile': 'https://Stackoverflow.com/users/2707200', 'pm_score': -1, 'selected': False, 'text': "<pre><code>import unittest\n\ndef generator(test_class, a, b,c,d,name):\n    def test(self):\n        print('Testexecution=',name)\n        print('a=',a)\n        print('b=',b)\n        print('c=',c)\n        print('d=',d)\n\n    return test\n\ndef add_test_methods(test_class):\n    test_list = [[3,3,5,6, 'one'], [5,5,8,9, 'two'], [0,0,5,6, 'three'],[0,0,2,3,'Four']]\n    for case in test_list:\n        print('case=',case[0], case[1],case[2],case[3],case[4])\n        test = generator(test_class, case[0], case[1],case[2],case[3],case[4])\n        setattr(test_class, &quot;test_%s&quot; % case[4], test)\n\n\nclass TestAuto(unittest.TestCase):\n    def setUp(self):\n        print ('Setup')\n        pass\n\n    def tearDown(self):\n        print ('TearDown')\n        pass\n\nadd_test_methods(TestAuto)\n\nif __name__ == '__main__':\n    unittest.main(verbosity=1)\n</code></pre>\n"}, {'answer_id': 62476654, 'author': 'Eric Cousineau', 'author_id': 7829525, 'author_profile': 'https://Stackoverflow.com/users/7829525', 'pm_score': 2, 'selected': False, 'text': '<p>This is effectively the same as <code>parameterized</code> as mentioned in a previous answer, but specific to <code>unittest</code>:</p>\n<pre class="lang-py prettyprint-override"><code>def sub_test(param_list):\n    &quot;&quot;&quot;Decorates a test case to run it as a set of subtests.&quot;&quot;&quot;\n\n    def decorator(f):\n\n        @functools.wraps(f)\n        def wrapped(self):\n            for param in param_list:\n                with self.subTest(**param):\n                    f(self, **param)\n\n        return wrapped\n\n    return decorator\n</code></pre>\n<p>Example usage:</p>\n<pre><code>class TestStuff(unittest.TestCase):\n    @sub_test([\n        dict(arg1=\'a\', arg2=\'b\'),\n        dict(arg1=\'x\', arg2=\'y\'),\n    ])\n    def test_stuff(self, arg1, arg2):\n        ...\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/32899', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/720/']