Jay Joshi
Jay Joshi

Reputation: 1562

Define Fixture along with pytest_generate_tests

Is there a way to define a Fixture function along with pytest_generate_tests?

When I implement fixture with pytest_generate_tests, the fixture is not being executed.

import pytest 
import time 

@pytest.fixture
def splunk_searchtime():
    time.sleep(5)
    print("Wow okay")

def pytest_generate_tests(metafunc):
    """
    Parse the fixture dynamically.
    """
    for fixture in metafunc.fixturenames:
        if fixture.startswith("splunk_searchtime"):
            metafunc.parametrize(fixture, [1,2,3])


def test_one(splunk_searchtime):
    pass

def test_two(splunk_searchtime):
    pass

It only runs when I comment pytest_generate_tests.

I know the fixture can be parameterized directly. But I want pytest_generate_tests as well because there are a 9-10 fixtures which are being generated with it. So parameterizing fixture directly with @pytest.fixture(params=[]) doesn't seem to be an option to my project.

Upvotes: 0

Views: 702

Answers (1)

Jay Joshi
Jay Joshi

Reputation: 1562

Solved the issue.!

I just had to create another fixture.

So there are now 2 fixtures.

  1. Parameterize the test cases
  2. Perform setup required for the test cases

Snippet:

import pytest 
import time 

@pytest.fixture
def splunk_searchtime(param_fixture):
    time.sleep(param_fixture)
    print("Wow okay")

def pytest_generate_tests(metafunc):
    global splunk_searchtime
    """
    Parse the fixture dynamically.
    """
    # global splunk_searchtime
    for fixture in metafunc.fixturenames:
        if fixture.startswith("param_fixture"):
            metafunc.parametrize("param_fixture", [1,2,3, 4])

def test_one(splunk_searchtime):
    pass

def test_two(splunk_searchtime):
    pass

Upvotes: 2

Related Questions