接口自动化测试之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)

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

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

相关推荐
搏博13 分钟前
将图形可视化工具的 Python 脚本打包为 Windows 应用程序
开发语言·windows·python·matplotlib·数据可视化
硅基茶水间26 分钟前
「轻量级AI编程桌面软件」代码上下文一键搞定|已开源
python
光电的一只菜鸡40 分钟前
Wireshark使用教程(含安装包和安装教程)
网络·测试工具·wireshark
Hockor1 小时前
写给前端的 Python 教程三(字符串驻留和小整数池)
前端·后端·python
网安小张1 小时前
解锁FastAPI与MongoDB聚合管道的性能奥秘
数据库·python·django
GeekAGI1 小时前
Python 定时器框架
python
mit6.8241 小时前
[测试_10] Selenium IDE | cssSelector | XPath | 操作测试
测试工具
KENYCHEN奉孝1 小时前
Pandas和Django的示例Demo
python·django·pandas
拾零吖1 小时前
《Pytorch深度学习实践》ch8-多分类
人工智能·pytorch·python
·云扬·1 小时前
【PmHub面试篇】Gateway全局过滤器统计接口调用耗时面试要点解析
面试·职场和发展·gateway