admin管理员组

文章数量:1122832

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:

  • tests/fixtures/data1.json
  • tests/fixtures/data2.json
  • tests/fixtures/data3.json

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.

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:

  • tests/fixtures/data1.json
  • tests/fixtures/data2.json
  • tests/fixtures/data3.json

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.

Share Improve this question asked Nov 21, 2024 at 14:49 jcfaraccojcfaracco 8942 gold badges8 silver badges23 bronze badges 1
  • I can return a tuple in my fixture, but I wonder if there is a beautiful way to do it. – jcfaracco Commented Nov 21, 2024 at 15:09
Add a comment  | 

1 Answer 1

Reset to default 1

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

本文标签: pythonHow to mix pytest fixtures that uses request and regular values for parametrizeStack Overflow