Bird
Raised Fist0
PyTesttesting~10 mins

Test containers with Docker in PyTest - Interactive Code Practice

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to start a Docker container for testing using pytest.

PyTest
from testcontainers.mysql import MySqlContainer

def test_mysql_container():
    with MySqlContainer("mysql:8.0") as [1]:
        assert container.is_running
Drag options to blanks, or click blank then click option'
Aservice
Bclient
Cdocker
Dcontainer
Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable name that does not represent the container instance.
Forgetting to assign the container to a variable.
2fill in blank
medium

Complete the code to get the connection URL from the running MySQL container.

PyTest
from testcontainers.mysql import MySqlContainer

def test_connection_url():
    with MySqlContainer("mysql:8.0") as container:
        url = container.[1]()
        assert url.startswith("mysql://")
Drag options to blanks, or click blank then click option'
Aconnection_url
Bget_connection_url
Cget_url
Dconnection_string
Attempts:
3 left
💡 Hint
Common Mistakes
Using an attribute instead of a method.
Using incorrect method names like 'connection_url' without parentheses.
3fill in blank
hard

Fix the error in the code to properly start a PostgreSQL test container.

PyTest
from testcontainers.postgres import PostgresContainer

def test_postgres():
    container = PostgresContainer("postgres:13")
    container.[1]()
    assert container.is_running
    container.stop()
Drag options to blanks, or click blank then click option'
Astart
Blaunch
Crun
Dbegin
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'run()' or 'launch()' which are not valid methods.
Forgetting to call the method with parentheses.
4fill in blank
hard

Fill both blanks to create a test that uses a Redis container and checks if it is running.

PyTest
from testcontainers.redis import RedisContainer

def test_redis_container():
    with RedisContainer() as [1]:
        assert [2].is_running
Drag options to blanks, or click blank then click option'
Aredis_container
Bredis
Ccontainer
Dclient
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names in the 'with' statement and assertion.
Using generic names like 'client' that do not represent the container.
5fill in blank
hard

Fill all three blanks to create a test that starts a MongoDB container, gets its connection URL, and asserts it contains 'mongodb://'.

PyTest
from testcontainers.mongodb import MongoDbContainer

def test_mongodb_connection():
    with MongoDbContainer("mongo:5.0") as [1]:
        url = [2].[3]()
        assert "mongodb://" in url
Drag options to blanks, or click blank then click option'
Amongo_container
Bmongo
Cget_connection_url
Dconnection_url
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names for the container instance.
Using 'connection_url' as an attribute instead of a method.
Forgetting parentheses when calling the method.

Practice

(1/5)
1. What is the main benefit of using test containers with Docker in pytest?
easy
A. They make tests run faster by skipping setup steps.
B. They replace the need for writing any test code.
C. They automatically fix bugs in the application code.
D. They provide real service environments during tests for better reliability.

Solution

  1. Step 1: Understand test containers purpose

    Test containers run real services like databases inside Docker during tests.
  2. Step 2: Identify benefit in pytest context

    This makes tests more reliable and realistic by using actual service environments.
  3. Final Answer:

    They provide real service environments during tests for better reliability. -> Option D
  4. Quick Check:

    Real service environment = Better test reliability [OK]
Hint: Remember: test containers run real services inside Docker [OK]
Common Mistakes:
  • Thinking test containers replace writing tests
  • Believing they fix code bugs automatically
  • Assuming tests run faster by skipping setup
2. Which pytest fixture code correctly starts a Docker container for testing?
easy
A. def container(): container = docker.run('redis') yield container container.stop()
B. def container(): client = docker.from_env() container = client.run('redis') yield container container.stop()
C. def container(): client = docker.from_env() container = client.containers.run('redis', detach=True) yield container container.stop()
D. def container(): client = docker.from_env() container = client.containers.run('redis') container.start() yield container container.stop()

Solution

  1. Step 1: Check correct Docker client usage

    Use docker.from_env() to get client, then client.containers.run() with detach=True to start container.
  2. Step 2: Verify fixture lifecycle management

    Yield container for test, then stop container after test finishes.
  3. Final Answer:

    def container(): client = docker.from_env() container = client.containers.run('redis', detach=True) yield container container.stop() -> Option C
  4. Quick Check:

    Use client.containers.run with detach=True [OK]
Hint: Use client.containers.run with detach=True to start container [OK]
Common Mistakes:
  • Calling client.run instead of client.containers.run
  • Missing detach=True causing blocking call
  • Not stopping container after test
3. Given this pytest fixture, what will be printed when running the test?
import pytest
import docker

@pytest.fixture
 def redis_container():
    client = docker.from_env()
    container = client.containers.run('redis:alpine', detach=True)
    yield container
    container.stop()

def test_redis_running(redis_container):
    print(redis_container.status)
medium
A. running
B. created
C. exited
D. paused

Solution

  1. Step 1: Understand container lifecycle in fixture

    Container is started with detach=True, so status should be 'running' during test.
  2. Step 2: Check printed status in test

    redis_container.status returns current container status, expected 'running' while test runs.
  3. Final Answer:

    running -> Option A
  4. Quick Check:

    Container started = status 'running' [OK]
Hint: Container status is 'running' while test uses it [OK]
Common Mistakes:
  • Expecting 'created' before container starts
  • Assuming container is 'exited' during test
  • Confusing status with container image tag
4. Identify the error in this pytest fixture that manages a Docker container:
@pytest.fixture
def redis_container():
    client = docker.from_env()
    container = client.containers.run('redis', detach=True)
    yield container
    container.remove()
medium
A. Missing container.stop() before container.remove() to stop container properly.
B. Using container.remove() instead of container.delete() which is invalid.
C. Not specifying environment variables for Redis container causes failure.
D. Yielding container before starting it causes runtime error.

Solution

  1. Step 1: Check container cleanup steps

    Container must be stopped before removal to avoid errors.
  2. Step 2: Identify missing stop call

    Fixture calls container.remove() but misses container.stop() before it.
  3. Final Answer:

    Missing container.stop() before container.remove() to stop container properly. -> Option A
  4. Quick Check:

    Stop container before remove to clean up [OK]
Hint: Always stop container before removing it [OK]
Common Mistakes:
  • Calling remove without stopping container
  • Confusing remove() with non-existent delete()
  • Assuming environment vars are mandatory for container start
5. You want to write a pytest fixture that starts a PostgreSQL container with Docker, waits until it is ready to accept connections, and then yields it for tests. Which approach correctly combines container management and readiness check?
hard
A. Start container without detach, yield immediately, and rely on test to wait for readiness.
B. Start container with detach=True, then poll container logs until 'database system is ready' appears before yielding.
C. Start container with detach=True and yield immediately without any readiness check.
D. Start container with detach=True, sleep fixed 1 second, then yield container.

Solution

  1. Step 1: Manage container lifecycle properly

    Start PostgreSQL container detached to run in background during tests.
  2. Step 2: Implement readiness check before yielding

    Poll container logs for 'database system is ready' message to ensure service is ready.
  3. Step 3: Yield container after readiness confirmed

    This ensures tests run only after PostgreSQL is ready to accept connections.
  4. Final Answer:

    Start container with detach=True, then poll container logs until 'database system is ready' appears before yielding. -> Option B
  5. Quick Check:

    Wait for readiness log before yielding container [OK]
Hint: Wait for readiness log, don't guess with sleep [OK]
Common Mistakes:
  • Yielding container before it is ready
  • Using fixed sleep instead of log polling
  • Starting container without detach causing blocking