我已經找到了單元測試框架的解決方案:
的想法是改變測試輸出中的數據是不是在終端控制檯上,而是到一個文件中。做到這一點的方法之一是將以下代碼添加到測試:使用命令像這樣的
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和閱讀,讓信息如何測試/測試已經完成了第一線,只要你想保存這些信息。
爲什麼區分兩者? pytest應該可以運行unittest.py-style測試就好了。 –