close

How to parametrize a Pytest fixture

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to parametrize a Pytest fixture in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to parametrize a Pytest fixture?

  1. How to parametrize a Pytest fixture?

    The use of indirect parametrization works, but I find the need to use request.param as a magic, unnamed variable a little awkard.

  2. parametrize a Pytest fixture

    The use of indirect parametrization works, but I find the need to use request.param as a magic, unnamed variable a little awkard.

Method 1

instead of indirect parametrization, or my hacky solution below involving inheritance, you can also just use the params argument to @pytest.fixture() — i think this is the simplest solution maybe?

import pytest

class TimeLine:
    def __init__(self, instances=[0, 0, 0]):
        self.instances = instances


@pytest.fixture(params=[
    [1, 2, 3], [2, 4, 5], [6, 8, 10]
])
def timeline(request):
    return TimeLine(request.param)


def test_timeline(timeline):
    for instance in timeline.instances:
        assert instance % 2 == 0

Method 2

The use of indirect parametrization works, but I find the need to use request.param as a magic, unnamed variable a little awkard.

Here’s a pattern I’ve used. It’s awkward in a different way, arguably, but perhaps you’ll prefer it too!

import pytest

class TimeLine:
    def __init__(self, instances):
        self.instances = instances


@pytest.fixture
def instances():
    return [0, 0, 0]


@pytest.fixture
def timeline(instances):
    return TimeLine(instances)


@pytest.mark.parametrize('instances', [
    [1, 2, 3], [2, 4, 5], [6, 8, 10]
])
def test_timeline(timeline):
    for instance in timeline.instances:
        assert instance % 2 == 0

the timeline fixture depends on another fixture called instances, which has a default vale of [0,0,0], but in the actual test, we use parametrize to inject a series of different values for instances.

the advantage as I see it is that everything has a good name, plus you don’t need to pass that indirect=True flag.

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read