Skip to content

Suggestion: add new 'parametrization' fixture scope #1552

Description

@csaftoiu

Currently, a fixture can be scoped as function, class, module, or session.

I propose a fixture can also be scoped per parametrization.

Consider:

import time
@pytest.fixture
def slow_setup():
    time.sleep(1)
    return 'foo'

If I have a group of tests which I am parametrizing, but that would share this value, it'll do the setup for each one (as expected):

# takes 4 seconds
@pytest.mark.parametrize('bar', [1, 2, 3, 4])
def test_parametrized(slow_setup, bar):
    assert slow_setup == 'foo'

If I wanted to run the same group of tests but sharing the fixture, I only really have one option (considering that other tests in the same module need the fixture to be re-set up each time, so I can't use module or session scope): set the fixture scope to class, and put the tests inside a class:

@pytest.fixture(scope='class')
def slow_setup_cls():
    time.sleep(1)
    return 'foo'

# takes 1 second
class TestParametrized(object):
    @pytest.mark.parametrize('bar', [1, 2, 3, 4])
    def test_parametrized(self, slow_setup_cls, bar):
        assert slow_setup_cls == 'foo'

However, the meaning I really intend to convey is "this fixture should be shared across all parametrizations of a function". I propose the following:

@pytest.fixture(scope='parametrization')
def slow_setup_pmt():
    time.sleep(1)
    return 'foo'

# takes 1 second
@pytest.mark.parametrize('bar', [1, 2, 3, 4])
def test_parametrized(self, slow_setup_pmt, bar):
    assert slow_setup_pmt == 'foo'

This fixture scope conveys, to me: "All parametrizations of this test share the same setup and teardown with regards to this fixture."

Metadata

Metadata

Assignees

No one assigned

    Labels

    status: help wanteddevelopers would like help from experts on this topictopic: parametrizerelated to @pytest.mark.parametrizetype: backward compatibilitymight present some backward compatibility issues which should be carefully noted in the changelogtype: enhancementnew feature or API change, should be merged into features branchtype: feature-branchnew feature or API change, should be merged into features branchtype: proposalproposal for a new feature, often to gather opinions or design the API around the new feature

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions