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
相关推荐
SCBAiotAigc13 分钟前
Chrome的cookie编辑插件EditThisCookie
人工智能·chrome·python·ubuntu
dagouaofei19 分钟前
运营述职 PPT 工具横评:效率与呈现谁更优
python·powerpoint
先做个垃圾出来………23 分钟前
Python测试桩工具
java·开发语言·python
小芳矶23 分钟前
【langchain框架——检索链】利用检索链创建自己的购物知识库并完成智能体的商品推荐
java·python·langchain
就叫飞六吧31 分钟前
py脚本一键生成常见文件格式案例
开发语言·python
AI能力探索40 分钟前
Python机器学习三大经典算法:KNN、SVM、朴素贝叶斯
python
盼哥PyAI实验室44 分钟前
Python 爬虫实战:从 Ajax 到 POST 请求,完整爬取汉堡王门店与产品数据
爬虫·python·ajax
TheSumSt1 小时前
Python丨课程笔记Part2:方法论进阶部分
开发语言·笔记·python
知远同学1 小时前
使用virtualenv 和 anaconda 创建管理虚拟环境的区别
python
山沐与山1 小时前
【设计模式】Python状态模式:从入门到实战
python·设计模式·状态模式