Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django parallel testing: Test processes incorrectly accessing test databases

I have a Django 3.0.8 project running locally, connected to a local PostgreSQL database (postgres:///myapp). When I run the python manage.py test, my unit tests run fine; a test database called test_myapp automatically gets created, and it's correctly accessed.

However, when I run python manage.py test --parallel 8, the test fails. I see that 8 cloned databases are correctly generated (test_myapp_1, test_myapp_2,..., test_myapp_8), but I get errors like these:

psycopg2.OperationalError: FATAL:  database "myapp_3" does not exist

It appears that for parallel tests, databases are accessed incorrectly (trying to access the database myapp_N rather than test_myapp_N). I'm trying to figure out if my local config has issues, but this is all I have in my base config:

DATABASES = {
    'default': env.db('DATABASE_URL', default='postgres:///myapp'),
}
DATABASES['default']['ATOMIC_REQUESTS'] = True

Why are my parallel tests processes not accessing their respective cloned test databases correctly?

like image 828
sunw Avatar asked Jan 19 '26 06:01

sunw


1 Answers

A simple solution that worked for me is to explicitly specify the test database name in settings.py, e.g.,

DATABASES = {
    'default': {
        ...
        'TEST': {
            # Avoid naming it the same as your original database name. 
            # Otherwise, it will be used while testing (and even may get deleted).
            'NAME': 'name_of_your_choice',
        },
    },
    ...
}

If you are using multiple databases, you may need to do it for all of them.

like image 165
Dipen Dadhaniya Avatar answered Jan 21 '26 23:01

Dipen Dadhaniya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!