链式调用 Fixtures

Python 测试入门

Alexander Levin

Data Scientist

什么是链式请求

  • 通过"链式调用 fixtures"功能,允许一个 fixture 使用另一个 fixture(pytest 功能)
  • 形成 fixture 组合

fixture 调用其他 fixture

Python 测试入门

为何及何时使用

链式调用 fixtures 有助于:

  • 建立 fixture 之间的依赖
  • 保持代码模块化

适用场景:

  • 多个 fixtures 彼此依赖时
Python 测试入门

链式请求示例

# 被其他 fixture 请求的 fixture
@pytest.fixture
def setup_data():
    return "I am a fixture!"
# 被测试函数请求的 fixture
@pytest.fixture
def process_data(setup_data):
    return setup_data.upper()
# 测试函数
def test_process_data(process_data):
    assert process_data == "I AM A FIXTURE!"
Python 测试入门

如何使用链式请求

  1. 准备要测试的程序
  2. 准备测试函数
  3. 准备 pytest fixtures
  4. 在另一个 fixture 的签名中传入该 fixture 名称
# 请求其他 fixture 的 fixture
@pytest.fixture
def process_data(setup_data):
    return setup_data.upper()
Python 测试入门

小结

  • 链式调用 fixture:允许一个 fixture 使用另一个 fixture(形成组合)
  • 有助于按功能拆分代码并保持模块化
  • 典型用例:数据管道各步骤
  • 用法:在另一个 fixture 的函数签名中传入其名称
Python 测试入门

Passons à la pratique !

Python 测试入门

Preparing Video For Download...