D94【python 接口自动化学习】- pytest进阶之fixture用法

day94 pytest的fixture详解

学习日期:20241210

学习目标:pytest基础用法 -- pytest的fixture详解

学习笔记:

fixture的介绍

fixture是 pytest 用于将测试前后进行预备、清理工作的代码处理机制。

fixture相对于setup和teardown来说有以下几点优势:

  • fixure命名更加灵活,局限性比较小
  • conftest.py 配置里面可以实现数据共享,不需要import就能自动找到一些配置
fixture夹具

@pytest.fixture,scope作用域的意思

  • (scop="function") 每一个函数或方法都会调用,默认就是function
  • 只有调用了func函数的才会运行func
python 复制代码
import pytest
import requests

#默认scope是function
@pytest.fixture()
def func():
    print("我是前置步骤")

def test_getmobile(func):
    print("测试get请求")
    params = {'key1': 'value1', 'key2': 'value2'}
    r=requests.get('https://httpbin.org/get',params=params)
    print(r.status_code)
    assert r.status_code == 200
    res = r.json()
    assert res['url'] == 'https://httpbin.org/get?key1=value1&key2=value2'
    assert res['origin'] == '163.125.202.248'
    assert res['args']['key1'] == 'value1'
    assert res['args']['key2'] == 'value2'

def test_postmobile():
    print("测试post请求")
    params = {'key': 'value'}
    r = requests.post('https://httpbin.org/post', data=params)
    print(r.status_code)
    assert r.status_code == 200
    print(r.json())
    res=r.json()
    assert res['args'] == {}
    assert res['data'] == ''
    assert res['form']['key'] == 'value'

if __name__ == '__main__':
    pytest.main()
总结
  1. fixture是 pytest 用于将测试前后进行预备、清理工作的代码处理机制
  2. scope作用域(scop="function") 每一个函数或方法都会调用,默认就是function
相关推荐
天上的光15 分钟前
3.python——数据类型转换
python
钱彬 (Qian Bin)30 分钟前
一文掌握工业缺陷检测项目实战(Pytorch算法训练、部署、C++ DLL制作、Qt集成)
c++·pytorch·python·qt·实战·工业缺陷检测·faster rcnn
Python×CATIA工业智造1 小时前
Python迭代协议完全指南:从基础到高并发系统实现
python·pycharm
THMAIL1 小时前
机器学习从入门到精通 - Transformer颠覆者:BERT与预训练模型实战解析
python·随机森林·机器学习·分类·bootstrap·bert·transformer
0wioiw01 小时前
Python基础(①⑧Queue)
windows·python
Source.Liu2 小时前
【Python自动化】 21 Pandas Excel 操作完整指南
python·excel·pandas
urhero2 小时前
Python 制作的一个小说在线阅读工具
python·免费·小说·应用软件·小说在线阅读·无广告
跟橙姐学代码2 小时前
列表、元组与字典:Python开发者的三大必备利器,再向高手靠近一步
前端·python·ipython
计算机毕设残哥2 小时前
HDFS存储农业大数据的秘密是什么?高级大豆数据分析与可视化系统架构设计思路
大数据·hadoop·python·hdfs·数据分析·spark·django
蛋仔聊测试2 小时前
pytest源码解析(二)剖析 pytest 的核心组件
python·面试