1

I am using pytest parametrized fixtures, which have variable return values.

This is a simplified example:

import pytest


@pytest.fixture
def mocked_value(mock_param):
    if mock_param:
        mocked_value =  "true"
    else:
        mocked_value = "false"
    yield mocked_value


@pytest.mark.parametrize(("mock_param"), [True, False])
def test_both_mocked_parameters(mocked_value, mock_param):
    assert mocked_value == str(mock_param).lower()


@pytest.mark.parametrize(("mock_param"), [True])
def test_just_one_mocked_param(mocked_value, mock_param):
    assert mocked_value == "true"

Is there a way to make the pytest fixture have a default param given to it? Something like this, except built into the single fixture definition:

def _mocked_function(mock_param):
    if mock_param:
        mocked_value =  "true"
    else:
        mocked_value = "false"
    return mocked_value

@pytest.fixture
def mocked_value_with_default():
    yield _mocked_function(True)

@pytest.fixture
def mocked_value(mock_param):
    yield _mocked_function(mock_param)


@pytest.mark.parametrize(("mock_param"), [True, False])
def test_both_mocked_parameters(mocked_value, mock_param):
    assert mocked_value == str(mock_param).lower()


def test_just_one_mocked_param(mocked_value_with_default):
    assert mocked_value_with_default == "true"

The above works, however it would be much cleaner to have just one fixture definition handling both use cases. How do I do this?

enderland
  • 13,825
  • 17
  • 98
  • 152
  • Are you looking for that? https://stackoverflow.com/questions/42228895/how-to-parametrize-a-pytest-fixture – DevLounge Mar 12 '21 at 00:20
  • Not exactly - it's straightforward to have parametrized fixtures (in fact, my first example could easily just have `True` and `False` as parametrized inputs if I was always using both true/false all the time). What I want is to be able to reuse the fixture as a one time use fixture, with a default value, so I don't have to explicitly call `@pytest.mark.parametrize(("mock_param"), [True])`. – enderland Mar 12 '21 at 00:33

1 Answers1

0

You could use fixture parametrization: https://docs.pytest.org/en/stable/example/parametrize.html#indirect-parametrization

Denis Barmenkov
  • 2,276
  • 1
  • 15
  • 20