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
相关推荐
apocelipes1 小时前
golang unique包和字符串内部化
java·python·性能优化·golang
Geoking.2 小时前
NumPy zeros() 函数详解
python·numpy
Full Stack Developme2 小时前
java.text 包详解
java·开发语言·python
丁浩6663 小时前
Python机器学习---2.算法:逻辑回归
python·算法·机器学习
B站_计算机毕业设计之家3 小时前
计算机毕业设计:Python农业数据可视化分析系统 气象数据 农业生产 粮食数据 播种数据 爬虫 Django框架 天气数据 降水量(源码+文档)✅
大数据·爬虫·python·机器学习·信息可视化·课程设计·农业
Q_Q5110082853 小时前
python+uniapp基于微信小程序的旅游信息系统
spring boot·python·微信小程序·django·flask·uni-app·node.js
鄃鳕3 小时前
python迭代器解包【python】
开发语言·python
懷淰メ4 小时前
python3GUI--模仿百度网盘的本地文件管理器 By:PyQt5(详细分享)
开发语言·python·pyqt·文件管理·百度云·百度网盘·ui设计
Q_Q5110082854 小时前
python基于web的汽车班车车票管理系统/火车票预订系统/高铁预定系统 可在线选座
spring boot·python·django·flask·node.js·汽车·php
新子y4 小时前
【小白笔记】普通二叉树(General Binary Tree)和二叉搜索树的最近公共祖先(LCA)
开发语言·笔记·python