Django: Use a read-only database within django test suite

Viewed 58

In my Django project, I'm using two databases, one of which is my own PostgreSQL database where I have the read and write rights, and the other one is an external PostgreSQL database in which I only have read-only rights. By the way, both databases have their own respective models, they aren't the same in any way.

It works perfectly in the context of the project, I can access both databases. However when I use the Django test suite using ./manage.py test, Django is trying to create a test database for the external database.

I don't want that, I want to be still able to access the external PostgreSQL database within the test suite without needing to create a test database on this external PostgreSQL database.

It also gives me this error:

/usr/local/lib/python3.10/site-packages/django/db/backends/postgresql/base.py:323: RuntimeWarning:
Normally Django will use a connection to the 'postgres' database to avoid
running initialization queries against the production database when it's not needed
(for example, when running tests).
Django was unable to create a connection to the 'postgres' database
and will use the first PostgreSQL database instead.

But I don't have access to the 'postgres' database in the external database and I don't want to run initialization queries against it.

Here is the configuration for the external read-only database connection:

DATABASES["aact"] = {
    "ENGINE": "django.db.backends.postgresql_psycopg2",
    "OPTIONS": {"options": "-c search_path=ctgov"},
    "NAME": AACT_DATABASE_NAME,
    "USER": AACT_DATABASE_USER,
    "PASSWORD": AACT_DATABASE_PASS,
    "HOST": AACT_DATABASE_HOST,
    "PORT": AACT_DATABASE_PORT,
    "TEST": {"NAME": AACT_DATABASE_NAME, "MIGRATE": False},
}
1 Answers

on test you can choose any database which you want.

in settings.py, or, much better, local_settings.py:

import sys

DATABASES["aact"] = {...}
if 'test' in sys.argv:
   DATABASES["aact"] = {settings for fake database with write permissions}

other way - define your DbRouter. https://docs.djangoproject.com/en/4.0/topics/db/multi-db/#database-routers

class BaseRouter:
    
    def db_for_read(self, model, **__):
        return "db for read"

    def db_for_write(self, model, **__):
        return "db for write"

after that in settings.py:

DATABASE_ROUTERS = ['somethere.whereis.BaseRouter']

The first example if fast to start. The second help you to make tests better.

Related