python - 单元测试中的for循环

标签 python unit-testing testing python-unittest

有没有办法告诉 python unittest 执行一个方法中的所有断言并显示它失败的所有情况,而不是在第一个失败时停止。

class MyTestCase(TestCase):
    def test_a(self):
        with open('testcase.txt') as ifile: 
            for iline in ifile:
                self.assertEqual(iline, 'it is a test!')

最佳答案

Python 3.4 引入了 subTest上下文管理器。你的代码看起来像

class MyTestCase(TestCase):
    def test_a(self):
        with open('testcase.txt') as ifile: 
            for iline in ifile:
                with self.subTest(line=iline):
                    self.assertEqual(iline, 'it is a test!')

在没有 subTest 的情况下实现这一点的丑陋方法是在 try block 中进行 self.assert* 调用,打印捕获的错误,如果至少有一个测试失败,则在循环后显式地引发 AssertionError

关于python - 单元测试中的for循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26458634/

相关文章:

python - Numpy Polyfit 或 X 和 Y 多维数组的任何拟合

python - 为什么在 python cv2.bitwise 中使用类似的源参数?示例 :cv2. bitwise_and(roi,roi,mask = mask_inv)

python - 在 Python 中向字典中的特定键添加值

python - sys.stdin 的模型?

testing - Golang Benchmark 表测试,我可以从b.Run()中提取func吗?

python - 使用 shell 命令更改正在运行的程序行为

node.js - 运行 mocha 时出现 TypeError : Describe is not a function.

iphone - SentTestCase 不会将 UnitTest 失败突出显示为代码中的错误

testing - 如何规划白盒测试

testing - 字符串输入的测试用例