Django Pytest. Use database entries in parametrize

Viewed 68

I want to have a test for data that will use real data from DB.

The goal is to go through all the entries of a table Foo and apply some test logic on each entry. Ideally is to use parametrize for that but I am a bit struggling with DB access to parametrize.

What I do so far:

tests.py

import pytest
from app.models import Foo

pytestmark = pytest.mark.django_db

@pytest.fixture(scope='session')
def django_db_setup():
    settings.DATABASES['default'] = {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': os.environ['DB_NAME'],
        'USER': os.environ['DB_USER'],
        'PASSWORD': os.environ['DB_PASSWORD'],
        'HOST': 'localhost',
    }

@pytest.mark.django_db
class TestFoo:
    @pytest.mark.parametrize('foo', Foo.objects.all())
    def test_foo_objects(self, foo):
        assert foo.is_ok

Eventually I get

E RuntimeError: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it.

However, if DB-access is not used in parametrize - it works. I.e inside test_foo_objects DB-access is allowed.

So the question is how to allow parametrize use DB as well?

0 Answers
Related