Test Overview
This test uses Docker containers to run a temporary PostgreSQL database. It verifies that the application can connect and query the database correctly.
This test uses Docker containers to run a temporary PostgreSQL database. It verifies that the application can connect and query the database correctly.
import pytest import psycopg2 from testcontainers.postgres import PostgresContainer @pytest.fixture(scope="module") def postgres_container(): with PostgresContainer("postgres:15-alpine") as postgres: yield postgres def test_postgres_connection(postgres_container): conn = psycopg2.connect( dbname=postgres_container.DBNAME, user=postgres_container.USER, password=postgres_container.PASSWORD, host=postgres_container.get_container_host_ip(), port=postgres_container.get_exposed_port(5432), ) cur = conn.cursor() cur.execute("SELECT 1;") result = cur.fetchone() cur.close() conn.close() assert result == (1,)
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts and pytest fixture postgres_container initializes a PostgreSQL Docker container using PostgresContainer. | Docker runs a temporary PostgreSQL 15-alpine container with default credentials and exposed port. | - | PASS |
| 2 | Test function test_postgres_connection connects to the PostgreSQL container using psycopg2 with container credentials and host/port. | Connection to the running PostgreSQL container is established. | - | PASS |
| 3 | Cursor executes SQL query 'SELECT 1;' on the PostgreSQL container database. | Query runs successfully inside the container database. | - | PASS |
| 4 | Fetch one row from the query result and close cursor and connection. | Result fetched is (1,). Database connection closed. | Assert that fetched result equals (1,). | PASS |
| 5 | Test ends and pytest fixture tears down the PostgreSQL Docker container. | Docker container is stopped and removed. | - | PASS |