Search code examples
pythondjangodjango-rest-frameworkpytestpytest-django

How can i select needed db for Pytest? I have 2 - one remote, one local. I need pytest to be started on local


The default db is cloud one. And when pytest tries to create a temporary data it got permissions error. So i want to create a second database to be used with pytest. How can i select this database in pytest config?

DATABASES = {
    'default': {
        'NAME': config['database']['name'],
        'ENGINE': '...',
    },
    'tests_db': {
        "NAME": "tests_db",
        "ENGINE": 'django.db.backends.sqlite3',
    }
}

Solution

  • I prefer having separate development and production settings. My production doesn't get muddied with an sqlite database for no reason and I can speed up tests with less security/other benefits.

    settings/
    │   base.py
    │   heroku.py
    │   test.py
    
    # settings/test.py
    
    ...
    
    # Make password hashing faster
    PASSWORD_HASHERS = ('django.contrib.auth.hashers.MD5PasswordHasher',)
    
    # Use sqlite database
    DATABASES = {
        'default': {
            'NAME': config['database']['name'],
            'ENGINE': 'django.db.backends.sqlite3',
        }
    }
    

    Then change DJANGO_SETTINGS_MODULE to "settings.test" during tests. If you're using pytest with pytest-django, you can do this:

    # setup.cfg
    [tool:pytest]
    addopts = --reuse-db --ds=settings.test