Friday 4 December 2020

pytest: how to use indirect parameterization when fixtures have same parameters

I am using pytest's indirect parameterization to parameterize an upstream fixture. This has been working fine for me.

However, now I am stuck on when the upstream fixtures have the same argument names, and I want to pass them different values.

How can I use indirect parameterization when the upstream fixture to be parameterized's arguments have the same names?


Sample Code

import pytest

class Config:
    """This is a configuration object."""
    def __init__(self, a: int, b: int):
        self._a = a
        self._b = b

@pytest.fixture
def config(a: int, b: int) -> Config:
    return Config(a, b)

class Foo:
    def __init__(self, config: Config):
        """This does some behavior."""
        self.config = config

@pytest.fixture
def foo(config: Config) -> Foo:
    return Foo(config)

class Bar:
    def __init__(self, config: Config):
        """This does some other behavior."""
        self.config = config

@pytest.fixture
def bar(config: Config) -> Bar:
    return Bar(config)

class TestFooBarTogether:
    @pytest.mark.parametrize("a, b", [(1, 2)])
    def test_foo_alone(self, foo: Foo) -> None:
        """This works fine, since parameters get passed all the way to Config."""

    @pytest.mark.parametrize("a, b", [(1, 2)])
    def test_together(self, foo: Foo, bar: Bar) -> None:
        """Test interactions between the two objects.

        This does not work, because both foo and bar get the same config.
        How can I pass a different config to foo and bar, even though Config
        takes both an "a" and a "b"?
        
        I would like to pass `foo` something like (1, 2) and 
        `bar` something like (3, 4).

        """


from pytest: how to use indirect parameterization when fixtures have same parameters

No comments:

Post a Comment