python unittest 和 pytest - 我可以将测试状态分配给变量吗

python unittest and pytest - can I assign test status to a variable

我正在开发一个基于 python 的测试系统,该系统迭代一组 python 测试并一个一个地 运行 它们(有 unittests 和 pytests)。

有没有一种方法可以让我的测试系统理解每个单独测试的结果并将其保存到一个字典中,例如键 [test_name] 和值 [test_status]。我想象如果测试的结果被分配给一个变量例如:

test_status = "passed"

PS:所有测试都有一个 main(),看起来像那样

# for unittests
def main():
    unittest.main()

# for pytests
def main():
    os.system("py.test -v {}".format(os.path.abspath(__file__)))

如果我理解正确,你想实际上运行 pytest 或 unittests 作为命令行工具 并检索结果。

执行此操作的直接方法是使用 JUnit xml output 并解析它。例如在 pytest 中:

pytest --junitxml=path

也许您想考虑使用像 Jenkins 这样的自动化服务器,它将 运行 unittests 和 pytest 分开测试,然后收集结果。

我找到了单元测试框架的解决方案:

想法是将测试输出数据更改为不在终端控制台上,而是更改为文件。一种方法是将以下代码添加到测试中:

if __name__ == '__main__':
    # terminal command to run a specific test and save its output to a log file
    # python [this_module_name] [log_file.log] [*tests]
    parser = argparse.ArgumentParser()
    parser.add_argument('test_log_file')
    parser.add_argument('unittest_args', nargs='*')

    args = parser.parse_args()

    log_file = sys.argv[1]
    # Now set the sys.argv to the unittest_args (leaving sys.argv[0] alone)
    sys.argv[1:] = args.unittest_args

    with open(log_file, "w") as f:
        runner = unittest.TextTestRunner(f)
        unittest.main(defaultTest=sys.argv[2:], exit=False, testRunner=runner)

和 运行 它使用这样的命令:

python my_tests.py log_file.log class_name.test_1 class_name.test_2 ... test_n

另一种方法是使用如下所示的直接命令:

python -m unittest [test_module_name].[test_class_name].[test_name] 2> [log_file_name]
# real command example:
python -m unittest my_tests.class_name.test_1 2> my_test_log_file.log
# real command example with multiple tests:
python -m unittest my_tests.class_name.test_1 my_tests.class_name.test_2 my_tests.class_name.test_3 2> my_test_log_file.log

最后一部分是写一个方法,读取这个日志文件并得到测试结果。这些日志文件看起来像这样:

.FEs
======================================================================
ERROR: test_simulative_error (__main__.SimulativeTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "unittest_tests.py", line 84, in test_simulative_error
    raise ValueError
ValueError

======================================================================
FAIL: test_simulative_fail (__main__.SimulativeTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "unittest_tests.py", line 81, in test_simulative_fail
    assert False
AssertionError

----------------------------------------------------------------------
Ran 4 tests in 0.001s

FAILED (failures=1, errors=1, skipped=1)

所以最后一步是打开 log_file 并阅读第一行,其中提供了 test/tests 如何完成的信息,并根据需要保存此信息。