Skip to content

Pytest scope='module' fixture not delete model instance after testing module #873

Closed
@MaximMukhametov

Description

@MaximMukhametov

I create the message instance in a fixture with scope='module', right in the test file. But when the test reaches another module, this message instance still exists in the database.

in .../apps/dialogs/test/api/test_message.py

@pytest.fixture(scope='module')
def message_by_auth_user(django_db_setup, django_db_blocker,
                         message_factory: type,
                         user_factory: type,
                         user_with_auth: User) -> Message:
    """Return message by auth user."""
    with django_db_blocker.unblock():
        message = message_factory(written_by=user_with_auth)  # Message object (1)
        message_text = message.message  # 'text_message_№_1'
        return message

in .../apps/users/test/api/test_users.py

@pytest.mark.django_db
def test_get_users_view_with_filter(bool_value: bool,
                                    user_count_change: int,
                                    filter_pattern: str,
                                    api_auth_client: APIClient,
                                    user_with_auth: User,
                                    user_factory: type):
    message_count = Message.objects.all().count()  # 1
    message = Message.objects.first()  # Message object (1)
    message_text = message.message # 'text_message_№_1'

After I replaced the 'return' with a 'yield', and after the 'yield' I manually deleted the object, everything works correctly. But shouldn't the test do it automatically, as it does in my other fixtures? For example, if scope = 'function' then the test automatically deletes the object (after each test), without any 'yield'

If the message instance is not manually deleted, it will exist throughout the entire session, even if scope='module'. Why is this happening???

@pytest.fixture(scope='module')
def message_by_auth_user(django_db_setup, django_db_blocker,
                         message_factory: type,
                         user_factory: type,
                         user_with_auth: User) -> Message:
    """Return message by auth user."""
    with django_db_blocker.unblock():
        message = message_factory(written_by=user_with_auth)
        yield message
        message.delete()  # This code is executed when fixture run teardown, after testing current module

why does function scope fixtures delete it automatically after each test? I expect module scope fixture to have the same behavior after each test module.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions