Python unittest:以编程方式生成多个测试?

时间:2010-05-09 19:52:11

标签: python tdd unit-testing

  

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

我有一个测试函数under_test和一组预期的输入/输出对:

[
(2, 332),
(234, 99213),
(9, 3),
# ...
]

我希望这些输入/输出对中的每一个都能用自己的test_*方法进行测试。这可能吗?

这是我想要的,但是将每个输入/输出对强制为单个测试:

class TestPreReqs(unittest.TestCase):

    def setUp(self):
        self.expected_pairs = [(23, 55), (4, 32)]

    def test_expected(self):
        for exp in self.expected_pairs:
            self.assertEqual(under_test(exp[0]), exp[1])

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

(另外,我真的希望将self.expected_pairs的定义放在setUp中吗?)

更新:尝试 doublep 的建议:

class TestPreReqs(unittest.TestCase):

    def setUp(self):
        expected_pairs = [
                          (2, 3),
                          (42, 11),
                          (3, None),
                          (31, 99),
                         ]

        for k, pair in expected_pairs:
            setattr(TestPreReqs, 'test_expected_%d' % k, create_test(pair))

    def create_test (pair):
        def do_test_expected(self):
            self.assertEqual(get_pre_reqs(pair[0]), pair[1])
        return do_test_expected


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

这不起作用。运行0次测试。我是否错误地调整了示例?

7 个答案:

答案 0 :(得分:47)

我必须做类似的事情。我创建了简单的TestCase子类,它们在__init__中获取了一个值,如下所示:

class KnownGood(unittest.TestCase):
    def __init__(self, input, output):
        super(KnownGood, self).__init__()
        self.input = input
        self.output = output
    def runTest(self):
        self.assertEqual(function_to_test(self.input), self.output)

然后我用这些值制作了一个测试套件:

def suite():
    suite = unittest.TestSuite()
    suite.addTests(KnownGood(input, output) for input, output in known_values)
    return suite

然后您可以从主方法运行它:

if __name__ == '__main__':
    unittest.TextTestRunner().run(suite())

这样做的好处是:

  • 当您添加更多值时,报告的测试数量会增加,这会让您感觉自己做得更多。
  • 每个单独的测试用例都可能单独失败
  • 它在概念上很简单,因为每个输入/输出值都转换为一个TestCase

答案 1 :(得分:32)

未经测试:

class TestPreReqs(unittest.TestCase):
    ...

def create_test (pair):
    def do_test_expected(self):
        self.assertEqual(under_test(pair[0]), pair[1])
    return do_test_expected

for k, pair in enumerate ([(23, 55), (4, 32)]):
    test_method = create_test (pair)
    test_method.__name__ = 'test_expected_%d' % k
    setattr (TestPreReqs, test_method.__name__, test_method)

如果你经常使用它,你可以通过使用效用函数和/或装饰器来解决这个问题。请注意,在此示例中,对不是TestPreReqs对象的属性(因此setUp已消失)。相反,它们在TestPreReqs类的某种意义上是“硬连线”。

答案 2 :(得分:25)

与Python一样,有一种复杂的方法可以提供简单的解决方案。

在这种情况下,我们可以使用元编程,装饰器和各种漂亮的Python技巧来实现一个不错的结果。以下是最终测试的结果:

import unittest

# some magic code will be added here later

class DummyTest(unittest.TestCase):
  @for_examples(1, 2)
  @for_examples(3, 4)
  def test_is_smaller_than_four(self, value):
    self.assertTrue(value < 4)

  @for_examples((1,2),(2,4),(3,7))
  def test_double_of_X_is_Y(self, x, y):
    self.assertEqual(2 * x, y)

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

执行此脚本时,结果为:

..F...F
======================================================================
FAIL: test_double_of_X_is_Y(3,7)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/xdecoret/Documents/foo.py", line 22, in method_for_example
    method(self, *example)
  File "/Users/xdecoret/Documents/foo.py", line 41, in test_double_of_X_is_Y
    self.assertEqual(2 * x, y)
AssertionError: 6 != 7

======================================================================
FAIL: test_is_smaller_than_four(4)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/xdecoret/Documents/foo.py", line 22, in method_for_example
    method(self, *example)
  File "/Users/xdecoret/Documents/foo.py", line 37, in test_is_smaller_than_four
    self.assertTrue(value < 4)
AssertionError

----------------------------------------------------------------------
Ran 7 tests in 0.001s

FAILED (failures=2)

实现了我们的目标:

  • 它不引人注目:我们像往常一样从TestCase派生
  • 我们只编写一次参数化测试
  • 每个示例值都被视为单独测试
  • 装饰器可以堆叠,因此很容易使用一组示例(例如,使用函数来构建示例文件或目录中的值列表)
  • 锦上添花,它适用于任意签名

那它是如何运作的。基本上,装饰器将示例存储在函数的属性中。我们使用元类用函数列表替换每个修饰函数。我们将unittest.TestCase替换为我们的新魔法代码(将粘贴在上面的“魔术”评论中):

__examples__ = "__examples__"

def for_examples(*examples):
    def decorator(f, examples=examples):
      setattr(f, __examples__, getattr(f, __examples__,()) + examples)
      return f
    return decorator

