Testcontainers Core¶
testcontainers-core is the core functionality for spinning up Docker containers in test environments.
- class BytesExecResult(exit_code, output)¶
- class DockerContainer(image: str, docker_client_kw: dict[str, Any] | None = None, command: str | None = None, env: dict[str, str] | None = None, name: str | None = None, ports: list[int] | None = None, volumes: list[tuple[str, str, str]] | None = None, network: Network | None = None, network_aliases: list[str] | None = None, _wait_strategy: WaitStrategy | None = None, transferables: list[tuple[bytes | Path, str] | tuple[bytes | Path, str, int]] | None = None, **kwargs: Any)¶
Basic container object to spin up Docker instances.
- Parameters:
image – The name of the image to start.
docker_client_kw – Dictionary with arguments that will be passed to the docker.DockerClient init.
command – Optional execution command for the container.
name – Optional name for the container.
ports – Ports to be exposed by the container. The port number will be automatically assigned on the host, use
get_exposed_port(PORT)method to get the port number on the host.volumes – Volumes to mount into the container. Each entry should be a tuple with three values: host path, container path and mode (default ‘ro’).
network – Optional network to connect the container to.
network_aliases – Optional list of aliases for the container in the network.
>>> from testcontainers.core.container import DockerContainer >>> from testcontainers.core.waiting_utils import wait_for_logs >>> with DockerContainer("hello-world") as container: ... delay = wait_for_logs(container, "Hello from Docker!")
- copy_into_container(transferable: bytes | Path, destination_in_container: str, mode: int = 420) None¶
- exec(command: str | list[str] | ExecConfig) BytesExecResult¶
- get_container_info() ContainerInspectInfo | None¶
Get container information via docker inspect (lazy loaded).
- Returns:
Container inspect information or None if container is not started.
- get_wrapped_container() Container¶
- waiting_for(strategy: WaitStrategy) Self¶
Set a wait strategy to be used after container start.
- with_bind_ports(container: str | int, host: str | int | None = None) Self¶
Bind container port to host port
- Parameters:
container – container port
host – host port
- Doctest:
>>> from testcontainers.core.container import DockerContainer >>> container = DockerContainer("nginx") >>> container = container.with_bind_ports("8080/tcp", 8080) >>> container = container.with_bind_ports("8081/tcp", 8081)
- with_copy_into_container(transferable: bytes | Path, destination_in_container: str, mode: int = 420) Self¶
- with_exposed_ports(*ports: str | int) Self¶
Expose ports from the container without binding them to the host.
- Parameters:
ports – ports to expose
- Doctest:
>>> from testcontainers.core.container import DockerContainer >>> container = DockerContainer("nginx") >>> container = container.with_exposed_ports("8080/tcp", "8081/tcp")
- class ExecConfig(command: str | list[str], user: str | None = None, environment: dict[str, str] | None = None, workdir: str | PathLike[str] | None = None, privileged: bool = False)¶
Configuration for a command executed inside a running container.
Backend-agnostic data carrier. Only command is required, and every other field defaults to None/False.
command accepts either an argv list[str] or a str. Both are forwarded untouched.
- class Network(docker_client_kw: dict[str, Any] | None = None, docker_network_kw: dict[str, Any] | None = None)¶
Network context manager for programmatically connecting containers.
- class DockerImage(path: str | PathLike[str], docker_client_kw: dict[str, Any] | None = None, tag: str | None = None, clean_up: bool = True, dockerfile_path: str = 'Dockerfile', no_cache: bool = False, **kwargs: Any)¶
Basic image object to build Docker images.
>>> from testcontainers.core.image import DockerImage >>> with DockerImage(path=f"{TEST_DIR}/core/image_fixtures/sample/", tag="test-image") as image: ... logs = image.get_logs()
- Parameters:
path – Path to the build context
docker_client_kw – Keyword arguments to pass to the DockerClient
tag – Tag for the image to be built (default: None)
clean_up – Remove the image after exiting the context (default: True)
dockerfile_path – Path to the Dockerfile within the build context path (default: Dockerfile)
no_cache – Bypass build cache; CLI’s –no-cache
kwargs – Additional keyword arguments to pass to the underlying docker-py
- class DbContainer(image: str, docker_client_kw: dict[str, Any] | None = None, command: str | None = None, env: dict[str, str] | None = None, name: str | None = None, ports: list[int] | None = None, volumes: list[tuple[str, str, str]] | None = None, network: Network | None = None, network_aliases: list[str] | None = None, _wait_strategy: WaitStrategy | None = None, transferables: list[tuple[bytes | Path, str] | tuple[bytes | Path, str, int]] | None = None, **kwargs: Any)¶
DEPRECATED (for removal) Please use database-specific container classes or SqlContainer instead. # from testcontainers.community.generic.sql import SqlContainer
Generic database container.
- class WaitStrategy¶
Base class for all wait strategies.
Compose¶
It is also possible to use Docker Compose functionality:
- class ComposeContainer(ID: str | None = None, Name: str | None = None, Command: str | None = None, Project: str | None = None, Service: str | None = None, State: str | None = None, Health: str | None = None, ExitCode: int | None = None, Publishers: list[PublishedPortModel] = <factory>)¶
A container class that represents a container managed by compose. It is not a true testcontainers.core.container.DockerContainer, but you can use the id with DockerClient to get that one too.
- class DockerCompose(context: str | PathLike[str], compose_file_name: str | list[str] | None = None, pull: bool = False, build: bool = False, wait: bool = True, keep_volumes: bool = False, env_file: str | list[str] | None = None, services: list[str] | None = None, docker_command_path: str | None = None, profiles: list[str] | None = None, quiet_pull: bool = False, quiet_build: bool = False)¶
Manage docker compose environments.
- Parameters:
context – The docker context. It corresponds to the directory containing the docker compose configuration file.
compose_file_name – Optional. File name of the docker compose configuration file. If specified, you need to also specify the overrides if any.
pull – Pull images before launching environment.
build – Run docker compose build before running the environment.
wait – Wait for the services to be healthy (as per healthcheck definitions in the docker compose configuration)
env_file – Path(s) to an ‘.env’ file containing environment variables to pass to docker compose.
services – The list of services to use from this DockerCompose.
docker_command_path – The docker compose command to run.
profiles – The list of profiles to enable.
quiet_pull – Whether to suppress output when pulling images.
quiet_build – Whether to suppress output when building images.
Example
This example spins up chrome and firefox containers using docker compose.
>>> from testcontainers.compose import DockerCompose >>> compose = DockerCompose(f"{TEST_DIR}/core/compose_fixtures/basic", compose_file_name="hello.yaml", ... pull=True) >>> with compose: ... stdout, stderr = compose.get_logs() >>> "Hello from Docker!" in stdout True
services: hello-world: image: "hello-world"
- exec_in_container(command: list[str], service_name: str | None = None) tuple[str, str, int]¶
Executes a command in the container of one of the services.
- Parameters:
service_name – Name of the docker compose service to run the command in.
command – Command to execute.
service_name – specify the service name
command – the command to run in the container
- Returns:
stdout: Standard output stream. str: stderr: Standard error stream. int: exit_code: The command’s exit code.
- Return type:
- get_config(*, path_resolution: bool = True, normalize: bool = True, interpolate: bool = True) dict[str, Any]¶
Parse, resolve and returns compose file via docker config –format json. In case of multiple compose files, the returned value will be a merge of all files.
See: https://docs.docker.com/reference/cli/docker/compose/config/ for more details
- Parameters:
path_resolution – whether to resolve file paths
normalize – whether to normalize compose model
interpolate – whether to interpolate environment variables
- Returns:
Compose file
- get_containers(include_all: bool = False) list[ComposeContainer]¶
Fetch information about running containers via docker compose ps –format json. Available only in V2 of compose.
- Returns:
The list of running containers.
- get_logs(*services: str) tuple[str, str]¶
Returns all log output from stdout and stderr of a specific container.
- Parameters:
services – which services to get the logs for (or omit, for all)
- Returns:
stdout: Standard output stream. str: stderr: Standard error stream.
- Return type:
- get_service_host(service_name: str | None = None, port: int | None = None) str | None¶
Returns the host for one of the services.
- get_service_port(service_name: str | None = None, port: int | None = None) int | None¶
Returns the mapped port for one of the services.
- wait_for(url: str) Self¶
Waits for a response from a given URL. This is typically used to block until a service in the environment has started and is responding. Note that it does not assert any sort of return code, only check that the connection was successful.
This is a convenience method that internally uses HttpWaitStrategy. For more complex wait scenarios, consider using the structured wait strategies with waiting_for().
- Parameters:
url – URL from one of the services in the environment to use to wait on.
Example
# Simple URL wait (legacy style) compose.wait_for(”http://localhost:8080”) # For more complex scenarios, use structured wait strategies: from testcontainers.core.waiting_utils import HttpWaitStrategy, LogMessageWaitStrategy compose.waiting_for({ “web”: HttpWaitStrategy(8080).for_status_code(200), “db”: LogMessageWaitStrategy(“database system is ready to accept connections”) })
- waiting_for(strategies: dict[str, WaitStrategy]) Self¶
Set wait strategies for specific services.
- Parameters:
strategies – Dictionary mapping service names to wait strategies
- class PublishedPortModel(URL: str | None = None, TargetPort: int | None = None, PublishedPort: int | None = None, Protocol: str | None = None)¶
Class that represents the response we get from compose when inquiring status via DockerCompose.get_running_containers().
Examples¶
Using DockerContainer and DockerImage to create a container:
>>> from testcontainers.core.container import DockerContainer
>>> from testcontainers.core.waiting_utils import wait_for_logs
>>> from testcontainers.core.image import DockerImage
>>> with DockerImage(path=f"{TEST_DIR}/core/image_fixtures/sample/", tag="test-sample:latest") as image:
... with DockerContainer(str(image)) as container:
... delay = wait_for_logs(container, "Test Sample Image")
The DockerImage class is used to build the image from the specified path and tag. The DockerContainer class is then used to create a container from the image.
Copying a file from disk into a container:
>>> import tempfile
>>> from pathlib import Path
>>> from testcontainers.core.container import DockerContainer
>>> with tempfile.TemporaryDirectory() as tmp:
... my_file = Path(tmp) / "my_file.txt"
... _ = my_file.write_text("file content")
... with DockerContainer("bash", command="sleep infinity") as container:
... container.copy_into_container(my_file, "/tmp/my_file.txt")
... result = container.exec("cat /tmp/my_file.txt")
... result.output
b'file content'