5

Say I have a test function that takes a parametrize record as a dict, where one of its values is a fixture which is already defined.

For example, we have a fixture:

@pytest.fixture
def a_value():
    return "some_value"

And the test function:

@pytest.mark.parametrize("record", [{"a": a_value, "other": "other_value"},
                                    {"a": a_value, "another": "another_value"}])
def test_record(record):
    do_something(record)

Now, I know that this can be solved by passing the fixture to the test function and updating the record accordingly, like:

@pytest.mark.parametrize("record", [{"other": "other_value"},
                                    {"another": "another_value"}])
def test_record(a_value, record):
    record["a"] = a_value
    do_something(record)

But I was wondering if there is a way of doing this without this "workaround", when I have many fixtures that are already defined and I just want to use them in each parametrized record I pass to the function.

I have already checked this question, although it doesn't seem to fit my case exactly. Couldn't find a correct use from the answers there.

A. Sarid
  • 3,916
  • 2
  • 31
  • 56
  • 1
    Related: [metafunc parametrization](https://stackoverflow.com/a/49117044/674039) – wim Jan 07 '19 at 20:13
  • Thanks @wim - If I understand correctly, this requires me to modify the comment for running the tests. Is there a way to do it by code? – A. Sarid Jan 08 '19 at 11:08

1 Answers1

0

One solution is to create record as a fixture rather than using parametrize and accept a_value as a paraemter:

@pytest.fixture
def record(a_value):
    return {
        'a': a_value,
        'other': 'other_value',
    }
Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
  • Thanks! But then, how do you parametrize over different `record`s? I've edited my question to have few different values for the `record` parameter. – A. Sarid Jan 07 '19 at 18:38
  • @A.Sarid In your example, the record only has two fields. In practice, how many fields will the records really have? – Code-Apprentice Jan 07 '19 at 18:44
  • Varies, that's the whole reason for using the parametrize, some will have 2 and some will have more key-value pairs. Although all records will include a fixture such as `a_value` in my example. – A. Sarid Jan 07 '19 at 19:09
  • @A.Sarid I tip from someone who knows more than I do about pytest suggested `metafunc.parametrize`: https://docs.pytest.org/en/latest/parametrize.html#basic-pytest-generate-tests-example – Code-Apprentice Jan 07 '19 at 19:54