Python Testing how to run parameterised Testcases and pass a parameter to setupClass

renzop picture renzop · Mar 3, 2016 · Viewed 7.7k times · Source

I have an python unitest. In the setupClass method I so some timeconsuming tasks... The tests itself run very fast. Now i would like to run the same Testcase with multiple sets of parameters. How can I achieve this?

I ve tried differet approaches with nose_parameterized etc. but there i cant use the @parameterized.expand()

import unittest
from nose_parameterized import parameterized


parameters = [('test1', 2 ),('test2', 3)]


class TestParameterizedTestcase(unittest.TestCase):
    @classmethod
    def setUpClass(cls, param=1):
        """
        Do some expensive stuff
        """
        cls.param = param
        print 'Param in setup class  %s'


    def test_is_one(self):
        """
        A fast test
        """
        self.assertEqual(1,self.param)

    def test_is_two(self):
        """
        Another fast test
        """
        self.assertEqual(2, self.param)

    def test_is_three(self):
        """
        Another fast test
        """
        self.assertEqual(3, self.param)

Answer

David Wolever picture David Wolever · Mar 3, 2016

Unfortunately there isn't any way to create parameterized test classes with either unittest, nose, or parameterized.

py.test has an example showing how you can build your own parameterized test class, here: https://pytest.org/latest/example/parametrize.html#a-quick-port-of-testscenarios

And you can build your own parameterized class generator like this:

class MyTestClassBase(object):
    # Inherit from `object` so unittest doesn't think these are tests which
    # should be run

    @classmethod
    def setUpClass(cls):
        print "doing expensive setup with", cls.param

    def test_one(self):
        self.assertEqual(self.param, 1)


params = [('test1', 1), ('test2', 2)]

for name, param in params:
    cls_name = "TestMyTestClass_%s" %(name, )
    globals()[cls_name] = type(cls_name, (MyTestClassBase, unittest.TestCase), {
        "param": param,
    })

Which will generate a new test class for each paramter.