pytest文檔71-pytest+yaml實現接口自動化框架


前言

httprunner 用 yaml 文件實現接口自動化框架很好用,最近在看 pytest 框架,於是參考 httprunner的用例格式,寫了一個差不多的 pytest 版的簡易框架

項目結構設計

項目結構完全符合 pytest 的項目結構,pytest 是查找 test_.py 文件,我這里是查找 test_.yml 文件,唯一不同的就是這個地方
以前寫test_*.py 的測試用例,現在完全不用寫了,全部寫yaml 文件就行,項目結構參考

只需在 conftest.py 即可實現,代碼量超級少

import pytest
import requests
# 作者-上海悠悠 QQ交流群:717225969
# blog地址 https://www.cnblogs.com/yoyoketang/


def pytest_collect_file(parent, path):
    # 獲取文件.yml 文件,匹配規則
    if path.ext == ".yml" and path.basename.startswith("test"):
        # print(path)
        # print(parent)
        return YamlFile(path, parent)



class YamlFile(pytest.File):
    # 讀取文件內容
    def collect(self):
        import yaml
        raw = yaml.safe_load(self.fspath.open(encoding='utf-8'))
        for yaml_case in raw:
            name = yaml_case["test"]["name"]
            values = yaml_case["test"]
            yield YamlTest(name, self, values)


class YamlTest(pytest.Item):
    def __init__(self, name, parent, values):
        super(YamlTest, self).__init__(name, parent)
        self.name = name
        self.values = values
        self.request = self.values.get("request")
        self.validate = self.values.get("validate")
        self.s = requests.session()

    def runtest(self):
        # 運行用例
        request_data = self.values["request"]
        # print(request_data)
        response = self.s.request(**request_data)
        print("\n", response.text)
        # 斷言
        self.assert_response(response, self.validate)

    def assert_response(self, response, validate):
        '''設置斷言'''
        import jsonpath
        for i in validate:
            if "eq" in i.keys():
                yaml_result = i.get("eq")[0]
                actual_result = jsonpath.jsonpath(response.json(), yaml_result)
                expect_result = i.get("eq")[1]
                print("實際結果:%s" % actual_result)
                print("期望結果:%s" % expect_result)
                assert actual_result[0] == expect_result

斷言這部分,目前只寫了判斷相等,僅供參考,支持jsonpath來提取json數據

yaml格式的用例

在項目的任意目錄,只要是符合test_開頭的yml文件,我們就認為是測試用例
test_login.yml的內容如下

- test:
    name: login case1
    request:
        url: http://49.235.x.x:7000/api/v1/login/
        method: POST
        headers:
            Content-Type: application/json
            User-Agent: python-requests/2.18.4
        json:
            username: test
            password: 123456
    validate:
        - eq: [$.msg, login success!]
        - eq: [$.code, 0]


- test:
    name: login case2
    request:
        url: 49.235.x.x:7000/api/v1/login/
        method: POST
        headers:
            Content-Type: application/json
            User-Agent: python-requests/2.18.4
        json:
            username: test
            password: 123456
    validate:
        - eq: [$.msg, login success!]
        - eq: [$.code, 0]

運行用例

運行用例,完全符合pytest的只需用例風格,支持allure報告

pytest -v

D:\soft\api_pytest_1208>pytest -v
====================== test session starts ======================
platform win32 -- Python 3.6.6, pytest-4.5.0, py-1.9.0,
cachedir: .pytest_cache
rootdir: D:\soft\api_pytest_1208
plugins: allure-pytest-2.8.6
collected 4 items

data/test_login.yml::login case1 PASSED                    [ 25%]
data/test_login.yml::login case2 PASSED                    [ 50%]
data/test_login1.yml::login case1 PASSED                   [ 75%]
data/test_login1.yml::login case2 PASSED                   [100%]

=================== 4 passed in 1.34 seconds ====================

allure報告

pytest --alluredir ./report

目前是把 yaml 文件下每個 test 當一個用例執行,后續還可以加上提取參數,參數關聯更高級的功能!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM