pytest-dev / pytest-django

A Django plugin for pytest.
https://pytest-django.readthedocs.io/
Other
1.33k stars 341 forks source link

`--reuse-db` does nothing and test database is flushed #1052

Open cursedgrape opened 1 year ago

cursedgrape commented 1 year ago

As per the docs:

Using --reuse-db will create the test database in the same way as manage.py test usually does. However, after the test run, the test database will not be removed. The next time a test run is started with --reuse-db, the database will instantly be re used. This will allow much faster startup time for tests.

This actually doesn't work

Here's pytest.ini

[pytest]
DJANGO_SETTINGS_MODULE = myproject.settings
addopts = --reuse-db

and here's django_db_setup

import sqlite3
import uuid

import pytest
from django.conf import settings
from django.contrib.auth.models import User
from django.core.management import call_command

@pytest.fixture(scope='session')
def test_user():
    return {
        'username': uuid.uuid4().hex[:10],
        'password': uuid.uuid4().hex,
    }

@pytest.fixture(scope='session')
def django_db_setup(django_db_blocker, test_user, django_db_keepdb):
    db_path = settings.BASE_DIR / 'test-db.sqlite3'
    sqlite3.connect(db_path.as_posix())
    settings.DATABASES['default']['NAME'] = db_path
    with django_db_blocker.unblock():
        call_command('migrate', '--noinput')
        User.objects.create_user(
            username=test_user['username'],
            password=test_user['password'],
            email=f'{test_user["username"]}@test',
            is_active=True,
        )

and django_db_keepdb evaluates to True. Here's the tests:

def test1(django_user_model, django_db_keepdb):
    print(django_db_keepdb, django_user_model.objects.all())

def test2(django_user_model, django_db_keepdb):
    print(django_db_keepdb, django_user_model.objects.all())

which results in:

True <QuerySet [<User: b18cd8369b>]>
True <QuerySet []>

and the expected results are

True <QuerySet [<User: b18cd8369b>]>
True <QuerySet [<User: b18cd8369b>]>

So, how to actually obtain this outcome?

robertddewey commented 6 months ago

Would like to know as well. The --reuse-db flag is useful to create the skeleton DB schema, but there are times where I want to actually inspect the data generated from all of the tests.