gpt4 book ai didi

python - 使用 "assert"从一个函数运行 python 中的所有测试文件,而不会在测试失败时退出 "for loop"

转载 作者:太空宇宙 更新时间:2023-11-03 16:29:32 25 4
gpt4 key购买 nike

我正在开发测试运行程序,它从给定目录读取“.test”文件。

“.test”的结构是:

---TEMPLATE---
template content
---CONTEXT---
context to render on template
---RESULT---
expected result of the template.

有“n”个。我的测试目录中的测试文件。我存储测试号。字典“tests”中的 .test 文件作为其键,.test 文件的名称作为其值。

之后迭代字典“tests”并读取.test文件的内容并将它们存储在变量中。

---TEMPLATE--- part in "template_string",
---CONTEXT--- part in "context_string", and
---RESULT--- part in "expected_result"

然后使用 jinja2.Environment 类渲染 template_string 和 context_string 并将它们存储在“结果”变量中。

将“结果”与“expected_result”进行比较。

当前测试运行程序代码:

class TestTempates(TestCase):
def test_method(self):
tests = { dictionary of .test file }
results = {} #to store status of test case at there index (pass or error).
env = jinja2.Environment()
passed = 0
error = 0
for index, fname in tests.items():
file_path = dirpath + os.sep + fname
with open(file_path) as f:
# logic to read file content
template_string = #content of ---TEMPLATE--- part from file
context_string = #content of ---CONTEXT--- part from file
expected_result = #content of ---RESULT--- part from file
template = env.from_string(template_string)
context = json.loads(context_string)
result = template.render(context)

if result == expected_result:
results[index] = "Pass"
passed += 1
else:
sep = "-----------------------------"
error = "Error: results mismatch:\n%s\n%s\n%s\n%s" % \
(sep, result, sep, expected_result)
results[index] = error
errors += 1

将“result”和“expected_result”与“if else”条件进行比较工作正常。但现在我想使用“assert”或“assertEquals”,当任何测试文件“结果”与“expected_result”不匹配时,不退出“for循环”,直到所有测试文件都没有执行。因此,我可以在 Travis CI 中使用我的测试运行器,这样当任何测试用例失败时 Travis 构建都会失败。

在当前情况下,Travis CI 构建不会因测试用例失败而失败。

最佳答案

您可以按照下面的代码片段来解决您的问题。

suite = unittest.TestSuite()

def test_main(self):
self.assertEquals(self.result, self.expected_output)


def test_method(self):
"""
"""
# -- code to get tests objects to have all .tests content
for index, fname in tests.items():
# get result and expected_output value
obj = type('Test', (unittest.TestCase,), {'test_main': test_main,
'result':result, 'expected_output':expected_output})

suite.addTest(obj('test_main'))

unittest.TextTestRunner(verbosity=2).run(suite)

关于python - 使用 "assert"从一个函数运行 python 中的所有测试文件,而不会在测试失败时退出 "for loop",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37719570/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com