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。

相关推荐
m0_6324825012 小时前
Jenkins + Pytest +allure接口自动化测试配置与操作
jenkins·集成测试·pytest·jenkins配置
李星星BruceL12 小时前
Pytest第三章(参考指南1)
python·自动化·pytest
哎呀呦呵12 小时前
pytest基本使用
python·pytest
Kristen_YXQDN12 小时前
PyCharm 中 pytest 运行 python 测试文件报错:D:\Python_file\.venv\Scripts\python.exe: No module named pytest
运维·开发语言·python·pycharm·pytest
Low--Key12 小时前
pytest框架快速入门
python·自动化·pytest
姜西西_12 小时前
自动化测试框架pytest之fixture
android·java·pytest
测试开发Kevin12 小时前
超级实用!汇总pytest中那些常用的参数
单元测试·pytest
Beaman102412 小时前
pytest框架
python·pytest
昔时扬尘处1 天前
【Files Content Replace】文件夹文件内容批量替换自动化测试脚本
c语言·python·pytest·adi
我的xiaodoujiao1 天前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 32--开源电商商城系统项目实战--如何区分登录状态
python·学习·测试工具·pytest