Search code examples
python-3.xtestingpytestfixtures

Using pytest fixture with parameter from mark


I try to create a test case in pytest. I want to use parameterized fixtures to get parameters from the @pytest.mark.parametrize decorator and create more types of tests. My code looks right now:

@pytest.mark.parametrize( 
    "a",
    ["1", "2"],
    ids=["a:1", "a:2"]
)
@pytest.mark.parametrize(  # type: ignore
    "fixture_a",
    [{"b": 1}],
    ids=["b:1"],
    indirect=["fixture_a"],
)
def test_postgres_basic(fixture_a, a):
    ...

What do I want?

I want to send parameter a to fixture_a so fixture request.param wouldn't be {"b": 1} but something like {"b":1, a: "1"} and {"b":1, a: "2"}. Is it possible in some easy way?

Thank you


Solution

  • An alternative is just define the value of a manually in the dict to be passed to the fixture.

    import pytest
    
    
    @pytest.fixture
    def fixture_a(request):
        print(f"{request.param=}")
        return request.param
    
    
    @pytest.mark.parametrize( 
        "fixture_a, a",
        [
            ({"a": 1, "b": 1}, "1"),
            ({"a": 2, "b": 1}, "2"),
        ],
        ids=["a:1", "a:2"],
        indirect=["fixture_a"],
    )
    def test_postgres_basic(fixture_a, a):
        print(fixture_a, a)
    

    Output

    $ pytest -q -rP
    ..
    [100%]
    ================================================================================================= PASSES ==================================================================================================
    ________________________________________________________________________________________ test_postgres_basic[a:1] _________________________________________________________________________________________
    ------------------------------------------------------------------------------------------ Captured stdout setup ------------------------------------------------------------------------------------------
    request.param={'a': 1, 'b': 1}
    ------------------------------------------------------------------------------------------ Captured stdout call -------------------------------------------------------------------------------------------
    {'a': 1, 'b': 1} 1
    ________________________________________________________________________________________ test_postgres_basic[a:2] _________________________________________________________________________________________
    ------------------------------------------------------------------------------------------ Captured stdout setup ------------------------------------------------------------------------------------------
    request.param={'a': 2, 'b': 1}
    ------------------------------------------------------------------------------------------ Captured stdout call -------------------------------------------------------------------------------------------
    {'a': 2, 'b': 1} 2
    2 passed in 0.06s