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

2024-05-01 21:39:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在开发一个测试运行程序,它从给定的目录中读取“.test”文件。你知道吗

“.test”的结构是:

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

我的测试目录中有'n'个测试文件。 我在字典“tests”中存储.test文件的test编号作为它的键,.test文件的名称作为它的值。你知道吗

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

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

然后使用jinja2.Environment类呈现带有上下文字符串的模板字符串,并将它们存储在“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

将“结果”和“预期结果”与“如果其他”条件进行比较是可行的。 但是现在我想使用“assert”或“assertEquals”而不退出“for循环”,当任何测试文件“result”与“expected\u result”不匹配时,直到所有测试文件都没有执行为止。 所以,我可以在Travis CI中使用我的测试运行程序,这样当任何测试用例失败时,Travis构建都会失败。你知道吗

在当前情况下,travisci构建并没有因为测试用例失败而失败。你知道吗


Tags: 文件ofinteststringindexcontexttests
1条回答
网友
1楼 · 发布于 2024-05-01 21:39:44

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

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)

相关问题 更多 >