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
相关推荐
灏瀚星空1 小时前
基于Python的量化交易实盘部署与风险管理指南
开发语言·python
Amo Xiang3 小时前
《100天精通Python——基础篇 2025 第18天:正则表达式入门实战,解锁字符串处理的魔法力量》
python·正则表达式·re
敲键盘的小夜猫4 小时前
Python核心数据类型全解析:字符串、列表、元组、字典与集合
开发语言·python
apcipot_rain5 小时前
【应用密码学】实验五 公钥密码2——ECC
前端·数据库·python
小彭律师6 小时前
门禁人脸识别系统详细技术文档
笔记·python
鸿业远图科技6 小时前
分式注记种表达方式arcgis
python·arcgis
头疼的程序员7 小时前
allure生成测试报告(搭配Pytest、allure-pytest)
测试工具·pytest
别让别人觉得你做不到7 小时前
Python(1) 做一个随机数的游戏
python
小彭律师9 小时前
人脸识别门禁系统技术文档
python