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
相关推荐
happylifetree2 小时前
Python70:核心语法-函数进阶-案例2
python
王中阳Go2 小时前
两个入口答案不一致先别调模型:6 行入口口径对账表(附脚本)
人工智能·后端·python·大语言模型·1024程序员节
BK贝壳2 小时前
bool-hybrid-array 落盘我只认 .bha:用 Create_BHA / Ask_BHA 做布尔数组序列化
数据结构·python·numpy·1024程序员节
Sakura_j_h_3 小时前
Python 在定时任务里输出 emoji,UnicodeEncodeError 从哪来
开发语言·字符编码·windows·python·定时任务
supabc1234 小时前
欧盟电子发票(XRechnung/Peppol/ZUGFeRD)踩坑记:用 Python 不装 Java 跑官方校验规则
xml·python·开源·电子发票·1024程序员节
ZhengEnCi5 小时前
AI Agent工具调用防护层怎么写-一份能直接跑的Python四层拦截实现
python·llm·agent
ZhengEnCi5 小时前
AI Agent工具误调用怎么解决-从参数校验到高危二次确认的四层工程防线
python·llm·agent
镜子AI6 小时前
镜子AI工程教程:用Python实现关键词布局检查器与语义改写查重(附完整代码)
人工智能·python·microsoft
小oo呆7 小时前
【学习心得】Python协程
python
信誓旦旦的程序猿7 小时前
【Python量化实战宝典 #22】涨跌停、连板情绪手册:情绪指标构建(Python 可跑)
python·1024程序员节·股票数据api·股票数据api接口·股票api数据接口·股票量化数据api·股票量化数据接口