简体   繁体   中英

Access Django Test Database

I have an API running on Heroku and would like to be able to test it using the test database. My problem I have is that the TestCase setUp(self) method adds the data to an automatically created test database. Then my tests send a POST request to the locally running version of itself. That code then is just using the regular default database instead of the test database the tests are running in.

Here's some code and what I've tried.

In my main settings.py I have named my database like so

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'theOneTrueDB',
    }
}

And I read here ( https://docs.djangoproject.com/en/3.0/topics/testing/overview/#the-test-database ) that

The default test database names are created by prepending test_ to the value of each NAME in DATABASES.

So I figured in my views file for one of my apps I could just do Tenant.objects.using('test_theOneTrueDB').all() and that would work but it says

django.db.utils.ConnectionDoesNotExist: The connection test_theOneTrueDB doesn't exist

I have also tried

Tenant.objects.using('test_default')

and many other things. I am lost. I would also be okay with setting up another database and then using that in the setup with

Tenant.objects.save(using='theOneTrueDBTest)

or something like that.

Any help would be appreciated!

EDIT: I know have my settings looking like this

DATABASES = {
    'default': {
        'NAME': 'theOneTrueDB',
        'ENGINE': 'django.db.backends.sqlite3',
    },
    'other': {
        'NAME': 'theOneTrueTest',
        'ENGINE': 'django.db.backends.sqlite3',
    }
}

but then if I try to save to the other database like this

tempPM.save(using='other')

Then I get this error

AssertionError: Database queries to 'other' are not allowed in this test. Add 'other' to API.tests.TenantLogin.databases to ensure proper test isolation and silence this failure.

You don't need to access the test database directly. It will be used by default and you don't need to worry about it.

By default for sqlite3 backend will be used in-memory database, with the name like this file:memorydb_default?mode=memory&cache=shared , you can examine the settings while tests are running via:

from django.conf import settings
print(settings.DATABASES)

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