接口自动化测试之pytest接口关联框架封装

🍅 点击文末小卡片,免费获取软件测试全套资料,资料在手,涨薪更快

一般情况下,我们是通过一个yaml文件进行关联实现

在根目录下新建一个文件yaml,通过上述conftest.py文件实现全局变量的更新:

1.首先需要建立一个读取、写入、清除yaml文件的工具类

如下:

复制代码
import os
 
import yaml
 
 
class YamlUnit:
    def readAllYaml(self):
        with open(os.getcwd() + "/extract.yml", mode='r', encoding='utf-8') as f:
            value = yaml.load(stream=f, Loader=yaml.FullLoader)
            return value
 
    def readKeyYaml(self,key):
        with open(os.getcwd() + "/extract.yml", mode='r', encoding='utf-8') as f:
            value = yaml.load(stream=f, Loader=yaml.FullLoader)
            return value[key]
 
    def writeYaml(self, data):
        with open(os.getcwd() + "/extract.yml", mode='w', encoding='utf-8') as f:
            print(os.getcwd() + "/extract.yml")
            value = yaml.dump(data=data, stream=f, allow_unicode=True)
 
    def deleteYaml(self):
        with open(os.getcwd()+"/extract.yml",mode="w",encoding='utf-8') as f:
            f.truncate()

2.配合conftest.py文件+ fixture实现全局共享调用

复制代码
# 实现部分前置
import pytest
 
from comment.yaml_unit import YamlUnit
 
 
@pytest.fixture(scope="function")
def conn_getbase():
    print("连接数据库成功")
    yield
    print("关闭数据库成功")
 
 
@pytest.fixture(scope="session", autouse=True)
def clear_yaml():
    YamlUnit().deleteYaml()
 
 
@pytest.fixture(scope="session", autouse=True)
def get_token():
    token = '';  # 获取token的代码请求
    return token

3.调用时只需传入方法函数名称即可

如:下面函数使用之前需要连接数据库,只需传入conftest.py文件里面的conn_getbase函数名即可

复制代码
   def test_Login(self,conn_getbase):
        # post请求
        url = "xxxxxxx"
        # 参数
        data = {
            "captcha": "Gkak!@#2019",
            "checkKey": 1637811815838,
            "password": "123456",
            "remember_me": 1,
            "username": "admin"
        }
        rep = requests.request('post', url, json=data)
        statues = rep.json()["success"]
        message = rep.json()["message"]
        if statues:
            print(message )
        else:
            raise Exception(message)

最后感谢每一个认真阅读我文章的人,礼尚往来总是要有的,虽然不是什么很值钱的东西,如果你用得到的话可以直接拿走:

这些资料,对于做【软件测试】的朋友来说应该是最全面最完整的备战仓库,这个仓库也陪伴我走过了最艰难的路程,希望也能帮助到你!凡事要趁早,特别是技术行业,一定要提升技术功底。

相关推荐
l1t9 分钟前
DeepSeek辅助利用搬移底层xml实现快速编辑xlsx文件的python程序
xml·开发语言·python·xlsx
大飞记Python12 分钟前
部门管理|“编辑部门”功能实现(Django5零基础Web平台)
前端·数据库·python·django
微笑尅乐2 小时前
中点为根——力扣108.讲有序数组转换为二叉搜索树
算法·leetcode·职场和发展
查士丁尼·绵2 小时前
笔试-羊狼过河
python
摸鱼的老谭2 小时前
构建Agent该选Python还是Java ?
java·python·agent
鄃鳕3 小时前
python 字典 列表 类比c++【python】
c++·python
可触的未来,发芽的智生3 小时前
新奇特:黑猫警长的纳米世界,忆阻器与神经网络的智慧
javascript·人工智能·python·神经网络·架构
夏鹏今天学习了吗3 小时前
【LeetCode热题100(46/100)】从前序与中序遍历序列构造二叉树
算法·leetcode·职场和发展
吃着火锅x唱着歌3 小时前
LeetCode 2389.和有限的最长子序列
算法·leetcode·职场和发展
程序员三藏3 小时前
Jmeter接口测试与压力测试
自动化测试·软件测试·python·测试工具·jmeter·接口测试·压力测试