简体   繁体   中英

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',
    }
}

I found solution. For this kind of issue we have to create another db

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

And then in conftest.py we add

pytestmark = [pytest.mark.django_db(databases=["tests_db"])]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM