python - Django 测试 - 打印一系列 n 次相同测试的所有测试失败

标签 python django unit-testing django-unittest

我希望测试用例中的每个断言测试都经过实际测试,即使第一个测试失败。在我的情况下,所有断言都具有相同的性质。

实际上,我有一些东西可以评估以 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)

=> 我想看到打印的所有不在 list_of_all_variables 中的变量!

这对于我检查所有所谓的公式并能够纠正错误是必要的。

更多背景信息:

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

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

这样,我就有了n个测试,对应于n个不同的id。这是第一步,但我想要的是这些测试中的每个断言都得到测试,并打印相应的断言错误。

最佳答案

如问题 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)

关于python - Django 测试 - 打印一系列 n 次相同测试的所有测试失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26505627/

相关文章:

Django - 模板中的变量没有空格

python - Python 生成器函数中的代码重复

python - "ValueError: A given column is not a column of the dataframe"尝试将分类特征转换为数值时

javascript - 为 HTML5 Django 网络应用程序实现实时通知系统

java - 如何为 MockServer 的相同请求设置不同的响应?

unit-testing - Grails 测试应用程序类路径

android - 如何使用 jMock ClassImposterizer 进行 Android 单元测试?

python - Jupyter 笔记本错误

python - 简单来说,pyglet 和 pygame 之间的区别?

django - 如何在 django 项目中使用 Selenium(LiveServerTestCase) 并行运行测试?