Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cause of pytest ValueError: fixture is being applied more than once to the same function

I have a unit test I'm running with a particular fixture. The fixture is pretty simple and looks like so:

@pytest.fixture
def patch_s3():
    # Create empty bucket
    bucket = s3_resource().create_bucket(Bucket=BUCKET)
    bucket.objects.all().delete()

    yield

    bucket.objects.all().delete()

and the test isn't all that complicated either. Here is the signature for the test:

def test_task_asg(patch_s3, tmp_path, monkeypatch)

However, when I run pytest, I get the following error:

tests/test_task_asg.py:313: in <module>
    @pytest.fixture
home/ubuntu/miniconda/envs/pipeline/lib/python3.7/site-packages/_pytest/fixtures.py:1150: in fixture
    fixture_function
home/ubuntu/miniconda/envs/pipeline/lib/python3.7/site-packages/_pytest/fixtures.py:1011: in __call__
    "fixture is being applied more than once to the same function"
E   ValueError: fixture is being applied more than once to the same function 

This is weird to me, as it seems to imply I'm somehow including patch_s3 more than once in test_task_asg. What could be causing this?

like image 815
code11 Avatar asked Dec 11 '25 11:12

code11


1 Answers

If you scroll up from your definition of patch_s3, you'll probably find another duplicate line like @pytest.fixture, causing the issue. That line can only be used once per fixture method definition.

The easiest way to reproduce this issue is with:

import pytest

@pytest.fixture(scope="session")
@pytest.fixture
def my_fixture():
    yield

def test_abc(my_fixture):
    pass

Running that with pytest yields ValueError: fixture is being applied more than once to the same function. But if you remove one of the two @pytest.fixture lines, then the issue goes away.

Here are some examples where other people had the same issue and fixed it:

  • https://github.com/pytest-dev/pytest/issues/3518
  • https://github.com/simonw/datasette/commit/969771770fcf795daace72e2310804e699067cfe
  • https://github.com/RhodiumGroup/rhg_compute_tools/pull/67
like image 196
Michael Mintz Avatar answered Dec 13 '25 17:12

Michael Mintz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!