Python unittest:在循环中运行多个断言,不在第一个失败时停止继续
场景:
我有一个测试案例,它需要运行一个外部程序,并且会用到几个输入文件和一个特定的输出结果。我想测试这些输入和输出的不同组合,每种组合都保存在自己的文件夹里,也就是说有一个文件夹结构。
/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))
在这个例子中,测试名称是“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
问题:
我该如何让它继续执行剩下的测试,并显示有多少个测试失败了?
(实际上就是动态创建一个单元测试并执行它)
谢谢
2 个回答
0
把断言语句放在一个尝试块里,这样即使断言失败,循环也会完全执行完。
try:
assert statement
except
print("exception occurred!!")
7
这样做怎么样呢?
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)