Pytest +requests+ Allure
這個框架基于python的的 Pytest 進行測試執行,并結合 Allure插件 生成測試報告的測試框架。采用 關鍵字驅動 方式,使測試用例更加清晰、模塊化,同時支持 YAML 文件來管理測試用例,方便維護和擴展。
測試用例:YAML 文件
主要包含測試用例的步驟、調用的函數、函數所需的參數。
分層結構
- config 層:全局配置(
base_url
、公共變量)。 - steps 層:測試步驟(請求 -> 提取 -> 斷言)。
模板引擎
- 支持
{{}}
變量插值語法。 - 支持環境變量注入(
${ENV_VAR}
)。
示例:登錄失敗測試用例(用戶名為空)
desc: 登錄失敗測試用例--用戶名為空
steps:- 發送Post請求:關鍵字: request_post_form_dataURL: "{{url}}"PARAMS:s: /api/user/loginapplication: appDATA:accounts: ''pwd: 123456type: username- 通過JSONPATH提取數據-MSG:關鍵字: ex_jsonDataEXVALUE: $..msgINDEX: 0VARNAME: msg_success- 斷言-文本斷言-等于:關鍵字: assert_text_comparatorsVALUE: "{{msg_success}}"EXPECTED: 登錄賬號不能為空OP_STR: ==
關鍵字驅動模式(封裝 Keywords 函數)
Keywords
類封裝了 YAML 文件中定義的請求關鍵字,并在執行步驟時,將有用的信息(如 token
、response
)存入全局字典 gc
,同時,每個方法都使用 @allure.step
裝飾器,以生成測試報告的步驟。
關鍵字實現示例
class Keywords:@allure.step('發送POST請求')def request_post(self, **kwargs):response = requests.post(**kwargs)gc.set_dict('current_response', response)return response@allure.step('發送GET請求')def request_get(self, **kwargs):response = requests.get(**kwargs)gc.set_dict('current_response', response)return response@allure.step('發送PUT請求')def request_put(self, **kwargs):response = requests.put(**kwargs)gc.set_dict('current_response', response)return response@allure.step('發送POST請求--form_data表單的請求')def request_post_form_data(self, **kwargs):url = kwargs.get('URL', None)params = kwargs.get('PARAMS', None)data = kwargs.get('DATA', None)headers = kwargs.get('HEADERS', None)request_data = {'url': url, 'params': params, 'data': data, 'headers': headers}response = self.request_post(**request_data)return response
Pytest 框架入口
import os
import pytestpytest_args = ['-v', '-s', '--capture=sys', '--clean-alluredir', '--alluredir=allure-results','--type=yaml', '--cases=./data/yaml_testcase', './core/ApiTestRunner.py'
]
pytest.main(pytest_args)
使用 pytest.main
函數,同時指定運行參數,包括 Allure
測試報告數據目錄和運行的 py
腳本。
用例運行腳本
class TestRunner:def test_case_execute(self, get_dict_token, caseinfo):try:allure.dynamic.title(caseinfo['_case_name']) # 自定義用例標題local_context = caseinfo.get('context', {})kw = Keywords()# 解析測試用例步驟steps = caseinfo.get('steps', None)for step in steps:step_name = list(step.keys())[0]step_value = list(step.values())[0]context = copy.deepcopy(g_context().show_dic())context.update(local_context)step_value = eval(ReFresh(step_value, context))with allure.step(step_name):key = step_value['關鍵字']try:key_func = kw.__getattribute__(key)except Exception as e:print(e)key_func(**step_value)except Exception as e:assert False, f"核心執行器或是核心執行器調用的關鍵字有錯誤: {e}"finally:print('---執行用例完成---')
此運行腳本的功能:
- 讀取 YAML 測試用例 (
caseinfo
變量)。 - 逐步運行測試用例步驟 (
steps
)。 - 使用
Keywords
類中的函數執行測試操作。 - 通過 Python 反射機制動態獲取
Keywords
類中的方法并執行。
測試用例執行全流程
- 測試用例按照 YAML 規范編寫,指定每一步測試步驟。
- 運行腳本讀取 YAML 文件。
- 逐步執行 YAML 中定義的步驟,并調用
Keywords
類中的方法。
技術要點
- YAML 文件管理測試用例。
- 采用關鍵字驅動模式 設計測試用例執行框架,使用例執行更加清晰。
- 使用全局字典管理數據,處理測試用例之間的關聯情況。
- 集成 Allure 生成測試報告,提供詳細的測試結果。