【问题标题】:Python unittest: Run multiple assertions in a loop without failing at first one, but continuePython unittest:在循环中运行多个断言而第一个断言没有失败,但继续
【发布时间】:2014-04-22 22:17:27
【问题描述】:

场景: 我的一个测试用例是执行一个带有几个输入文件和一个特定输出的 shell 程序。我想测试这些输入/输出的不同变体,每个变体都保存在自己的文件夹中,即文件夹结构

/testA
/testA/inputX
/testA/inputY
/testA/expected.out
/testB
/testB/inputX
/testB/inputY
/testB/expected.out
/testC/
...

这是我运行此测试的代码:

def test_folders(self):
    tfolders = glob.iglob(os.environ['testdir'] + '/test_*')                
    for testpath in tfolders:
        testname = os.path.basename(testpath)
        self.assertTrue(self.runTest(testname))

在这种情况下,testname 是“testX”。它使用该文件夹中的inputs 执行外部程序,并将其与同一文件夹中的expected.out 进行比较。

问题: 一旦遇到失败的测试,测试就会停止并获得:

Could not find or read expected output file: C:/PROJECTS/active/CMDR-Test/data/test_freeTransactional/expected.out
======================================================================
FAIL: test_folders (cmdr-test.TestValidTypes)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\PROJECTS\active\CMDR-Test\cmdr-test.py", line 52, in test_folders
    self.assertTrue(self.runTest(testname))
AssertionError: False is not true

问题: 我如何让它继续其余的测试并显示有多少失败? (本质上是动态创建一个单元测试并执行它)

谢谢

【问题讨论】:

标签: python unit-testing testing assertions python-unittest


【解决方案1】:

这样的事情怎么样?

def test_folders(self):
    tfolders = glob.iglob(os.environ['testdir'] + '/test_*')    

    failures = []    
    for testpath in tfolders:
        testname = os.path.basename(testpath)
        if not self.runTest(testname):
            failures.append[testname]

    self.assertEqual([], failures)

【讨论】:

  • 如果它告诉我哪个 testname(s) 具体失败了,那就太棒了。
  • 我已经修改了代码示例。消息现在应该显示不同的元素(失败)。
【解决方案2】:

将 assert 语句放在 try 块中,循环将完全迭代,即使断言失败:

 try:
    assert statement
except
    print("exception occurred!!")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-10
    • 2011-10-13
    • 2020-04-08
    • 1970-01-01
    相关资源
    最近更新 更多