2017-04-10 30 views
1

我正在研究一個基於python的測試系統,它通過一組python測試並逐一運行它們(有unittests和pytests)。Python單元測試和pytest - 我可以分配測試狀態到一個變量

有沒有一種方法可以讓我的測試系統瞭解每個單獨測試的結果,並將其保存到字典中,例如鍵[test_name]和值[test_status]。我可以想象,如果測試的結果被分配到例如變量:)所有的測試都具有主(,看起來像

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

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

爲什麼區分兩者? pytest應該可以運行unittest.py-style測試就好了。 –

回答

0

我已經找到了單元測試框架的解決方案:

的想法是改變測試輸出中的數據是不是在終端控制檯上,而是到一個文件中。做到這一點的方法之一是將以下代碼添加到測試:使用命令像這樣的

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和閱讀,讓信息如何測試/測試已經完成了第一線,只要你想保存這些信息。

1

如果我的理解:

test_status = "passed" 

PS正確的,你想實際運行 pytest或unittests作爲命令行工具並檢索結果。

直接的方法是使用JUnit xml輸出並解析它。例如,在pytest:

pytest --junitxml=path 

也許你要考慮使用一個自動化服務器一樣詹金斯,將單獨運行單元測試和pytest測試,然後收集結果。

+0

是的,我使用詹金斯。其實我已經解決了這個問題,在接下來的幾天裏,我有一點時間,我會在這裏發佈解決方案。 –