首页 > 解决方案 > pytest 参数化一个自动使用的夹具

问题描述

我有大量使用 pytest 并依赖于设置为自动使用的夹具的测试(高 100 秒)。我需要运行相同的 100 次测试,但由夹具控制的轻微变化。

考虑以下设置,该设置演示了我尝试使用的技术,但不起作用:

conftest.py

import pytest

def patch_0() -> int:
   return 0

def patch_1() -> int:
   return 1

@pytest.fixture(autouse=True)
@pytest.mark.parametrize("patch", [patch_0, patch_1])
def patch_time_per_test(monkeypatch, patch):
    monkeypatch.setattr("time.time", patch)

my_test.py

import time
  
def test_00():
    assert time.time() < 100

这是我看到的错误示例:

file ../conftest.py, line 14
  @pytest.fixture(autouse=True)
  @pytest.mark.parametrize("patch", [patch_0, patch_1])
  def patch_time_per_test(monkeypatch, patch):
E       fixture 'patch' not found

我看到了一些有些 相关的 问题,但我似乎无法找到如何在何时对夹具进行参数化autouse=True。似乎要做我想做的事情,我需要使用@pytest.mark.parametrize装饰器更新 100 个测试并独立参数化每个测试。想法?

标签: pythonpytestpytest-mock

解决方案


我自己想通了。就这么简单:

conftest.py

import pytest

def patch_0() -> int:
   return 0

def patch_1() -> int:
   return 1

@pytest.fixture(autouse=True, params=[patch_0, patch_1])
def patch_time_per_test(monkeypatch, request): 
    monkeypatch.setattr("time.time", request.param) 

推荐阅读