Search code examples
djangounix-socketpytest-django

Django Unit tests fail over domain socket


I have Django configured to use the database with peer authentication over the local Unix Domain socket, instead of user/password authentication. Here's the settings.DATABASES:

{'default': {'ENGINE': 'django.db.backends.postgresql',
             'NAME': 'mcps',
             'PORT': 5433,
             'TEST': {'ENGINE': 'django.db.backends.postgresql',
                      'NAME': 'mytestdb',
                      'PORT': 5433,
                      'USER': 'mcp'},
             'USER': 'mcp'}
}

The port is correctly configured, the application itself has no problem working correctly.

Yet, when I try to run pytest, with the environment variable DJANGO_SETTINGS_MODULE set to the above settings, a database is created - with the correct owner 'mcp' - but before tables are created I get an error:

django.db.utils.OperationalError: FATAL:  Peer authentication failed for user "mcp"

What are unit tests doing differently anmd how can I fix this please?


Solution

  • @Nader Alexan There's no host to set, communication goes over the local Unix domain socket. I tried adding

    'HOST': '/run/postgresql'
    

    as I had to do in pgAdmin, but that didn't solve the issue.

    It turns out that pytest also tries to access the database named 'postgres', even though the maintenance database is set to template1. I haven't been able to determine why, but adding access to that database explictely in pg_hba.conf enabled me to run the tests.

    Sorry if this explanation is a bit shaky, I'm new to forms of PG authentication other than username/password myself.