编写可重用(参数化)unittest.TestCase方法

时间:2009-11-04 20:04:43

标签: python unit-testing testcase parameterized-unit-test

  

可能重复:
  How to generate dynamic (parametrized) unit tests in python?

我正在使用unittest包编写测试,我想避免重复代码。我将进行一些测试,这些测试都需要一个非常类似的方法,但每次只有一个值不同。一个简单而无用的例子是:

class ExampleTestCase(unittest.TestCase):

    def test_1(self):
        self.assertEqual(self.somevalue, 1)

    def test_2(self):
        self.assertEqual(self.somevalue, 2)

    def test_3(self):
        self.assertEqual(self.somevalue, 3)

    def test_4(self):
        self.assertEqual(self.somevalue, 4)

有没有办法在不重复所有代码的情况下编写上面的示例,而是编写通用方法,例如

    def test_n(self, n):
        self.assertEqual(self.somevalue, n)

告诉unittest用不同的输入尝试这个测试?

6 个答案:

答案 0 :(得分:11)

可用于在Python中进行参数化测试的一些工具是:

答案 1 :(得分:3)

如果你真的想拥有多个unitttest,那么你需要多种方法。获得它的唯一方法是通过某种代码生成。你可以通过元类来完成,或者通过在定义之后调整类,包括(如果你使用的是Python 2.6)通过类装饰器。

这是一个寻找特殊'multitest'和'multitest_values'成员的解决方案,并使用它们来动态构建测试方法。不优雅,但它大致与你想要的一样:

import unittest
import inspect

class SomeValue(object):
    def __eq__(self, other):
        return other in [1, 3, 4]

class ExampleTestCase(unittest.TestCase):
    somevalue = SomeValue()

    multitest_values = [1, 2, 3, 4]
    def multitest(self, n):
        self.assertEqual(self.somevalue, n)

    multitest_gt_values = "ABCDEF"
    def multitest_gt(self, c):
        self.assertTrue(c > "B", c)


def add_test_cases(cls):
    values = {}
    functions = {}
    # Find all the 'multitest*' functions and
    # matching list of test values.
    for key, value in inspect.getmembers(cls):
        if key.startswith("multitest"):
            if key.endswith("_values"):
                values[key[:-7]] = value
            else:
                functions[key] = value

    # Put them together to make a list of new test functions.
    # One test function for each value
    for key in functions:
        if key in values:
            function = functions[key]
            for i, value in enumerate(values[key]):
                def test_function(self, function=function, value=value):
                    function(self, value)
                name ="test%s_%d" % (key[9:], i+1)
                test_function.__name__ = name
                setattr(cls, name, test_function)

add_test_cases(ExampleTestCase)

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

这是我运行时的输出

