joke2k / faker

Faker is a Python package that generates fake data for you.
https://faker.readthedocs.io
MIT License
17.33k stars 1.89k forks source link

pytest faker fixture is not session-based #2055

Open jgentil opened 1 month ago

jgentil commented 1 month ago

The faker documentation states here:

Out of the box, the faker fixture returns a session-scoped Faker instance to be used across all tests in your test suite.

But here it clearly is not defined to the session: https://github.com/joke2k/faker/blob/e0e0460ff715032ad5eda184d2fcb3720ce26b9c/faker/contrib/pytest/plugin.py#L23-L25 and there's even a "hidden" session-scoped faker: https://github.com/joke2k/faker/blob/e0e0460ff715032ad5eda184d2fcb3720ce26b9c/faker/contrib/pytest/plugin.py#L9-L11

I noticed that this functionality diverges from the original pytest-faker.

Steps to reproduce

@pytest.fixture(scope="session")
def current_user(faker):
    data = {
            "id":faker.uuid4(),
            "username":faker.user_name(),
            "first_name":faker.first_name(),
            "last_name":faker.last_name(),
            "email":faker.company_email(),
            "avatar":faker.file_name(category="image", extension="jpg"),
            "created_at":timezone.now() + timedelta(days=faker.random_int()),
            "updated_at":timezone.now() + timedelta(days=faker.random_int()),
    }
    user, _ = User.objects.get_or_create(**data)
ERROR [ 37%]
test setup failed
ScopeMismatch: You tried to access the function scoped fixture faker with a session scoped request object. Requesting fixture stack:
conftest.py:313:  def current_user(faker)
Requested fixture:
../../../Library/Caches/pypoetry/virtualenvs/api-YoAtlwgJ-py3.12/lib/python3.12/site-packages/faker/contrib/pytest/plugin.py:23:  def faker(request)

I need to scope a fixture that users faker to a session and I am finding it impossible to do.

fcurella commented 1 month ago

Thank you for the report @jgentil ! Do you mind submitting a Pull Request

jgentil commented 1 month ago

Yep I'd be glad to!

Would you prefer it be a separate "feature" that implements a session-based faker, or consider it a bug and fix this specific faker to be session-based? I'm worried about backward-compatibility if this has been used often or has become expected behavior.

fcurella commented 1 month ago

I would consider it a bug, but still increment the MAJOR version when we release