【问题标题】:pytest parametrize an autouse fixturepytest 参数化一个自动使用的夹具
【发布时间】:2021-02-05 19:44:03
【问题描述】:

我有大量使用 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

我看到了许多 somewhat related questions,但当 autouse=True 时,我似乎找不到如何参数化夹具。似乎要做我想做的事情,我需要使用 @pytest.mark.parametrize 装饰器更新 100 个测试并独立参数化每个测试。想法?

【问题讨论】:

    标签: python pytest pytest-mock


    【解决方案1】:

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

    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) 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-23
      • 1970-01-01
      • 1970-01-01
      • 2018-02-24
      相关资源
      最近更新 更多