Search code examples
pythonpytestfixtures

Shorter option names for pytest fixture variants with long names


I am testing a function with several incoming datasets defined as fixtures, but the fixture names get quite cumbersome to distinguish them from one another.

@pytest.fixture()
def dataset_with_foo():
    pass

@pytest.fixture()
def dataset_with_bar():
    pass

@pytest.fixture()
def dataset_with_foo_and_bar():
    pass

def test_something(dataset_with_foo_and_bar):
    pass

Is there a way to define some kind of alias for the option name to be shorter? For instance, something like:

@usesfixture("dataset_with_foo_and_bar", option_name="dataset")
def test_something(dataset):
    pass

Solution

  • Ok, the best way I could find to do it is by using deferred parametrized fixtures:

    @pytest.fixture()
    def dataset(request):
        mapping = {
            "with-foo": create_dataset_with_foo(),
            "with-bar": create_dataset_with_bar(),
            "with-foo-and-bar": create_dataset_with_foo_and_bar(),
        }
    
        return mapping[request.param]
    
    def create_dataset_with_foo():
        pass 
    
    def create_dataset_with_bar():
        pass
    
    def create_dataset_with_foo_and_bar():
        pass
    
    @pytest.mark.parametrize("dataset", ["with-foo"], indirect=True)
    def test_something(dataset):
        pass
    
    @pytest.mark.parametrize("dataset", ["with-foo-and-bar"], indirect=True)
    def test_something(dataset):
        pass
    

    There has been other attempts using pytest-lazy-fixture or specialized decorator, but I find it a bit too hacky.. https://gist.github.com/wcooley/7472b8de6edb1e8ceda560843c0519a8