15、pytest的fixture调用fixture

官方实例

python 复制代码
# content of test_append.py
import pytest

# Arrange
@pytest.fixture
def first_entry():
    return "a"
    
# Arrange
@pytest.fixture
def order(first_entry):
    return [first_entry]
    
def test_string(order):
    # Act
    order.append("b")
    
    # Assert
    assert order == ['a','b']
python 复制代码
# content of test_reuse_fixture.py
import pytest

# Arrange
@pytest.fixture
def first_entry():
    return "a"
    
# Arrange
@pytest.fixture()
def order(first_entry):
    return [first_entry]
    
def test_string(order):
    # Act
    order.append("b")
    
    # Assert
    assert order == ["a","b"]
    
def test_int(order):
    # Act
    order.append(2)
    
    # Assert
    assert order == ["a",2]

解读与实操

pytest最大的优势之一是其极其灵活的fixture系统。它允许我们将复杂的测试需求简化成更简单和有组织的功能,我们只需要让每个功能描述它们所依赖的东西。

pytest的fixture系统如此强大的原因之一是,它使我们能够定义一个可以反复重用的通用步骤,就像使用普通函数一样。两个不同的测试可以请求相同的fixture,并让pytest从该fixture为每个测试提供各自的结果。

这对于确保测试不受彼此影响非常有用。我们可以使用这个系统来确保每个测试都获得自己的新一批数据,并且从一个干净的状态开始,这样它就可以提供一致的、可重复的结果。

场景应用

fixture可以调用其它fixture;重复使用fixture时,每个测试都会获得不受影响的一批数据。在登录类应用时比较方便,创建一个获取token的fixture,其它测试函数重复使用这个fixture,获取鉴权。后面会说明fixture作用域,设置为类级或会话级,可以保证多次测试只请求了一个token。

相关推荐
2601_962077609 小时前
从零搭建Python接口自动化测试框架:pytest+requests实战指南
python·pytest·接口自动化·requests·框架搭建
weixin_4407305011 小时前
pytest结合allure生成html测试报告(step、story、severity、screenshot)
前端·html·pytest·allure报告
拜托多多指教12 小时前
【Pytest框架学习】分层架构
python·pytest
2601_9622998812 小时前
python脚本如何单元测试
python·单元测试·pytest·unittest·mock对象
Tizzy JJ1 天前
Python + pytest 接口自动化测试框架实战:从零搭建企业级项目骨架
开发语言·python·pytest
Tizzy JJ1 天前
接口自动化测试实战:如何围绕真实业务场景设计高质量用例
python·自动化·pytest
测试老哥2 天前
Pytest 之assert断言的使用
自动化测试·软件测试·python·测试工具·测试用例·pytest·接口测试
边吃番茄边敲代码6 天前
从本地工具到 MCP:给 Agent 接入独立工具服务,并补齐自动化测试
人工智能·python·功能测试·ai·单元测试·pytest
SugarAbsinthe6 天前
【Agent开发实习小记】从人工逐条验证到自动化验收:新 API 接入前的效率瓶颈
人工智能·python·自动化·pytest