0
0
PyTesttesting~15 mins

Test containers with Docker in PyTest - Build an Automation Script

Choose your learning style9 modes available
Verify application connects to a PostgreSQL database running in a Docker container
Preconditions (3)
Step 1: Start a PostgreSQL container using testcontainers in the test setup
Step 2: Wait until the database is ready to accept connections
Step 3: Connect to the PostgreSQL database using connection details from the container
Step 4: Create a test table and insert a sample record
Step 5: Query the inserted record to verify data is stored correctly
Step 6: Stop and remove the PostgreSQL container after the test
✅ Expected Result: The test should pass confirming that the application can connect to the PostgreSQL container, create and query data successfully.
Automation Requirements - pytest
Assertions Needed:
Assert that the inserted record is retrieved correctly from the database
Best Practices:
Use testcontainers Python library to manage Docker container lifecycle
Use explicit waits or retries to ensure database readiness
Use pytest fixtures for setup and teardown
Avoid hardcoding connection details; get them dynamically from the container
Keep tests isolated and clean up resources after test
Automated Solution
PyTest
import pytest
import psycopg2
from testcontainers.postgres import PostgresContainer

@pytest.fixture(scope='module')
def postgres_container():
    with PostgresContainer('postgres:15') as postgres:
        yield postgres


def test_postgres_connection(postgres_container):
    conn = psycopg2.connect(
        dbname=postgres_container.POSTGRES_DB,
        user=postgres_container.POSTGRES_USER,
        password=postgres_container.POSTGRES_PASSWORD,
        host=postgres_container.get_container_host_ip(),
        port=postgres_container.get_exposed_port(postgres_container.port)
    )
    cur = conn.cursor()
    cur.execute('CREATE TABLE test_table (id SERIAL PRIMARY KEY, name VARCHAR(50));')
    cur.execute("INSERT INTO test_table (name) VALUES ('testname') RETURNING id;")
    inserted_id = cur.fetchone()[0]
    conn.commit()

    cur.execute('SELECT name FROM test_table WHERE id = %s;', (inserted_id,))
    result = cur.fetchone()[0]

    cur.close()
    conn.close()

    assert result == 'testname'

This test uses the testcontainers library to start a PostgreSQL Docker container automatically before the test and stop it after.

The postgres_container fixture manages the container lifecycle with scope='module' so it runs once per test module.

Inside the test, it connects to the database using connection info provided by the container object, avoiding hardcoded values.

It creates a table, inserts a record, and queries it back to verify the database is working.

Assertions check that the retrieved data matches the inserted data.

This approach ensures the test is isolated, repeatable, and cleans up resources properly.

Common Mistakes - 4 Pitfalls
Hardcoding database connection details instead of using container properties
Not waiting for the database to be ready before connecting
Not cleaning up the container after tests
Using global or session scope for container without isolation
Bonus Challenge

Now add data-driven testing with 3 different names inserted and verified in the database

Show Hint