Django测试 - 在同一测试的n次打印中打印所有测试失败

时间:2014-10-22 10:41:37

标签: python django unit-testing django-unittest

我希望TestCase中的每个断言测试都经过实际测试,即使第一个测试失败也是如此。在我看来,所有的断言都具有相同的性质。

实际上我有一些东西可以评估写成Python对象的公式(把它看作是写成字符串的公式eval' d)。我想做类似的事情:

class MyTest(TestCase):
   def test_something(self):
       for id in ids:
           for expression in get_formulas(id):
                for variable in extract_variables(expression):
                    self.assertIn(variable, list_of_all_variables)

=>我希望看到打印的所有variable都不在list_of_all_variables

这对我来说是必要的,我可以检查所有我所谓的公式,并能够纠正错误。

更多上下文:

我要在一个应用中执行可变数量的测试(取决于在版本化数据文件中写入的ID列表)。

为了拥有可变数量的TestCase实例,我确实编写了一个基类(mixin),然后使用3-args type函数(即创建类)构建了动态类。

这样,我有n个测试,对应n个不同的ID。这是第一步,但我想要的是,那些测试中的每个断言都会被测试,相应的断言错误会被打印出来。

1 个答案:

答案 0 :(得分:1)

如问题Continuing in Python's unittest when an assertion fails中所述,断言错误失败是TestCase类的硬编码行为。

因此,我没有改变它的行为,而是以下列风格为我的类生成了许多不同的test_...方法:

from django.test import TestCase
from sys import modules


# The list of all objects against which the tests have to be performed
formids = [12,124,234]
# get_formulas returns a list of formulas I have to test independently, linked to a formid
formulas = {id: get_formulas(id) for id in formids}

current_module = sys.modules(__name__)

def test_formula_method(self, formula):
    # Does some assertions
    self.assertNotEqual(formula.id, 0)

for formid in formids:
    attrs = {'formid': formid}
    for f in formulas[formid]:
        # f=f so the 2nd arg to test_formula_method is staying local
        # and not overwritten by last one in loop
        attrs['test_formula_%s' % f.name] = lambda self, f=f: test_formula_method(self, f)

    klass_name = "TestForm%s" % formid
    klass = type(klass_name, (TestCase,), attrs)

    setattr(current_module, klass_name, klass)