python - 如何在 Python 中生成动态(参数化)单元测试?

我有一些测试数据,想为每个项目创建一个单元测试。我的第一个想法是这样做:

import unittest

l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]]

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

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

这样做的缺点是它在一次测试中处理所有数据。我想动态为每个项目生成一个测试。有什么建议吗?

最佳答案

这称为“参数化”。

有多种工具支持这种方法。例如:

  • pytest's decorator
  • parameterized

生成的代码如下所示:

from parameterized import parameterized

class TestSequence(unittest.TestCase):
    @parameterized.expand([
        ["foo", "a", "a",],
        ["bar", "a", "b"],
        ["lee", "b", "b"],
    ])
    def test_sequence(self, name, a, b):
        self.assertEqual(a,b)

这将生成测试:

test_sequence_0_foo (__main__.TestSequence) ... ok
test_sequence_1_bar (__main__.TestSequence) ... FAIL
test_sequence_2_lee (__main__.TestSequence) ... ok

======================================================================
FAIL: test_sequence_1_bar (__main__.TestSequence)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/site-packages/parameterized/parameterized.py", line 233, in <lambda>
    standalone_func = lambda *a: func(*(a + p.args), **p.kwargs)
  File "x.py", line 12, in test_sequence
    self.assertEqual(a,b)
AssertionError: 'a' != 'b'

由于历史原因,我将在 2008 年左右保留原始答案):

我使用这样的东西:

import unittest

l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]]

class TestSequense(unittest.TestCase):
    pass

def test_generator(a, b):
    def test(self):
        self.assertEqual(a,b)
    return test

if __name__ == '__main__':
    for t in l:
        test_name = 'test_%s' % t[0]
        test = test_generator(t[1], t[2])
        setattr(TestSequense, test_name, test)
    unittest.main()

https://stackoverflow.com/questions/32899/

相关文章:

linux - 如何使用 YUM 列出包的内容?

python - Python中的抽象方法

python - 如何在给定的图上绘制垂直线

linux - 如何在 Linux 上通过 FTP 递归下载文件夹

windows - 如何将 DOS/Windows 换行符 (CRLF) 转换为 Unix 换行符

linux - 使用 sed 删除空行

linux - 如何限制递归文件列表的深度?

python - 配置以便 pip install 可以从 github 工作

linux - 使用 openssl 从服务器获取证书

python - 从字符串创建 Pandas DataFrame