簡介:
python 主流自動化測試報告插件有三個:HTMLTestRunner、BeautifulReport 和 Allure。HTMLTestRunner是一個比較古老的報告模板,界面也不是很好看。BeautifulReport 界面很簡潔,看起來也很直觀,是一款比較不錯的報告插件。如果你想提升一下你的level,讓你的自動化測試報告變得高大上,那么請選擇 Allure 。
Allure測試報告介紹
Allure是一款非常輕量級並且非常靈活的開源測試報告生成框架。 它支持絕大多數測試框架, 例如TestNG、Pytest、JUint等。它簡單易用,易於集成。
Pytest框架集成Allure
Pytest是Python的單元測試框架,非常方便和易用。強烈推薦對於用Python進行測試工作的小伙伴使用這個測試框架,相比與Python自帶的UnitTest好用太多太多。后面我將用一整篇文章介紹Pytest測試框架。今天我們主要是介紹如何將測試報告生成工具Allure集成到Pytest中。
1.Allure 下載安裝
Allure 下載最新版本:https://github.com/allure-framework/allure2/releases
下載完成之后,解壓到 pytest 目錄中。然后設置環境變量,簡單一點就是進入 \allure-2.13.0\bin 目錄執行 allure.bat 。cmd 輸入 allure 查看環境變量是否設置成功。
2. allure-pytest
下載 allure-pytest 插件,用來生成 Allure 測試報告所需要的數據。
pip3 install allure-pytest
案例
#!/usr/bin/env python # coding=utf-8 import pytest import allure import os @pytest.fixture(scope='function') def login(): print("登錄") yield print("登錄完成") @allure.feature('加入購物車') def test_1(login): '''將蘋果加入購物車''' print("測試用例1") @allure.feature('加入購物車') def test_2(): '''將橘子加入購物車''' print("測試用例2") if __name__ =="__main__": # 執行pytest單元測試,生成 Allure 報告需要的數據存在 /temp 目錄 pytest.main(['--alluredir', './temp']) # 執行命令 allure generate ./temp -o ./report --clean ,生成測試報告 os.system('allure generate ./temp -o ./report --clean')
@allure 裝飾器中的一些功能點:
@allure.feature :用於定義被測試的功能,被測產品的需求點
@allure.story : 用於定義被測功能的用戶場景,即子功能點
@allure.step :用於將一個測試用例,分成幾個步驟在報告中輸出
allure.attach : 用於向測試報告中輸入一些附加的信息,通常是一些測試數據信息
3、生成Allure測試報告
3.1 執行測試腳本
測試腳本中添加了Allure特性之后,在執行測試的時候需要先生成Allure報告所需要的測試結果數據。在py.test執行測試的時候,指定–alluredir選項及測試數據保存的目錄即可:
$ py.test test/ --alluredir ./result/
./result/中保存了本次測試的結果數據。另外,還可以執行指定features或者stories執行一部分測試用例,比如執行‘購物車功能’下的‘加入購物車’子功能的測試用例:
$ py.test test/ --allure_features='購物車功能' --allure_stories='加入購物車'
運行完成后會在指定目錄下生產xml報告
3.2 生成測試報告
安裝完成后,通過下面的命令將./result/目錄下的測試數據生成測試報告:
$ allure generate ./result/ -o ./report/ --clean
這樣在./report/目錄下就生成了Allure的測試報告了。–clean目的是先清空測試報告目錄,再生成新的測試報告。