自动使用的 Fixtures

Python 测试入门

Alexander Levin

Data Scientist

Autouse 参数

  • fixture 的可选布尔参数
  • 可传给 fixture 装饰器
  • autouse=True 时,fixture 将不经请求也会执行
  • 有助于减少多余的 fixture 调用
Python 测试入门

何时使用

当需要为所有测试进行统一的环境准备或修改时。

例如,我们希望确保所有测试:

  • 使用相同的数据
  • 具有相同的连接(数据、API 等)
  • 具有相同的环境配置
  • 有统一的监控、日志或性能分析

以上情况应使用 "autouse" 参数

Python 测试入门

Autouse 示例

"自动使用" fixture 示例:

import pytest
import pandas as pd

# 自动使用的 fixture
@pytest.fixture(autouse=True)
def set_pd_options():
    pd.set_option('display.max_columns', 5000)

# 测试函数
def test_pd_options():
    assert pd.get_option('display.max_columns') == 5000
Python 测试入门

Autouse 错误示例

错误 的"自动使用" fixture 示例:

import pytest
import pandas as pd

# 错误的自动使用 fixture
@pytest.fixture(autouse=True)
def wrong_fixture():
    return [1,2,3,4,5]

# 测试函数
def test_type():
    assert type(wrong_fixture) == list

修正 的 fixture 示例:

import pytest
import pandas as pd

# 修正的 fixture(非自动使用)
@pytest.fixture
def correct_fixture():
    return [1,2,3,4,5]

# 测试函数
def test_type(correct_fixture):
    assert type(correct_fixture) == list
Python 测试入门

自动使用示例:输出

示例输出:

autouse 示例输出

Python 测试入门

小结

  • autouse 定义:fixture 装饰器的可选布尔参数
  • 用法@pytest.fixture(autouse=True)
  • 优点:减少重复的 fixture 调用,使代码更简洁
  • 特性:设置 autouse=True 后,fixture 会不经请求也执行
  • 适用场景:需要进行环境的统一准备或修改时
  • 示例用例
    • 为所有测试读取并准备数据
    • 配置连接与环境参数
    • 实现监控、日志或性能分析
Python 测试入门

¡Vamos a practicar!

Python 测试入门

Preparing Video For Download...