% python stackoverflow.py
.F..FF....
======================================================================
FAIL: test_2 (__main__.ExampleTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "stackoverflow.py", line 34, in test_function
    function(self, value)
  File "stackoverflow.py", line 13, in multitest
    self.assertEqual(self.somevalue, n)
AssertionError: <__main__.SomeValue object at 0xd9870> != 2

======================================================================
FAIL: test_gt_1 (__main__.ExampleTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "stackoverflow.py", line 34, in test_function
    function(self, value)
  File "stackoverflow.py", line 17, in multitest_gt
    self.assertTrue(c > "B", c)
AssertionError: A

======================================================================
FAIL: test_gt_2 (__main__.ExampleTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "stackoverflow.py", line 34, in test_function
    function(self, value)
  File "stackoverflow.py", line 17, in multitest_gt
    self.assertTrue(c > "B", c)
AssertionError: B

----------------------------------------------------------------------
Ran 10 tests in 0.001s

FAILED (failures=3)

您可以立即看到代码生成时出现的一些问题。 “test_gt_1”来自哪里?我可以将名称更改为更长的“test_multitest_gt_1”,但接着哪个测试为1?这里更好的是从_0而不是_1开始,也许在你的情况下你知道这些值可以用作Python函数名。

我不喜欢这种做法。我一直致力于自动生成测试方法的代码库(在一种情况下使用元类),并发现它比理解起来要难得多。当测试失败时,很难弄清楚失败案例的来源,并且很难坚持调试代码来探究失败的原因。

(我在这里写的示例中的调试失败并不像我必须使用的特定元类方法那么难。)

答案 2 :(得分:1)

我想你想要的是“参数化测试”。

我不认为unittest模块支持这个(不幸的是), 但如果我添加此功能,它将看起来像这样:

# Will run the test for all combinations of parameters
@RunTestWith(x=[0, 1, 2, 3], y=[-1, 0, 1])
def testMultiplication(self, x, y):
  self.assertEqual(multiplication.multiply(x, y), x*y)

使用现有的unittest模块,像这样的简单装饰器将无法多次“复制”测试,但我认为这是可行的,使用装饰器和元类的组合(元类应该观察所有'测试*'方法和复制(在不同的自动生成的名称下)应用装饰器的那些。)

答案 3 :(得分:1)

更加注重数据的方法可能比Andrew Dalke answer中使用的方法更清晰:

"""Parametrized unit test.

Builds a single TestCase class which tests if its
  `somevalue` method is equal to the numbers 1 through 4.

This is accomplished by
  creating a list (`cases`)
  of dictionaries which contain test specifications
  and then feeding the list to a function which creates a test case class.

When run, the output shows that three of the four cases fail,
  as expected:

>>> import sys
>>> from unittest import TextTestRunner
>>> run_tests(TextTestRunner(stream=sys.stdout, verbosity=9))
... # doctest: +ELLIPSIS
Test if self.somevalue equals 4 ... FAIL
Test if self.somevalue equals 1 ... FAIL
Test if self.somevalue equals 3 ... FAIL
Test if self.somevalue equals 2 ... ok
<BLANKLINE>
======================================================================
FAIL: Test if self.somevalue equals 4
----------------------------------------------------------------------
Traceback (most recent call last):
  ...
AssertionError: 2 != 4
<BLANKLINE>
======================================================================
FAIL: Test if self.somevalue equals 1
----------------------------------------------------------------------
Traceback (most recent call last):
  ...
AssertionError: 2 != 1
<BLANKLINE>
======================================================================
FAIL: Test if self.somevalue equals 3
----------------------------------------------------------------------
Traceback (most recent call last):
  ...
AssertionError: 2 != 3
<BLANKLINE>
----------------------------------------------------------------------
Ran 4 tests in ...s
<BLANKLINE>
FAILED (failures=3)
"""

from unittest import TestCase, TestSuite, defaultTestLoader

cases = [{'name': "somevalue_equals_one",
          'doc': "Test if self.somevalue equals 1",
          'value': 1},
         {'name': "somevalue_equals_two",
          'doc': "Test if self.somevalue equals 2",
          'value': 2},
         {'name': "somevalue_equals_three",
          'doc': "Test if self.somevalue equals 3",
          'value': 3},
         {'name': "somevalue_equals_four",
          'doc': "Test if self.somevalue equals 4",
          'value': 4}]

class BaseTestCase(TestCase):
    def setUp(self):
        self.somevalue = 2

def test_n(self, n):
    self.assertEqual(self.somevalue, n)

def make_parametrized_testcase(class_name, base_classes, test_method, cases):
    def make_parametrized_test_method(name, value, doc=None):
        def method(self):
            return test_method(self, value)
        method.__name__ = "test_" + name
        method.__doc__ = doc
        return (method.__name__, method)

    test_methods = (make_parametrized_test_method(**case) for case in cases)
    class_dict = dict(test_methods)
    return type(class_name, base_classes, class_dict)


TestCase = make_parametrized_testcase('TestOneThroughFour',
                                      (BaseTestCase,),
                                      test_n,
                                      cases)

def make_test_suite():
    load = defaultTestLoader.loadTestsFromTestCase
    return TestSuite(load(TestCase))

def run_tests(runner):
    runner.run(make_test_suite())

if __name__ == '__main__':
    from unittest import TextTestRunner
    run_tests(TextTestRunner(verbosity=9))

我不确定巫妖是如何参与确定测试运行的顺序,但doctest至少一直为我传递。

对于更复杂的情况,可以用包含参数列表和关键字参数字典的元组替换values字典的cases元素。虽然在那时你基本上是在python中编写lisp。

答案 4 :(得分:0)

也许是这样的:

def test_many(self):
    for n in range(0,1000):
        self.assertEqual(self.somevalue, n)

答案 5 :(得分:0)

编写一个测试方法,执行所有测试并捕获所有结果,将自己的诊断消息写入stderr,如果任何子测试失败,则测试失败:

def test_with_multiple_parameters(self):
    failed = False
    for k in sorted(self.test_parameters.keys()):
        if not self.my_test(self.test_parameters[k]):
           print >> sys.stderr, "Test {0} failed.".format(k)
           failed = True
    self.assertFalse(failed)            

请注意,my_test()的名称当然不能以test开头。