Skip to content
Latchkey

pytest "ConnectionError" / "could not connect" to the Test Database

Tests that talk to a real database failed to open a connection. The DB service the tests expect - a CI service container or sidecar - is not reachable at the configured host/port, often because it is not ready yet.

What this error means

Tests abort with psycopg2.OperationalError: could not connect to server: Connection refused (or redis.exceptions.ConnectionError, pymysql ... Can't connect). The code is fine; the database the tests depend on is down, not started, or on a different host than configured.

Python traceback
psycopg2.OperationalError: could not connect to server: Connection refused
	Is the server running on host "localhost" (127.0.0.1) and accepting
	TCP/IP connections on port 5432?

Common causes

DB service not started or not ready

The CI service container started but is not accepting connections yet when tests run, so early connections are refused (a readiness race), or no DB service was declared at all.

Wrong host/port for the CI network

Tests point at localhost:5432, but in the CI network the database is reachable at a service hostname (e.g. postgres) or a mapped port - a host/port mismatch.

How to fix it

Declare the DB service and wait for readiness

Run the database as a service container with a health check, then point the tests at it.

.github/workflows/ci.yml
services:
  postgres:
    image: postgres:16
    env: { POSTGRES_PASSWORD: postgres }
    ports: ['5432:5432']
    options: >-
      --health-cmd "pg_isready -U postgres" --health-interval 5s
      --health-timeout 5s --health-retries 10

Use the correct host and a readiness gate

Set the DB URL the tests read, and wait until the port answers before running them.

Terminal
export DATABASE_URL=postgres://postgres:postgres@localhost:5432/test
until pg_isready -h localhost -p 5432; do sleep 1; done
pytest

How to prevent it

  • Run dependent databases as service containers with health checks.
  • Gate tests on a readiness probe instead of a fixed sleep.
  • Read DB host/port from env so local and CI configs differ cleanly.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →