【问题标题】:unittest - run the same test for a list of inputs and outputs [duplicate]unittest - 对输入和输出列表运行相同的测试[重复]
【发布时间】:2014-02-24 14:26:15
【问题描述】:

我有这个测试

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")

【问题讨论】:

标签: python python-unittest


【解决方案1】:

查看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

【讨论】:

  • 如果我的测试输入存储在变量(例如列表)中,这将如何工作?
【解决方案2】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-25
    • 2018-09-13
    • 2022-08-04
    • 2018-10-10
    • 1970-01-01
    • 2019-09-09
    相关资源
    最近更新 更多