0
0
PyTesttesting~7 mins

Test containers with Docker in PyTest

Choose your learning style9 modes available
Introduction

Test containers help you run real services like databases in Docker during tests. This makes tests more reliable and close to real use.

When you want to test your code with a real database instead of a fake one.
When your application depends on external services like Redis or Kafka during tests.
When you want to isolate tests so they don't affect your local environment.
When you want consistent test environments on different machines or CI servers.
Syntax
PyTest
from testcontainers.postgres import PostgresContainer
import pytest
from sqlalchemy import create_engine

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


def test_database_connection(postgres_container):
    engine = create_engine(postgres_container.get_connection_url())
    # Your test code here

Use with PostgresContainer('image') to start and stop the container automatically.

Use pytest fixtures to manage container lifecycle during tests.

Examples
This example shows how to start a Redis container for testing.
PyTest
from testcontainers.redis import RedisContainer

with RedisContainer('redis:7') as redis:
    redis_url = redis.get_connection_url()
    # Connect your app to redis_url
Fixture to start a MySQL container for each test function.
PyTest
import pytest
from testcontainers.mysql import MySqlContainer

@pytest.fixture(scope='function')
def mysql_container():
    with MySqlContainer('mysql:8') as mysql:
        yield mysql
Sample Program

This test starts a Postgres container, creates a table, inserts data, and queries it to check correctness.

PyTest
from testcontainers.postgres import PostgresContainer
from sqlalchemy import create_engine, text
import pytest

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


def test_insert_and_query(postgres_container):
    engine = create_engine(postgres_container.get_connection_url())
    with engine.connect() as conn:
        conn.execute(text('CREATE TABLE test (id INT PRIMARY KEY, name VARCHAR(50));'))
        conn.execute(text("INSERT INTO test (id, name) VALUES (1, 'Alice');"))
        conn.commit()
        result = conn.execute(text('SELECT name FROM test WHERE id=1;'))
        name = result.scalar()
        assert name == 'Alice'
        print(f'Queried name: {name}')
OutputSuccess
Important Notes

Make sure Docker is running before you run tests using test containers.

Test containers automatically clean up after tests, so no leftover services remain.

Use lightweight official images to keep tests fast.

Summary

Test containers let you run real services in Docker during tests.

Use pytest fixtures to manage container lifecycle easily.

This approach makes tests more reliable and closer to real-world use.