Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example of a `pytest.indirect` fixture passing along its name ("a" or "b", as `request.param`) to look up values rather than parametrising directly in a decorator
from enum import Enum
from pytest import fixture, mark
class Int1(Enum):
small = 0
large = 100
class Int2(Enum):
small = 2
large = 200
@fixture(scope="function")
def numbers(request) -> tuple[int, int]:
return Int1[request.param].value, Int2[request.param].value
@mark.parametrize("numbers,total", [("small", 2), ("large", 300)], indirect=["numbers"])
def test_other(numbers, total):
"A fixture with an 'indirect' parameter, which passes along its name"
first, second = numbers
assert first + second == total
from enum import Enum
from pytest import fixture, mark
class Int1(Enum):
a = 0
c = 1
class Int2(Enum):
b = 2
d = 2
@fixture(scope="function")
def first(request):
return Int1[request.param].value
@fixture(scope="function")
def second(request):
return Int2[request.param].value
@mark.parametrize(
"first,second,total", [("a", "b", 2), ("c", "d", 3)], indirect=["first", "second"]
)
def test_other(first, second, total):
"A fixture with an 'indirect' parameter, which passes along its name"
assert first + second == total
from pytest import fixture, mark
def lookup_indirect(name) -> int:
return {"a": 0, "b": 1}[name]
@fixture(scope="function")
def a(request):
return lookup_indirect(name=request.param)
@fixture(scope="function")
def b(request):
return lookup_indirect(name=request.param)
@mark.parametrize("a,b", [("a", "b")], indirect=["a", "b"])
def test_other(a, b):
"A fixture with an 'indirect' parameter, which passes along its name"
assert a == 0
assert b == 1
@lmmx
Copy link
Author

lmmx commented Oct 27, 2022

Note: this shows how to parametrise with a fixture. You may instead want to parameterise the fixture (@pytest.fixture(params=[...]))

@lmmx
Copy link
Author

lmmx commented Oct 27, 2022

You could extend this to parametrize with a 2nd tuple ("c", "d"), and add entries in the lookup dict for keys c and d. This might be useful if you had a 3rd [non-indirect] parameter which these lookup values may relate to.

For example, you may have your keys be filenames used to look up file contents, and a 3rd value would be a result (e.g. a diff)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment