unittest - 对输入和输出列表运行相同的测试

时间:2014-02-24 14:26:16

标签: python python-unittest

我有这个测试

import unittest

class TestName(unittest.TestCase):

        def setUp(self):
                self.name = "Bob"
                self.expected_name = "Bob"


        def test_name(self):
                # ... some operation over self.name
                print self.name
                self.assertEquals(self.name, self.expected_name)

if __name__ == '__main__':
        unittest.main(verbosity=2)

我如何运行测试实例?

对输入和输出列表(["Bob", "Alice", ...])运行相同的测试,可能像

TestName(name="Bob", expected_name="Bob")
TestName(name="Alice", expected_name="Alice")

2 个答案:

答案 0 :(得分:18)

查看DDT (Data-Driven/Decorated Tests)

DDT允许您通过使用不同的测试数据运行测试用例来使其成倍增加,使其显示为多个测试用例。

考虑这个例子,使用DDT:

import unittest

from ddt import ddt, data, unpack


@ddt
class TestName(unittest.TestCase):

        # simple decorator usage:
        @data(1, 2)
        def test_greater_than_zero(self, value):
            self.assertGreater(value, 0)

        # passing data in tuples to achieve the 
        # scenarios from your given example:
        @data(('Bob', 'Bob'), ('Alice', 'Alice'))
        @unpack
        def test_name(self, first_value, second_value):
            name, expected_name = first_value, second_value
            self.assertEquals(name, expected_name)

if __name__ == '__main__':
        unittest.main(verbosity=2)

我在上面的代码中定义了2个测试方法,但是将使用装饰器中提供的数据运行4个测试用例。

输出:

test_greater_than_zero_1 (__main__.TestName) ... ok
test_greater_than_zero_2 (__main__.TestName) ... ok
test_name_('Alice', 'Alice') (__main__.TestName) ... ok
test_name_('Bob', 'Bob') (__main__.TestName) ... ok

----------------------------------------------------------------------
Ran 4 tests in 0.000s

OK

答案 1 :(得分:2)

我会在这里使用mixin或元类,因为unittest会查找类,而不是实例。

class TestMixin (object):
    def test_name ():
        print self.name

class TestName (unittest.TestCase, TestMixin):
    ...