Python测试如何运行参数化的测试用例并将参数传递给setupClass

时间:2016-03-03 13:47:52

标签: python python-unittest parameterized-unit-test nose-parameterized

我有一个python unitest。在setupClass方法中,我需要一些时间来完成任务......测试本身运行得非常快。现在我想用多组参数运行相同的Testcase。我怎样才能做到这一点?

我尝试过使用nose_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)

2 个答案:

答案 0 :(得分:4)

很遗憾,没有任何方法可以使用unittestnoseparameterized创建参数化测试类。

py.test有一个示例,展示了如何构建自己的参数化测试类,例如:https://pytest.org/latest/example/parametrize.html#a-quick-port-of-testscenarios

你可以像这样构建自己的参数化类生成器:

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,
    })

这将为每个参数生成一个新的测试类。

答案 1 :(得分:1)

这是使用unittest进行完整性的一种方法,但我更喜欢戴维斯的答案。

导入unittest 来自nose_parameterized导入参数化

class TestParameterizedTestcase(unittest.TestCase):
    param =3
    @classmethod
    def setUpClass(cls):
        """
        Do some expensive stuff
        """

        print 'Param in setup class  %s' % cls.param


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

    def test_is_two(self):
        """
        Anoter Fast test
        """
        self.assertEqual(2, self.param)

import unittest
from unittest import TestLoader

if __name__ == '__main__':
    for param in range(5):
        suite = unittest.TestSuite()
        loader = TestLoader()
        test = None
        test = TestParameterizedTestcase
        test.param =param

        tests = loader.loadTestsFromTestCase(test)
        suite.addTest(tests)
        unittest.TextTestRunner().run(suite)