### Basic Valkey Container Usage Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/valkey.md Example demonstrating how to create and use a Valkey container. Ensure the Valkey module is installed. ```python from testcontainers.valkey import ValkeyContainer with ValkeyContainer() as valkey: # Valkey container is ready to use # You can access its connection details via valkey.get_connection_url() print(f"Valkey running on: {valkey.get_connection_url()}") ``` -------------------------------- ### Basic PostgreSQL Container Example Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/postgres.md This example demonstrates how to create and use a basic PostgreSQL container. Ensure you have the necessary dependencies installed. ```python from testcontainers.postgres import PostgresContainer def test_postgres_basic_authentication(): with PostgresContainer("postgres:15.3") as postgres: assert postgres.get_connection_url() == "postgresql://test:test@localhost:5432/test" ``` -------------------------------- ### Spin up a Postgres Container and Connect Source: https://github.com/testcontainers/testcontainers-python/blob/main/modules/postgres/README.md This example demonstrates how to initialize a PostgresContainer and connect to it using the psycopg driver. Ensure the psycopg library is installed. ```python from testcontainers.postgres import PostgresContainer postgres_container = PostgresContainer("postgres:13.3") with postgres_container as postgres: connection = postgres.get_connection() with connection.cursor() as cursor: cursor.execute("SELECT 1") assert cursor.fetchone()[0] == 1 ``` -------------------------------- ### Basic Kafka Container Usage Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/kafka.md Example of creating and using a Kafka container. Ensure you have the Kafka module installed. ```python from testcontainers.kafka import KafkaContainer kafka_container = KafkaContainer() kafka_container.start() # Use the Kafka container, e.g., get bootstrap servers bootstrap_servers = kafka_container.get_bootstrap_servers() print(f"Bootstrap servers: {bootstrap_servers}") kafka_container.stop() ``` -------------------------------- ### Basic Registry Container Usage Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/registry.md Example demonstrating how to create and use a Registry container. This snippet shows the fundamental setup for a registry. ```python from testcontainers.registry import RegistryContainer def test_registry_container(): with RegistryContainer() as registry: assert registry.get_url() is not None ``` -------------------------------- ### start Source: https://github.com/testcontainers/testcontainers-python/blob/main/core/README.md Starts the docker compose environment. ```APIDOC ## start ### Description Starts the docker compose environment. ### Method Not specified (assumed to be a Python method call) ### Parameters None ### Returns None ``` -------------------------------- ### Common Use Case - Application Startup Verification Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/features/container_logs.md Monitor container logs to confirm that an application has started successfully. This example waits for the 'Application started' message. ```python with GenericContainer("myapp:latest") as container: # Wait for application to start for line in container.follow_logs(): if "Application started" in line: break ``` -------------------------------- ### Basic K3s Container Usage Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/k3s.md Example demonstrating the creation and basic usage of a K3s container. Ensure the necessary dependencies are installed. ```python from testcontainers.k3s import K3sContainer with K3sContainer() as k3s: print(f"K3s API endpoint: {k3s.get_k3s_api_endpoint()}") print(f"K3s token: {k3s.get_k3s_token()}") ``` -------------------------------- ### Install Dependencies with Make Source: https://github.com/testcontainers/testcontainers-python/blob/main/index.md Run this command to set up your local development environment after installing uv. ```bash make install ``` -------------------------------- ### Basic RabbitMQ Container Usage Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/rabbitmq.md Example of creating and using a RabbitMQ container. Ensure you have the RabbitMQ module installed. ```python from testcontainers.rabbitmq import RabbitMQContainer with RabbitMQContainer("rabbitmq:latest") as rabbitmq: # You can now use the rabbitmq container # For example, get the connection string: connection_string = rabbitmq.get_connection_url() print(f"RabbitMQ connection string: {connection_string}") # You can also access other properties like: # host = rabbitmq.get_host() # port = rabbitmq.get_port() # username = rabbitmq.username # password = rabbitmq.password ``` -------------------------------- ### Basic Scylla Container Usage Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/scylla.md Example of creating and using a Scylla container. Ensure the Scylla module is installed before running this code. ```python from testcontainers.scylla import ScyllaContainer with ScyllaContainer() as scylla: print(f"Scylla container running on port {scylla.get_exposed_port(9042)}") ``` -------------------------------- ### Basic AWS Container Usage Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/aws.md Example demonstrating the creation of an AWS container. This snippet requires the AWS module to be installed. ```python from testcontainers.aws.awsproxy import AWSProxy with AWSProxy() as aws: # Use aws container here pass ``` -------------------------------- ### Basic Selenium Container Usage Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/selenium.md Example demonstrating how to create and use a Selenium container with Testcontainers for Python. Ensure the Selenium module is installed. ```python from testcontainers.selenium import SeleniumContainer with SeleniumContainer() .with_chrome() as driver: driver.get("http://www.google.com") print(driver.title) ``` -------------------------------- ### Install SFTP module dependencies Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/sftp.md Run this command to install the necessary packages for the SFTP module. ```bash pip install testcontainers[sftp] paramiko cryptography ``` -------------------------------- ### Install Cassandra module dependencies Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/cassandra.md Run this command to install the necessary packages for using the Cassandra module. ```bash pip install testcontainers[cassandra] cassandra-driver ``` -------------------------------- ### Install Kafka Module Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/kafka.md Install the Kafka module for Testcontainers by running this command. ```bash pip install testcontainers[kafka] ``` -------------------------------- ### Install OpenSearch module dependencies Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/opensearch.md Run this command to install the necessary packages for using the OpenSearch module. ```bash pip install testcontainers[opensearch] opensearch-py ``` -------------------------------- ### Database Setup with `exec` Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/features/executing_commands.md Use `exec` to perform database setup tasks like creating databases or running SQL migrations within a PostgreSQL container. ```python from testcontainers.postgres import PostgresContainer with PostgresContainer() as postgres: # Create a database postgres.exec(["createdb", "testdb"]) # Run migrations postgres.exec(["psql", "-d", "testdb", "-f", "/path/to/migrations.sql"]) ``` -------------------------------- ### Multi-Container Application Setup Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/features/networking.md Use this snippet to create and manage multiple containers within a shared network. Ensure containers are started within a `with` statement for proper lifecycle management. Network aliases are crucial for inter-container communication. ```python from testcontainers.core.network import Network from testcontainers.postgres import PostgresContainer from testcontainers.redis import RedisContainer def test_multi_container_app(): # Create a network network = Network() network.create() # Create containers postgres = PostgresContainer() postgres.with_network(network) postgres.with_network_aliases(["db"]) redis = RedisContainer() redis.with_network(network) redis.with_network_aliases(["cache"]) # Start containers with postgres, redis: # Get connection details db_host = postgres.get_container_host_ip() db_port = postgres.get_exposed_port(5432) redis_host = redis.get_container_host_ip() redis_port = redis.get_exposed_port(6379) # Your test code here pass ``` -------------------------------- ### Basic Nginx Container Usage Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/nginx.md Example of creating and using a basic Nginx container with Testcontainers for Python. Ensure the Nginx module is installed. ```python from testcontainers.nginx import NginxContainer def test_nginx_basic(): with NginxContainer() as nginx: # You can now interact with the Nginx container # For example, check if it's running or access its exposed ports assert nginx.get_container_host_ip() is not None assert nginx.get_exposed_port(80) is not None ``` -------------------------------- ### Install Poetry and Add Testcontainers Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/system_requirements/index.md Install Poetry using a script, initialize a project, and add testcontainers as a development dependency. Poetry manages dependencies and virtual environments with TOML-based configuration. ```bash curl -sSL https://install.python-poetry.org | python3 - poetry init poetry add --dev testcontainers poetry shell ``` -------------------------------- ### Basic Weaviate Container Usage Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/weaviate.md Example demonstrating how to create and use a Weaviate container with Testcontainers. This snippet shows the basic setup for running Weaviate in a test environment. ```python from testcontainers.weaviate import WeaviateContainer with WeaviateContainer() as weaviate: # Use the weaviate container, e.g. get connection details connection_details = weaviate.get_connection_details() print(f"Weaviate host: {connection_details.host}") print(f"Weaviate port: {connection_details.port}") ``` -------------------------------- ### Install MinIO module dependencies Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/minio.md Run this command to install the necessary packages for using the MinIO module. ```bash pip install testcontainers[minio] minio requests ``` -------------------------------- ### Basic Milvus Container Usage Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/milvus.md Example demonstrating how to create and use a Milvus container with Testcontainers Python. Ensure the Milvus module is installed. ```python from testcontainers.milvus import MilvusContainer with MilvusContainer() .with_http_client() .start() as milvus: print(milvus.get_connection_config()) ``` -------------------------------- ### Basic Vault Container Usage Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/vault.md Example demonstrating how to create and use a Vault container. This snippet shows the fundamental setup for integrating Vault with Testcontainers. ```python from testcontainers.vault import VaultContainer with VaultContainer() as vault: # Use the vault container here # For example, get the Vault URL: print(vault.get_connection_url()) # Get the root token: print(vault.get_root_token()) # Get the Vault client: client = vault.get_client() print(client.is_sealed()) ``` -------------------------------- ### Install Valkey Module Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/valkey.md Run this command to add the Valkey module to your project dependencies. ```bash pip install testcontainers[valkey] ``` -------------------------------- ### Create and Activate virtualenv Environment Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/system_requirements/index.md Install and use the virtualenv package to create a stand-alone virtual environment. Activate the environment and install project dependencies. ```bash pip install virtualenv virtualenv .env source .env/bin/activate pip install -r requirements.txt ``` -------------------------------- ### Install Generic Module Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/generic.md Command to install the generic module dependencies via pip. ```bash pip install testcontainers[generic] ``` -------------------------------- ### Basic Ollama Container Usage Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/ollama.md Example of creating and using an Ollama container. This snippet demonstrates the basic setup for integrating Ollama with Testcontainers in Python. ```python from testcontainers.ollama import OllamaContainer with OllamaContainer() as ollama: print(ollama.get_image_names()) ``` -------------------------------- ### Install Trino Module Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/trino.md Install the Trino module for testcontainers-python and the Trino client library. ```bash pip install testcontainers[trino] trino ``` -------------------------------- ### Install MQTT module dependencies Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/mqtt.md Run this command to install the necessary packages for MQTT support in your Python project. ```bash pip install testcontainers[mqtt] paho-mqtt ``` -------------------------------- ### Docker Compose Example Source: https://github.com/testcontainers/testcontainers-python/blob/main/core/README.md This YAML snippet defines a simple Docker Compose service named 'hello-world' using the 'hello-world' image. It's a basic example for demonstrating Docker Compose integration. ```yaml services: hello-world: image: "hello-world" ``` -------------------------------- ### Example .testcontainers.properties File Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/features/configuration.md This snippet shows an example of a .testcontainers.properties file, demonstrating how to configure Docker host, TLS, Ryuk, and Testcontainers connection modes. ```properties # Docker host configuration docker.host=tcp://my.docker.host:1234 docker.tls.verify=1 docker.cert.path=/path/to/certs # Ryuk configuration ryuk.disabled=false ryuk.container.privileged=true ryuk.reconnection.timeout=30s ryuk.image=testcontainers/ryuk:0.8.1 # Testcontainers configuration tc.host=tcp://my.testcontainers.host:1234 connection.mode=bridge_ip ``` -------------------------------- ### Install PostgreSQL Module Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/postgres.md Install the PostgreSQL module along with SQLAlchemy and psycopg2 for database interaction. ```bash pip install testcontainers[postgres] sqlalchemy psycopg2 ``` -------------------------------- ### Install MSSQL module dependencies Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/mssql.md Run this command to install the necessary packages for using the MSSQL module. ```bash pip install testcontainers[mssql] pymssql ``` -------------------------------- ### Install Google Cloud Testcontainers dependencies Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/google.md Run this command to install the necessary packages for Google Cloud integration. ```bash pip install testcontainers[google] google-cloud-datastore google-cloud-pubsub ``` -------------------------------- ### Configuration Properties Example Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/features/advanced_features.md Illustrates configuration properties that can be used for Testcontainers settings, such as Ryuk container behavior and Docker client strategy. ```properties # .testcontainers.properties # ryuk.container.privileged=true # ryuk.reconnection.timeout=10s # docker.client.strategy=org.testcontainers.dockerclient.UnixSocketClientProviderStrategy ``` -------------------------------- ### Initialize DockerCompose environment Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/features/docker_compose.md Use the DockerCompose class to define and start a container environment from a directory. ```python from testcontainers.compose import DockerCompose # Create a compose environment compose = DockerCompose( context="path/to/compose/directory", compose_file_name="docker-compose.yml" ) # Start the environment with compose: # Your test code here pass ``` -------------------------------- ### Install MongoDB module dependencies Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/mongodb.md Run this command to install the necessary MongoDB module and pymongo driver. ```bash pip install testcontainers[mongodb] pymongo ``` -------------------------------- ### Install Memcached module dependencies Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/memcached.md Run this command to install the necessary packages for using the Memcached module. ```bash pip install testcontainers[memcached] pymemcache ``` -------------------------------- ### Install Chroma module dependencies Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/chroma.md Command to install the necessary packages for using the Chroma module. ```bash pip install testcontainers[chroma] chromadb requests ``` -------------------------------- ### Install MySQL module dependencies Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/mysql.md Run this command to install the necessary packages for MySQL support in testcontainers-python. ```bash pip install testcontainers[mysql] sqlalchemy pymysql ``` -------------------------------- ### Basic CosmosDB Container Usage Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/cosmosdb.md Example demonstrating how to create and use a CosmosDB container with Testcontainers. ```python from testcontainers.cosmosdb import CosmosDbContainer with CosmosDbContainer() as cosmosdb: # Use the cosmosdb container here # For example, get the connection string: connection_string = cosmosdb.get_connection_string() print(f"CosmosDB connection string: {connection_string}") ``` -------------------------------- ### Install LocalStack module dependencies Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/localstack.md Use pip to install the necessary testcontainers-localstack and boto3 packages. ```bash pip install testcontainers[localstack] boto3 ``` -------------------------------- ### Install and Use Pipenv Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/system_requirements/index.md Install pipenv, add testcontainers as a development dependency, and activate the project's shell. Pipenv manages dependencies and virtual environments automatically. ```bash pip install pipenv pipenv install --dev testcontainers pipenv shell ``` -------------------------------- ### Install NATS module dependencies Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/nats.md Run this command to install the necessary packages for using the NATS module. ```bash pip install testcontainers[nats] nats-py ``` -------------------------------- ### Install Neo4j module dependencies Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/neo4j.md Command to install the necessary Python packages for using the Neo4j module. ```bash pip install testcontainers[neo4j] neo4j ``` -------------------------------- ### Basic ClickHouse Container Usage Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/clickhouse.md Example of creating and using a ClickHouse container. Ensure you have the necessary imports. ```python from testcontainers.clickhouse import ClickHouseContainer with ClickHouseContainer() .with_driver_class("clickhouse.Client") .with_command("--queries-before-checking=1") .with_user("test") .with_password("test") .with_database("test") .with_port(9000) .start() as container: client = clickhouse_driver.Client( host=container.get_host(), port=container.get_internal_port(9000), user="test", password="test", database="test", ) client.execute("SELECT 1") print("ClickHouse container is running and accessible.") ``` -------------------------------- ### Start Podman Socket and Set DOCKER_HOST (Linux Rootless) Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/system_requirements/docker.md Configure Testcontainers to use Podman on Linux in rootless mode by starting the user's Podman socket and setting the DOCKER_HOST environment variable. ```bash systemctl --user start podman.socket export DOCKER_HOST="unix://${XDG_RUNTIME_DIR}/podman/podman.sock" ``` -------------------------------- ### Install Redis module dependencies Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/redis.md Command to install the necessary testcontainers Redis module and the redis client library. ```bash pip install testcontainers[redis] redis ``` -------------------------------- ### Build test images Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/features/building_images.md Example of building a test-specific image with build arguments for use in a test container. ```python def test_custom_image(): # Build test image image = build_image( path="path/to/dockerfile/directory", buildargs={"TEST_MODE": "true"}, tag="myapp:test" ) # Use the test image with GenericContainer(image) as container: # Your test code here pass ``` -------------------------------- ### Install Testcontainers CosmosDB Module Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/cosmosdb.md Install the CosmosDB module along with necessary Python dependencies using pip. ```bash pip install testcontainers[cosmosdb] pymongo azure-cosmos ``` -------------------------------- ### Setting Up Database Files in Container Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/features/copying_data.md Illustrates copying SQL initialization scripts and test data into a PostgreSQL container's entrypoint directory. This ensures the database is set up correctly on startup. ```python def test_database(): with GenericContainer("postgres:latest") as container: # Copy database initialization script container.copy_file_to_container( local_path="tests/db/init.sql", container_path="/docker-entrypoint-initdb.d/init.sql" ) # Copy test data container.copy_file_to_container( local_path="tests/db/test_data.sql", container_path="/docker-entrypoint-initdb.d/test_data.sql" ) ``` -------------------------------- ### Install RabbitMQ Module Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/rabbitmq.md Install the RabbitMQ module and the pika library using pip. This is required to use the RabbitMQ container. ```bash pip install testcontainers[rabbitmq] pika ``` -------------------------------- ### Implement multi-service integration test Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/features/docker_compose.md Example demonstrating service interaction and command execution within a test function. ```python from testcontainers.compose import DockerCompose import requests def test_web_application(): compose = DockerCompose( "path/to/compose/directory", compose_file_name="docker-compose.yml", pull=True, build=True ) with compose: # Get web service details host = compose.get_service_host("web") port = compose.get_service_port("web", 8080) # Make a request to the web service response = requests.get(f"http://{host}:{port}/api/health") assert response.status_code == 200 # Execute a command in the database service stdout, stderr, exit_code = compose.exec_in_container( ["psql", "-U", "postgres", "-c", "SELECT 1"], service_name="db" ) assert exit_code == 0 ``` -------------------------------- ### Install Keycloak module dependencies Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/keycloak.md Install the required packages using pip to enable Keycloak container support. ```bash pip install testcontainers[keycloak] python-keycloak requests ``` -------------------------------- ### Start Podman Socket and Set DOCKER_HOST (Linux Rootful) Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/system_requirements/docker.md Configure Testcontainers to use Podman on Linux in rootful mode by starting the system's Podman socket and setting the DOCKER_HOST environment variable. ```bash sudo systemctl start podman.socket export DOCKER_HOST="unix:///run/podman/podman.sock" ``` -------------------------------- ### Spin up ClickHouse and connect with clickhouse-driver Source: https://github.com/testcontainers/testcontainers-python/blob/main/modules/clickhouse/README.md Use this snippet to initialize a ClickHouse container and establish a connection using the 'clickhouse-driver' library. Ensure 'clickhouse-driver' is installed. ```python from testcontainers.clickhouse import ClickHouseContainer with ClickHouseContainer() .with_driver_mode('native') as clickhouse: client = clickhouse_driver.Client(host=clickhouse.get_host(), port=clickhouse.get_port(), secure=True) client.ping() print("Connection successful") ``` -------------------------------- ### Install Azurite Module Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/azurite.md Install the Azurite module and Azure Blob Storage client library using pip. This command ensures you have the necessary dependencies for using Azurite with Testcontainers. ```bash pip install testcontainers[azurite] azure-storage-blob ``` -------------------------------- ### Install Testcontainers for Python Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/quickstart.md Install the testcontainers-python library using pip. This is the first step to using Testcontainers in your Python projects. ```bash pip install testcontainers ``` -------------------------------- ### Configure DockerCompose options Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/features/docker_compose.md Customize environment startup with parameters for multiple files, image building, and service filtering. ```python compose = DockerCompose( context="path/to/compose/directory", compose_file_name=["docker-compose.yml", "docker-compose.override.yml"], # Multiple compose files pull=True, # Pull images before starting build=True, # Build images before starting wait=True, # Wait for services to be healthy env_file=".env", # Environment file services=["service1", "service2"], # Specific services to run profiles=["profile1", "profile2"], # Compose profiles to use keep_volumes=False # Whether to keep volumes after stopping ) ``` -------------------------------- ### Setting Up Application Files in Container Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/features/copying_data.md Shows how to copy entire directories for static assets and templates into an application container. This is useful for deploying application components. ```python def test_application(): with GenericContainer("myapp:latest") as container: # Copy application files container.copy_directory_to_container( local_path="app/static", container_path="/app/static" ) # Copy templates container.copy_directory_to_container( local_path="app/templates", container_path="/app/templates" ) ``` -------------------------------- ### Built-in Connection Waiting for Redis Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/features/wait_strategies.md RedisContainer automatically waits for a connection to be established upon starting, simplifying setup for Redis instances. ```python from testcontainers.redis import RedisContainer redis = RedisContainer() redis.start() # Will wait until Redis is ready to accept connections ``` -------------------------------- ### Create a Trino Container Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/trino.md Example of creating and using a Trino container with Testcontainers for Python. ```python from testcontainers.trino import TrinoContainer def test_trino_basic(): with TrinoContainer("trino:432") as trino: assert trino.get_container_host_ip() is not None ``` -------------------------------- ### Run OllamaContainer and interact with models Source: https://github.com/testcontainers/testcontainers-python/blob/main/modules/ollama/README.md Demonstrates initializing the container with a local home directory, checking for models, and streaming a chat response. ```python >>> from json import loads >>> from pathlib import Path >>> from requests import post >>> from testcontainers.ollama import OllamaContainer >>> def split_by_line(generator): ... data = b'' ... for each_item in generator: ... for line in each_item.splitlines(True): ... data += line ... if data.endswith((b'\r\r', b'\n\n', b'\r\n\r\n', b'\n')): ... yield from data.splitlines() ... data = b'' ... if data: ... yield from data.splitlines() >>> with OllamaContainer(ollama_home=Path.home() / ".ollama") as ollama: ... if "llama3:latest" not in [e["name"] for e in ollama.list_models()]: ... print("did not find 'llama3:latest', pulling") ... ollama.pull_model("llama3:latest") ... endpoint = ollama.get_endpoint() ... for chunk in split_by_line( ... post(url=f"{endpoint}/api/chat", stream=True, json={ ... "model": "llama3:latest", ... "messages": [{ ... "role": "user", ... "content": "what color is the sky? MAX ONE WORD" ... }] ... }) ... ): ... print(loads(chunk)["message"]["content"], end="") ``` -------------------------------- ### Basic ArangoDB Container Usage Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/arangodb.md Example demonstrating how to create and use a basic ArangoDB container. This snippet is intended for integration testing scenarios. ```python from testcontainers.arangodb import ArangoDBContainer with ArangoDBContainer() as arango: print(arango.get_connection_url()) ``` -------------------------------- ### MySqlContainer Initialization and Usage Source: https://github.com/testcontainers/testcontainers-python/blob/main/modules/mysql/README.md Demonstrates how to initialize a MySQL container with various options and retrieve its connection URL. ```APIDOC ## MySqlContainer ### Description MySql database container. ### Method Instantiation ### Endpoint N/A (Class instantiation) ### Parameters - **image** (str) - Default: 'mysql:latest' - The Docker image to use for the MySQL container. - **dialect** (str | None) - None - The SQLAlchemy dialect to use. - **username** (str | None) - None - The username for connecting to the database. - **root_password** (str | None) - None - The root password for the MySQL server. - **password** (str | None) - None - The password for connecting to the database. - **dbname** (str | None) - None - The name of the database to create. - **port** (int) - Default: 3306 - The port on which MySQL will be exposed. - **seed** (str | None) - None - Path to SQL files to be loaded on initialization. - **wait_strategy_check_string** (str) - Default: '.": ready for connections.": ready for connections.' - String to check for readiness. ### Request Example ```python from testcontainers.mysql import MySqlContainer mysql_container = MySqlContainer( "mysql:8.0", root_password="my-secret-pw", dbname="my-db" ) mysql_container.start() # Get SQLAlchemy connection URL connection_url = mysql_container.get_connection_url() print(connection_url) # Stop the container mysql_container.stop() ``` ### Response #### Success Response (Instantiation) - **MySqlContainer instance**: An initialized MySQL container object. #### Response Example (Connection URL) ``` mysql+pymysql://root:my-secret-pw@localhost:3306/my-db ``` ### Notes The `seed` parameter allows loading arbitrary SQL files by mounting them to `/docker-entrypoint-initdb.d/`, which containerized MySQL automatically loads during startup. ``` -------------------------------- ### Initialize Postgres Container with SQLAlchemy Source: https://github.com/testcontainers/testcontainers-python/blob/main/README.md Demonstrates spinning up a PostgreSQL container and connecting to it using SQLAlchemy. ```pycon >>> from testcontainers.postgres import PostgresContainer >>> import sqlalchemy >>> with PostgresContainer("postgres:16") as postgres: ... engine = sqlalchemy.create_engine(postgres.get_connection_url()) ... with engine.begin() as connection: ... result = connection.execute(sqlalchemy.text("select version()")) ... version, = result.fetchone() >>> version 'PostgreSQL 16...' ``` -------------------------------- ### Install ArangoDB Module Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/arangodb.md Install the ArangoDB module along with its dependencies. Ensure python-arango is also installed for database interaction. ```bash pip install testcontainers[arangodb] python-arango ``` -------------------------------- ### Dependencies and Environment Variables Example Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/test_module_import.md Shows how to handle module dependencies and environment requirements. This includes importing modules with external dependencies, managing required dependency versions, setting up and accessing environment variables, and handling environment-specific configurations. ```python from testcontainers.modules.test_module_import import TestModuleImportContainer with TestModuleImportContainer() as container: # Example: Install a package with a specific dependency version container.install("my_package==1.0.0") # Assuming my_package requires a specific version of another lib container.run_python_code("import my_package; print('my_package imported successfully')") # Example: Setting environment variables container.with_env("MY_API_KEY", "test_key_123") container.with_env("ANOTHER_VAR", "some_value") # Example: Accessing environment variables within the container api_key = container.run_python_code("import os; print(os.environ.get('MY_API_KEY'))") print(f"API Key from env: {api_key}") another_var = container.run_python_code("import os; print(os.environ.get('ANOTHER_VAR'))") print(f"Another Var from env: {another_var}") # Example: Handling environment-specific configurations (conceptual) # This often involves checking env vars to load different settings container.run_python_code("import os; config_type = 'prod' if os.environ.get('PROD_ENV') else 'dev'; print(f'Loading {config_type} configuration')") ``` -------------------------------- ### Install InfluxDB dependencies Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/influxdb.md Install the required packages for InfluxDB 1.x or 2.x support. ```bash # For InfluxDB 1.x pip install testcontainers[influxdb] influxdb # For InfluxDB 2.x pip install testcontainers[influxdb] influxdb-client ``` -------------------------------- ### Install Mailpit dependencies Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/mailpit.md Install the required Mailpit module and cryptography library via pip. ```bash pip install testcontainers[mailpit] cryptography ``` -------------------------------- ### Install Testcontainers ClickHouse Module Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/clickhouse.md Install the ClickHouse module for Testcontainers and the clickhouse-driver using pip. ```bash pip install testcontainers[clickhouse] clickhouse-driver ``` -------------------------------- ### Setting Up Test Data with Copied Files Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/features/copying_data.md Demonstrates copying JSON and YAML files into a container for test data and configuration. Ensure paths are correct for your test setup. ```python def test_with_data(): with GenericContainer("alpine:latest") as container: # Copy test data container.copy_file_to_container( local_path="tests/data/test_data.json", container_path="/app/data/test_data.json" ) # Copy configuration container.copy_file_to_container( local_path="tests/config/test_config.yaml", container_path="/app/config/config.yaml" ) ``` -------------------------------- ### Build a basic Docker image Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/features/building_images.md Use build_image to create an image from a specified directory path and tag it for use in a GenericContainer. ```python from testcontainers.core.container import build_image # Build an image from a Dockerfile image = build_image( path="path/to/dockerfile/directory", tag="myapp:test" ) # Use the built image with GenericContainer(image) as container: # Your test code here pass ``` -------------------------------- ### Install DB2 module dependencies Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/db2.md Command to install the necessary packages for using the DB2 module with SQLAlchemy. ```bash pip install testcontainers[db2] sqlalchemy ibm-db ``` -------------------------------- ### Spin up Azurite Container and Create Blob Service Client Source: https://github.com/testcontainers/testcontainers-python/blob/main/modules/azurite/README.md This example demonstrates how to instantiate an Azurite container and then use its connection string to create an Azure Blob service client. The `get_connection_string` method is versatile and can be used for Blob, Queue, and Table services. ```python from testcontainers.azure.azurite import AzuriteContainer with AzuriteContainer() as azurite: blob_service_client = azurite.get_blob_service_client() print(blob_service_client.list_containers()) ``` -------------------------------- ### Install Testcontainers K3s Module Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/k3s.md Install the K3s module along with Kubernetes and PyYAML dependencies using pip. ```bash pip install testcontainers[k3s] kubernetes pyyaml ``` -------------------------------- ### Version-Specific Imports Example Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/test_module_import.md Demonstrates handling version-specific module imports. This includes importing specific versions of modules, managing version compatibility, accessing and verifying version information, and working with version-specific features. ```python from testcontainers.modules.test_module_import import TestModuleImportContainer with TestModuleImportContainer() as container: # Example: Install and import a specific version of a package container.install("requests==2.25.0") version = container.run_python_code("import requests; print(requests.__version__)") print(f"Requests version: {version}") # Example: Install a different version and verify container.install("requests==2.28.0") version = container.run_python_code("import requests; print(requests.__version__)") print(f"Requests version after update: {version}") # Example: Handling version conflicts (if applicable, though install command manages this) # This example assumes a scenario where you might check compatibility manually container.run_python_code("import sys; print(f'Python version: {sys.version_info.major}.{sys.version_info.minor}')") # Example: Using features specific to a version (conceptual) # This would depend on the package itself. For instance, if a feature was added in 2.26.0: # container.run_python_code("import requests; # Use feature available from v2.26.0") ``` -------------------------------- ### Advanced Container Configuration with run Helper Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/features/creating_container.md The `run` helper function provides a high-level interface similar to `docker run` for complex configurations. It automatically manages temporary networks, file mounts, waiting for readiness, and cleanup. ```python import io import pytest from testcontainers.core.container import run from testcontainers.core.network import DockerNetwork from testcontainers.core.waiting_utils import wait_for_logs def test_nginx_advanced(): # Create an isolated network network = DockerNetwork() network.create() pytest.addfinalizer(network.remove) # Create a test file to mount test_file_content = b"Hello from test file!" host_file = io.BytesIO(test_file_content) # Run the container with various options container = run( image="nginx:alpine", network=network.name, files=[(host_file, "/usr/share/nginx/html/test.txt")], tmpfs={"/tmp": "rw"}, labels={"testcontainers.label": "true"}, environment={"TEST": "true"}, ports={"80/tcp": None}, command=["nginx", "-g", "daemon off;"], wait=wait_for_logs("Configuration complete; ready for start"), startup_timeout=30, ) # Ensure cleanup pytest.addfinalizer(container.stop) pytest.addfinalizer(container.remove) # Test the container host = container.get_container_host_ip() port = container.get_exposed_port(80) # Verify the mounted file import requests response = requests.get(f"http://{host}:{port}/test.txt") assert response.text == "Hello from test file!" ``` -------------------------------- ### Build Custom Optimized Docker Images Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/features/advanced_features.md Create custom Docker images using multi-stage builds for optimized application deployment. This example demonstrates building an image with a Python application, leveraging a slim base image and copying only necessary artifacts. ```python from testcontainers.core.container import DockerContainer from testcontainers.core.docker_client import DockerClient client = DockerClient() client.build_image( path=".", tag="my-optimized-app:latest", dockerfile=""" FROM python:3.9-slim as builder WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt FROM python:3.9-slim WORKDIR /app COPY --from=builder /usr/local/lib/python3.9/site-packages /usr/local/lib/python3.9/site-packages COPY . . """ ) ``` -------------------------------- ### Install CockroachDB module dependencies Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/cockroachdb.md Command to install the necessary packages for using the CockroachDB module with SQLAlchemy and psycopg2. ```bash pip install testcontainers[cockroachdb] sqlalchemy psycopg2 ``` -------------------------------- ### Install Testcontainers Selenium Module Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/selenium.md Install the Selenium module for Testcontainers along with Selenium and urllib3 dependencies using pip. ```bash pip install testcontainers[selenium] selenium urllib3 ``` -------------------------------- ### QdrantContainer Class Initialization Source: https://github.com/testcontainers/testcontainers-python/blob/main/modules/qdrant/README.md Initializes a new Qdrant vector database container instance with configurable ports and authentication settings. ```APIDOC ## QdrantContainer Initialization ### Description Initializes a Qdrant vector database container for testing purposes. ### Parameters - **image** (str) - Optional - The Docker image to use (default: 'qdrant/qdrant:v1.16.2') - **rest_port** (int) - Optional - The REST API port (default: 6333) - **grpc_port** (int) - Optional - The gRPC port (default: 6334) - **api_key** (str | None) - Optional - API key for authentication - **config_file_path** (Path | None) - Optional - Path to a custom configuration file - **kwargs** - Optional - Additional keyword arguments for the container ``` -------------------------------- ### Install Nginx Module Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/nginx.md Install the Nginx module for testcontainers-python using pip. This command adds the necessary dependencies to your project. ```bash pip install testcontainers[nginx] ``` -------------------------------- ### Install Ollama Module Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/ollama.md Install the Ollama module for Testcontainers and the requests library using pip. This command adds the necessary dependencies to your project. ```bash pip install testcontainers[ollama] requests ``` -------------------------------- ### Handle Container Startup Failures Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/features/advanced_features.md Gracefully handle potential exceptions during container startup and log relevant information, including container logs, for debugging purposes. ```python try: container = DockerContainer("nginx:alpine") container.start() except Exception as e: print(f"Container startup failed: {e}") print(f"Container logs: {container.get_logs()}") raise ``` -------------------------------- ### Install Milvus Module Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/milvus.md Install the Milvus module for Testcontainers Python along with the requests library. This command adds the necessary dependencies to your project. ```bash pip install testcontainers[milvus] requests ``` -------------------------------- ### Install Testcontainers AWS Module Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/aws.md Install the AWS module for Testcontainers Python along with httpx. This command adds the necessary dependencies to your project. ```bash pip install testcontainers[aws] httpx ``` -------------------------------- ### Start Interactive Shell in Container Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/features/executing_commands.md Use `exec_interactive` to start an interactive shell session within the container. This is useful for debugging or manual interaction. ```python with GenericContainer("alpine:latest") as container: # Start an interactive shell container.exec_interactive(["sh"]) ``` -------------------------------- ### Module Reloading Example Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/test_module_import.md Shows how to work with module reloading functionality. This includes importing a module, accessing its initial state, reloading it to pick up changes, handling reloading errors gracefully, and managing module state during reloads. ```python import shutil import tempfile from pathlib import Path from testcontainers.modules.test_module_import import TestModuleImportContainer # Create a temporary directory for the module with tempfile.TemporaryDirectory() as tmpdir: tmpdir_path = Path(tmpdir) module_path = tmpdir_path / "my_module.py" module_path.write_text("version = 1\n") # Create a virtual environment and install the module with TestModuleImportContainer(source_folder=tmpdir_path) as container: # Initial import and check version initial_version = container.run_python_code("import my_module; print(my_module.version)") print(f"Initial version: {initial_version}") # Modify the module file module_path.write_text("version = 2\n") # Reload the module and check the new version container.run_python_code("import importlib; importlib.reload(my_module); print(my_module.version)") print(f"Updated version: {container.run_python_code('import my_module; print(my_module.version)')}") # Example of handling reloading errors (e.g., syntax error) module_path.write_text("version = invalid syntax\n") try: container.run_python_code("import importlib; importlib.reload(my_module)") except Exception as e: print(f"Caught expected error during reload: {e}") # Reset to a valid state module_path.write_text("version = 3\n") container.run_python_code("import importlib; importlib.reload(my_module); print(my_module.version)") print(f"Reset version: {container.run_python_code('import my_module; print(my_module.version)')}") ``` -------------------------------- ### Install Testcontainers Vault Module Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/vault.md Install the Vault module along with the necessary hvac library. This command adds the Vault module to your project dependencies. ```bash pip install testcontainers[vault] hvac ``` -------------------------------- ### Configure ARM64 Emulation and Resource Limits Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/features/advanced_features.md Enable automatic AMD64 emulation for ARM64 hosts and apply resource constraints to containers. ```python from testcontainers.core.container import DockerContainer # Basic usage with automatic emulation container = DockerContainer("nginx:alpine") container.maybe_emulate_amd64() # Automatically handles ARM64 emulation # Advanced configuration with resource limits container = DockerContainer("nginx:alpine") container.maybe_emulate_amd64() container.with_memory_limit("512m") container.with_cpu_limit(0.5) # Use 50% of available CPU ``` -------------------------------- ### Install Testcontainers with Mamba Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/system_requirements/index.md Use Mamba, a faster alternative to conda, to install pip and then testcontainers from the conda-forge channel. This is an efficient way to manage environments and packages. ```bash mamba install pip mamba install -c conda-forge testcontainers ``` -------------------------------- ### Install Scylla Testcontainers Module Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/scylla.md Add the Scylla module to your Python project dependencies using pip. This command installs the necessary package for Scylla integration. ```bash pip install testcontainers[scylla] ``` -------------------------------- ### Install Testcontainers Registry Module Source: https://github.com/testcontainers/testcontainers-python/blob/main/docs/modules/registry.md Add the Registry module to your project dependencies using pip. This command installs the necessary package to use the Registry container. ```bash pip install testcontainers[registry] ``` -------------------------------- ### ChromaContainer Initialization Source: https://github.com/testcontainers/testcontainers-python/blob/main/modules/chroma/README.md Details on how to initialize the ChromaContainer class and retrieve a client. ```APIDOC ## ChromaContainer ### Description Initializes a ChromaDB container instance. The container can be configured with a specific image and port. ### Parameters - **image** (str) - Optional - The Docker image to use (default: 'chromadb/chroma:1.0.0') - **port** (int) - Optional - The port to expose (default: 8000) - **kwargs** - Optional - Additional keyword arguments for container configuration ### Methods - **get_client()**: Returns a client for the Chroma Python Client to interact with the container. ```