pythonpytestfixtures

How to mix pytest fixtures that uses request and regular values for parametrize?


This is very hard for me to find in pytest documentation. That's why I'm asking here.

I have a fixture that is loading data.

import pytest

@pytest.fixture(scope="function")
def param_data(request):
    with open(f'tests/fixtures/{request.param}.json') as f:
        return json.load(f)

And with that, I want to test the execution of a function of 3 JSON files:

How can I do it using @pytest.mark.parametrize? I mean...

@pytest.mark.parametrize(???)
def test_my_function(dict, expected):
    # Test my_function() with the dict loaded by fixture and the expected result.
    assert my_function(dict) == expected

I see examples of both usages, but not with both of them. And, all the fixtures I see are fixed with a value return, not using request.param.


Solution

  • Use indirect parametrization along with "normal" parameters.

    import pytest
    
    @pytest.fixture
    def add_one(request):
        return 1 + request.param
    
    @pytest.mark.parametrize("add_one,expected", ((2, 3), (4, 5)), indirect=["add_one"])
    def test_my_func(add_one, expected):
        assert add_one == expected