• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

火爆全网,接口自动化框架-pytest+yaml细

武飞扬头像
测试追风
帮助2


前言

httprunner 用 yaml 文件实现接口自动化框架很好用,最近在看 pytest 框架,于是参考 httprunner的用例格式,写了一个差不多的 pytest 版的简易框架

项目结构设计

项目结构完全符合 pytest 的项目结构,pytest 是查找 test_.py 文件,我这里是查找 test_.yml 文件,唯一不同的就是这个地方

项目结构参考

学新通

只需在 conftest.py 即可实现,代码量超级少
pytest 7.x最新版

def pytest_collect_file(parent, file_path):
    # 获取文件.yml 文件,匹配规则
    if file_path.suffix == ".yml" and file_path.name.startswith("test"):
        return YamlFile.from_parent(parent, path=file_path)

pytest 5.x以上版本

import pytest
import requests


def pytest_collect_file(parent, path):
    # 获取文件.yml 文件,匹配规则
    if path.ext == ".yml" and path.basename.startswith("test"):
        # print(path)
        # print(parent)
        # return YamlFile(path, parent)
        return YamlFile.from_parent(parent, fspath=path)


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.from_parent(self, name=name, values=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
学新通

pytest 4.x 以下版本

import pytest
import requests


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
下面是我整理的2023年最全的软件测试工程师学习知识架构体系图

一、Python编程入门到精通

学新通

二、接口自动化项目实战

学新通

三、Web自动化项目实战

学新通

四、App自动化项目实战

学新通

五、一线大厂简历

学新通

六、测试开发DevOps体系

学新通

七、常用自动化测试工具

学新通

八、JMeter性能测试

学新通

九、总结(尾部小惊喜)

心怀梦想,勇攀高峰,奋斗是成就的律动。不畏艰辛,坚守初心,用执着铸就辉煌。每一次努力都是改变的力量,相信自己的能量,奋发向前,让努力与汗水绽放生命的辉煌之花。

执着追求,勇往直前,奋斗是舞出人生的节拍。无惧困境,砥砺前行,用智慧与汗水铸就辉煌。相信自己的力量,坚定信念,用勤奋书写属于自己的传世之作。

拥抱挑战,超越极限,奋斗是蜕变的契机。不断努力,磨砺品格,让激情驱动前行的步伐。坚信自己的力量,勇敢地闯荡未来,用汗水浇灌成长的花朵,在追求中创造属于自己的辉煌人生。

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhhkbcbh
系列文章
更多 icon
同类精品
更多 icon
继续加载