pytest parametrize an autouse fixture

2k views Asked by At

I have a large amount of tests (high 100s) that use pytest and rely on a fixture that is set for autouse. I need to run those same 100s of tests with a slight variation that's controlled by the fixture.

Consider the following setup that demonstrates the technique I am trying to use, and does not work:

In 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)

In my_test.py

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

Here's a sample of the error I'm seeing:

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

I see a number of somewhat related questions, but I can't seem to find how to parametrize a fixture when autouse=True. It seems like to do what I'm trying to do I need to update 100s of tests with the @pytest.mark.parametrize decorator and parametrize each of them independently. Thoughts?

1

There are 1 answers

0
theG On

I figured it out myself. It's as simple as this:

In 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)