1. 程式人生 > 其它 >HttpRunner3.X - 框架環境搭建及使用的完整教程

HttpRunner3.X - 框架環境搭建及使用的完整教程

一、環境配置

1、安裝:pip install httprunner

2、檢驗是否安裝成功:hrun -V

3、在 HttpRunner 安裝成功後,系統中會新增 4 個命令:

  • httprunner: 核心命令,用於所有函式
  • hrun:httprunner 的縮寫,功能與 httprunner 完全相同,用於執行yaml/json/pytest測試用例
  • hmake:httprunner make的別名,用於將YAML/JSON測試用例轉換為pytest檔案
  • har2case:輔助工具,可將標準通用的 HAR 格式(HTTP Archive)轉換為YAML/JSON格式的測試用例

二、建立httprunner專案

1、建立專案:httprunner startproject demo

可以cd到指定目錄後,再建立,以下就是每個目錄代表的含義:
  • debugtalk.py 放置在專案根目錄下(借鑑了pytest的conftest檔案的設計)
  • .env 放置在專案根目錄下,可以用於存放一些環境變數
  • reports 資料夾:儲存 HTML 測試報告
  • testcases 用於存放測試用例
  • har 可以存放錄製匯出的.har檔案

2、執行用例:hrun demo 或 pytest demo

3、將har檔案轉換成指令碼,舉例有檔案test.har

  • 轉yaml格式指令碼:har2case test.har -2y
  • 轉json格式指令碼:har2case test.har -2j
  • 轉pytest檔案:har2case test.har

三、執行程式碼

  因為httprunner封裝了pytest,所有既可以用hrun去執行,也可以用pytest去執行。   舉例有檔案test_test.py
  • hrun執行:hrun test_test.py (若想在日誌控制檯檢視詳細的介面返回資訊,可以在命令加 -s ,即hrun -s test_test.py
  • pytest執行:pytest tetst_test.py

四、allure安裝

1、安裝python依賴包:pip3 install pytest-allure-adaptor

2、安裝allure:pip install allure-pytest

執行命令後報錯module 'pytest' has no attribute 'allure'的問題,解決方案如下:
  • 發現之前安裝了pytest-allure-adaptor。
  • 如果存在安裝過的pytest-allure-adaptor外掛,
  • 先解除安裝:pip uninstall pytest-allure-adaptor
  • 重新安裝allure-pytest:pip install allure-pytest
  • 如果上述方法安裝不了,則改用豆瓣進行安裝,格式為:pip install 庫名 -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com

五、安裝allure命令列工具

  下載allure,開啟bin目錄執行allure.bat,配置環境變數後,在cmd執行allure

六、allure執行用例,生成測試報告

1、進入測試用例目錄下,指定執行用例:

  • 測試檔案:如果是填寫檔名,預設是當前路徑的檔案,如果要執行指定檔案,則測試檔案要帶上路徑
  • reprort: 是用於存放的檔案(預設是存放在當前路徑,如果要存放在指定路徑,則檔名要帶上路徑)
  • pytest執行的測試用例只能是.py格式,hrun執行的測試用例,可以是pytest格式,也可以是yml格式

步驟一:執行測試用例開啟cmd,定位到hetest_re_test.py所在的目錄下

  • pytest執行:pytest hetest_re_test.py --alluredir report
  • hrun執行:hrun hetest_re.yml --alluredir=report
  執行完後會在當前資料夾下生成測試結果資料夾 .pytest_cache、report

步驟二:生成報告

  • allure generate report # 預設在當前目錄下生成allure-report檔案
  • allure generate report -o allure-report --clean # --clean是為了清空已有的測試報告; -oallure-report 是指定清空測試報告的檔案allure-report
會在當前資料夾生成allure-report資料夾,包含HTML測試報告 index.html ,然後用瀏覽器開啟檢視

2、全部執行:pytest --alluredir report

  • 全部執行的是test_.*py的檔案
  • pytest --alluredir report
  • 會在當前資料夾下生成測試結果資料夾 .pytest_cache、report
  • allure generate report
  • 同樣會在當前資料夾生成 allure-report 資料夾,包含HTML測試報告 index.html,含所有測試用例結果資料

附上HttpRunner官方文件:https://docs.httprunner.org/