0
0
PyTesttesting~10 mins

Test containers with Docker in PyTest - Test Execution Trace

Choose your learning style9 modes available
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.

Test Code - pytest
PyTest
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,)
Execution Trace - 5 Steps
StepActionSystem StateAssertionResult
1Test 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
2Test 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
3Cursor executes SQL query 'SELECT 1;' on the PostgreSQL container database.Query runs successfully inside the container database.-PASS
4Fetch 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
5Test ends and pytest fixture tears down the PostgreSQL Docker container.Docker container is stopped and removed.-PASS
Failure Scenario
Failing Condition: The test fails if the connection to the PostgreSQL container cannot be established or the query returns an unexpected result.
Execution Trace Quiz - 3 Questions
Test your understanding
What does the pytest fixture postgres_container do in this test?
AMocks the database connection without using Docker.
BRuns the test inside a Docker container.
CStarts and provides a temporary PostgreSQL Docker container for the test.
DCreates a permanent PostgreSQL database on the host.
Key Result
Using test containers with Docker allows tests to run against real services in isolated environments, improving reliability and reproducibility without needing permanent infrastructure.