class TestCaseWithExamplesMetaclass(type):
  def __new__(meta, name, bases, dict):
    def tuplify(x):
      if not isinstance(x, tuple):
        return (x,)
      return x
    for methodname, method in dict.items():
      if hasattr(method, __examples__):
        dict.pop(methodname)
        examples = getattr(method, __examples__)
        delattr(method, __examples__)
        for example in (tuplify(x) for x in examples):
          def method_for_example(self, method = method, example = example):
            method(self, *example)
          methodname_for_example = methodname + "(" + ", ".join(str(v) for v in example) + ")"
          dict[methodname_for_example] = method_for_example
    return type.__new__(meta, name, bases, dict)

class TestCaseWithExamples(unittest.TestCase):
  __metaclass__ = TestCaseWithExamplesMetaclass
  pass

unittest.TestCase = TestCaseWithExamples

如果有人想要很好地打包,或者提出一个针对unittest的补丁,请随意!我的名字的引用将不胜感激。

- 编辑--------

如果您准备使用帧内省(导入sys模块),代码可以更简单并完全封装在装饰器中

def for_examples(*parameters):

  def tuplify(x):
    if not isinstance(x, tuple):
      return (x,)
    return x

  def decorator(method, parameters=parameters):
    for parameter in (tuplify(x) for x in parameters):

      def method_for_parameter(self, method=method, parameter=parameter):
        method(self, *parameter)
      args_for_parameter = ",".join(repr(v) for v in parameter)
      name_for_parameter = method.__name__ + "(" + args_for_parameter + ")"
      frame = sys._getframe(1)  # pylint: disable-msg=W0212
      frame.f_locals[name_for_parameter] = method_for_parameter
    return None
  return decorator

答案 3 :(得分:11)

鼻子(由@Paul Hankin建议)

#!/usr/bin/env python
# file: test_pairs_nose.py
from nose.tools import eq_ as eq

from mymodule import f

def test_pairs(): 
    for input, output in [ (2, 332), (234, 99213), (9, 3), ]:
        yield _test_f, input, output

def _test_f(input, output):
    try:
        eq(f(input), output)
    except AssertionError:
        if input == 9: # expected failure
            from nose.exc import SkipTest
            raise SkipTest("expected failure")
        else:
            raise

if __name__=="__main__":
   import nose; nose.main()

示例:

$ nosetests test_pairs_nose -v
test_pairs_nose.test_pairs(2, 332) ... ok
test_pairs_nose.test_pairs(234, 99213) ... ok
test_pairs_nose.test_pairs(9, 3) ... SKIP: expected failure

----------------------------------------------------------------------
Ran 3 tests in 0.001s

OK (SKIP=1)

unittest(类似于@doublep's one的方法)

#!/usr/bin/env python
import unittest2 as unittest
from mymodule import f

def add_tests(generator):
    def class_decorator(cls):
        """Add tests to `cls` generated by `generator()`."""
        for f, input, output in generator():
            test = lambda self, i=input, o=output, f=f: f(self, i, o)
            test.__name__ = "test_%s(%r, %r)" % (f.__name__, input, output)
            setattr(cls, test.__name__, test)
        return cls
    return class_decorator

def _test_pairs():
    def t(self, input, output):
        self.assertEqual(f(input), output)

    for input, output in [ (2, 332), (234, 99213), (9, 3), ]:
        tt = t if input != 9 else unittest.expectedFailure(t)
        yield tt, input, output

class TestCase(unittest.TestCase):
    pass
TestCase = add_tests(_test_pairs)(TestCase)

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

示例:

$ python test_pairs_unit2.py -v
test_t(2, 332) (__main__.TestCase) ... ok
test_t(234, 99213) (__main__.TestCase) ... ok
test_t(9, 3) (__main__.TestCase) ... expected failure

----------------------------------------------------------------------
Ran 3 tests in 0.000s

OK (expected failures=1)

如果您不想安装unittest2,请添加:

try:    
    import unittest2 as unittest
except ImportError:
    import unittest
    if not hasattr(unittest, 'expectedFailure'):
       import functools
       def _expectedFailure(func):
           @functools.wraps(func)
           def wrapper(*args, **kwargs):
               try:
                   func(*args, **kwargs)
               except AssertionError:
                   pass
               else:
                   raise AssertionError("UnexpectedSuccess")
           return wrapper
       unittest.expectedFailure = _expectedFailure    

答案 4 :(得分:6)

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

有关此问题的更多答案,另请参阅question 1676269

答案 5 :(得分:2)

答案 6 :(得分:1)

我认为Rory的解决方案是最干净,最短的。但是,doublep的“在TestCase中创建合成函数”的这种变化也有效:

from functools import partial
class TestAllReports(unittest.TestCase):
    pass

def test_spamreport(name):
    assert classify(getSample(name))=='spamreport', name

for rep in REPORTS:
    testname = 'test_'+rep
    testfunc = partial(test_spamreport, rep)
    testfunc.__doc__ = testname
    setattr( TestAllReports, testname, testfunc )

if __name__=='__main__':
    unittest.main(argv=sys.argv + ['--verbose'])