pytest-dev / pytest-django

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

pytest.mark.django_db does not isolate tests #461

Closed qwiglydee closed 7 years ago

qwiglydee commented 7 years ago

pytest version 3.0.6 pytest-django-3.1.2 django-1.10

settings:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR + '/var/db.sqlite'
    },
    'world': {
        'ENGINE': 'django.contrib.gis.db.backends.postgis',
        'NAME': 'test',
        'HOST': '',
        'USER': 'postgres',  # need superuser to create db
        'TEST': {
            'NAME': 'test'
        }
    }
}

tests:

@pytest.mark.django_db
def test_1():
    models.Feature.objects.create(id=99999999, **dumb_attrs)

@pytest.mark.django_db
def test_2():
    models.Feature.objects.create(id=99999999, **dumb_attrs)

Running tests fails with IntegrityError. After running created objects remain in database.

blueyed commented 7 years ago

Is the Feature model being routed through the world DB?

qwiglydee commented 7 years ago

Yes, it is routed. But this indeed seems to be the problem. The same problem arises when using native django testrunner. Also, documentation says: "To have the GeoDjango tests executed when running the Django test suite with runtests.py all of the databases in the settings file must be using one of the spatial database backends."

I changed the testing settings to use one and only 'default' database, removed routing, and isolation started to work.

It seems like both for django testrunner and pytest runner problem is at using multiple databases. Or maybe it is even deeper than test runner.

blueyed commented 7 years ago

You need to enable multi_db. pytest-django does not support it easily currently though - see #431 and the issues referenced there.

pelme commented 7 years ago

Closing this since it is a multi_db problem, see the referenced issue above.

Feel free to comment/reopen this issue if I misunderstood it!