我找到了一个unittest框架的解决方案:
其思想是将测试输出数据更改为不在终端控制台上,而是改为一个文件。一种方法是将以下代码添加到测试中: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)
然后用这样的命令运行它:
^{pr2}$
另一种方法是使用如下所示的直接命令: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)
因此,最后一步是打开日志文件并读取第一行,该行提供了测试/测试如何完成的信息,并根据需要保存这些信息。在