### Start and Connect to PostgreSQL Container with Psycopg (Python) Source: https://testcontainers-python.readthedocs.io/en/latest/index Launches a PostgreSQL container and retrieves its connection URL, demonstrating connection using the 'psycopg' library. This example specifically sets the driver to None in `get_connection_url()` for compatibility with psycopg v3. Similar to the SQLAlchemy example, 'psycopg' is not a direct dependency of testcontainers[postgres]. ```python >>> from testcontainers.postgres import PostgresContainer >>> import psycopg >>> with PostgresContainer("postgres:16", driver=None) as postgres: ... psql_url = postgres.get_connection_url() ... with psycopg.connect(psql_url) as connection: ... with connection.cursor() as cursor: ... version, = cursor.execute("SELECT version()").fetchone() >>> version 'PostgreSQL 16...' ``` -------------------------------- ### Spin up ChromaDB Container and Create Collection (Python) Source: https://testcontainers-python.readthedocs.io/en/latest/modules/chroma/README This snippet shows how to instantiate a ChromaDB container, retrieve its configuration, and use it to create a client for the Chroma Python Client. It then demonstrates creating or getting a collection and verifying its name. This requires the 'chromadb' and 'testcontainers' libraries. ```python import chromadb from testcontainers.chroma import ChromaContainer with ChromaContainer() as chroma: config = chroma.get_config() client = chromadb.HttpClient(host=config["host"], port=config["port"]) col = client.get_or_create_collection("test") print(col.name) ``` -------------------------------- ### SFTPContainer Basic Authentication Example Source: https://testcontainers-python.readthedocs.io/en/latest/modules/sftp/README Demonstrates how to use SFTPContainer with basic username and password authentication. It sets up an SFTP server, connects to it using Paramiko with provided credentials, and shows where to uncomment operations like getting, listing, changing directories, and putting files. ```python >>> import paramiko >>> from testcontainers.sftp import SFTPContainer >>> with SFTPContainer() as sftp_container: ... host_ip = sftp_container.get_container_host_ip() ... host_port = sftp_container.get_exposed_sftp_port() ... ssh = paramiko.SSHClient() ... ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ... ssh.connect(host_ip, host_port, "basic", "password") ... # ssh.get(...) ... # ssh.listdir() ... # ssh.chdir("upload") ... # ssh.put(...) ``` -------------------------------- ### Start PostgreSQL Container with Psycopg Source: https://testcontainers-python.readthedocs.io/en/latest/_sources/index.rst This snippet shows how to start a PostgreSQL container and connect using the psycopg library. It demonstrates configuring the container to not include a driver in the connection URL for compatibility with psycopg v3. Dependencies include testcontainers and psycopg. ```python from testcontainers.postgres import PostgresContainer import psycopg with PostgresContainer("postgres:16", driver=None) as postgres: psql_url = postgres.get_connection_url() with psycopg.connect(psql_url) as connection: with connection.cursor() as cursor: version, = cursor.execute("SELECT version()").fetchone() version ``` -------------------------------- ### Start Pub/Sub Emulator with PubSubContainer in Python Source: https://testcontainers-python.readthedocs.io/en/latest/modules/google/README This snippet shows how to initialize and use the PubSubContainer to spin up a Google Cloud Pub/Sub emulator. The container provides methods to get publisher and subscriber clients for interacting with the emulator, simplifying the process of creating topics. ```python from testcontainers.google import PubSubContainer config = PubSubContainer() with config as pubsub: publisher = pubsub.get_publisher_client() topic_path = publisher.topic_path(pubsub.project, "my-topic") topic = publisher.create_topic(name=topic_path) ``` -------------------------------- ### SFTPContainer Setup and Usage Source: https://testcontainers-python.readthedocs.io/en/latest/modules/sftp/README Demonstrates how to initialize and use the SFTPContainer with both basic and keypair authentication methods, including connecting via paramiko. ```APIDOC ## SFTPContainer Class ### Description Test container for an SFTP server. It can be configured with multiple users, each having different authentication methods (password or keypair) and permissions. ### Default Configuration By default, it creates two users: `basic:password` and `keypair` (with no password, using a generated private key). ### User Permissions Users can only download from their root user folder, but can upload & download from any subfolder (e.g., `upload/` by default). ### Parameters - `image` (str): The Docker image to use for the SFTP server. Defaults to 'atmoz/sftp:alpine'. - `port` (int): The port to expose for the SFTP server. Defaults to 22. - `users` (list[SFTPUser] | None): A list of `SFTPUser` objects to configure the SFTP server with. If None, default users are created. - `**kwargs`: Additional keyword arguments to pass to the underlying container. ### Example Usage (Basic Authentication) ```python import paramiko from testcontainers.sftp import SFTPContainer with SFTPContainer() as sftp_container: host_ip = sftp_container.get_container_host_ip() host_port = sftp_container.get_exposed_sftp_port() ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(host_ip, host_port, "basic", "password") # You can now use ssh object to perform SFTP operations like: # ssh.get(...) # ssh.listdir() # ssh.chdir("upload") # ssh.put(...) ``` ### Example Usage (Keypair Authentication) ```python import paramiko from testcontainers.sftp import SFTPContainer with SFTPContainer() as sftp_container: host_ip = sftp_container.get_container_host_ip() host_port = sftp_container.get_exposed_sftp_port() ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) private_key_file = sftp_container.users[1].private_key_file ssh.connect(host_ip, host_port, "keypair", key_filename=private_key_file) # You can now use ssh object to perform SFTP operations like: # ssh.listdir() # ssh.get(...) # ssh.chdir("upload") # ssh.put(...) ``` ``` -------------------------------- ### Start Weaviate Container with Custom Environment Variables (Python) Source: https://testcontainers-python.readthedocs.io/en/latest/modules/weaviate/README This example illustrates how to configure a WeaviateContainer with specific environment variables. It shows setting modules, backup paths, and query defaults, then verifies the container's liveness. ```python from testcontainers.weaviate import WeaviateContainer with WeaviateContainer( env_vars={ "ENABLE_MODULES": "backup-filesystem,text2vec-openai", "BACKUP_FILESYSTEM_PATH": "/tmp/backups", "QUERY_DEFAULTS_LIMIT": 100, } ) as container: with container.get_client() as client: client.is_live() ``` -------------------------------- ### SFTPUser Class Example Source: https://testcontainers-python.readthedocs.io/en/latest/modules/sftp/README Shows how to create and configure SFTPUser objects, which are used by SFTPContainer. This example demonstrates creating users with passwords and keypairs, specifying custom folders, and accessing user properties like name, password, and keys. ```python >>> from testcontainers.sftp import SFTPUser >>> users = [ ... SFTPUser("jane", password="secret"), ... SFTPUser.with_keypair("ron", folders=["stuff"]), ... ] >>> for user in users: ... print(user.name, user.folders[0]) ... jane upload ron stuff >>> assert users[0].password == "secret" >>> assert users[1].public_key is not None >>> assert users[1].public_key.decode().startswith("ssh-rsa ") >>> assert users[1].private_key is not None >>> assert users[1].private_key.decode().startswith("-----BEGIN RSA PRIVATE KEY-----") ``` -------------------------------- ### OracleDbContainer Example with SQLAlchemy Source: https://testcontainers-python.readthedocs.io/en/latest/modules/oracle-free/README Demonstrates how to instantiate an OracleDbContainer, obtain its connection URL, and use SQLAlchemy to establish a connection and execute a query. ```python >>> import sys, pytest >>> if sys.platform.startswith('win') or sys.platform == 'darwin': ... pytest.skip("linux only test") >>> import sqlalchemy >>> from testcontainers.oracle import OracleDbContainer >>> with OracleDbContainer() as oracle: ... engine = sqlalchemy.create_engine(oracle.get_connection_url()) ... with engine.begin() as connection: ... result = connection.execute(sqlalchemy.text("SELECT 1 FROM dual")) ... result.fetchall() [(1,)] ``` -------------------------------- ### Spin up ClickHouse and connect with clickhouse-driver (Python) Source: https://testcontainers-python.readthedocs.io/en/latest/modules/clickhouse/README This example demonstrates how to instantiate a ClickHouse container and establish a connection to it using the `clickhouse-driver` library. It verifies the connection by executing a simple SQL query. ```python import clickhouse_driver from testcontainers.clickhouse import ClickHouseContainer with ClickHouseContainer("clickhouse/clickhouse-server:21.8") as clickhouse: client = clickhouse_driver.Client.from_url(clickhouse.get_connection_url()) client.execute("select 'working'") [('working',)] ``` -------------------------------- ### Instantiate and Use Redis Container (Python) Source: https://testcontainers-python.readthedocs.io/en/latest/modules/redis/README Demonstrates how to start a Redis container and obtain a Redis client instance. It requires the testcontainers-python library. The example shows a context manager usage for automatic container cleanup. ```python from testcontainers.redis import RedisContainer with RedisContainer() as redis_container: redis_client = redis_container.get_client() ``` -------------------------------- ### SFTPContainer Keypair Authentication Example Source: https://testcontainers-python.readthedocs.io/en/latest/modules/sftp/README Illustrates using SFTPContainer with keypair authentication. This example shows how to retrieve the private key file path for a user and connect to the SFTP server using Paramiko with the private key, enabling secure, passwordless authentication. ```python >>> import paramiko >>> from testcontainers.sftp import SFTPContainer >>> with SFTPContainer() as sftp_container: ... host_ip = sftp_container.get_container_host_ip() ... host_port = sftp_container.get_exposed_sftp_port() ... ssh = paramiko.SSHClient() ... ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ... private_key_file = sftp_container.users[1].private_key_file ... ssh.connect(host_ip, host_port, "keypair", key_filename=private_key_file) ... # ssh.listdir() ... # ssh.get(...) ... # ssh.chdir("upload") ... # ssh.put(...) ``` -------------------------------- ### Instantiate and Test NewSubModuleContainer Source: https://testcontainers-python.readthedocs.io/en/latest/modules/test_module_import/README Demonstrates how to instantiate and test the NewSubModuleContainer. It involves creating a DockerImage, then a NewSubModuleContainer with a specified port and image. It then creates a connection URL, makes an HTTP GET request to check for a 200 status code, and verifies an additional capability of the container. This example requires the httpx library. ```python import httpx from testcontainers.core.image import DockerImage from testcontainers.test_module_import import NewSubModuleContainer with DockerImage(path="./modules/generic/tests/samples/python_server", tag="test-new-mod:latest") as image: with NewSubModuleContainer(port=9000, image=image) as new_mod: url = new_mod._create_connection_url() response = httpx.get(f"{url}", timeout=5) assert response.status_code == 200, "Response status code is not 200" assert new_mod.additional_capability() == "NewSubModuleContainer" ``` -------------------------------- ### MilvusContainer Example - Python Source: https://testcontainers-python.readthedocs.io/en/latest/modules/milvus/README This snippet demonstrates how to instantiate and use the MilvusContainer to spin up a Milvus database. It shows how to access the exposed port and verify its presence in the connection URL. ```python from testcontainers.milvus import MilvusContainer with MilvusContainer("milvusdb/milvus:v2.4.4") as milvus_container: milvus_container.get_exposed_port(milvus_container.port) in milvus_container.get_connection_url() True ``` -------------------------------- ### Start CosmosDB NoSQL Emulator (Python) Source: https://testcontainers-python.readthedocs.io/en/latest/modules/cosmosdb/README This snippet demonstrates the initialization and basic usage of the CosmosDB NoSQL endpoint emulator. It allows for creating a database if it doesn't exist using an insecure synchronous client. ```python from testcontainers.cosmosdb import CosmosDBNoSQLEndpointContainer with CosmosDBNoSQLEndpointContainer() as emulator: db = emulator.insecure_sync_client().create_database_if_not_exists("test") ``` -------------------------------- ### Start PostgreSQL Container with SQLAlchemy Source: https://testcontainers-python.readthedocs.io/en/latest/_sources/index.rst This snippet demonstrates how to launch a PostgreSQL container using testcontainers-python and connect to it using SQLAlchemy. It retrieves the database version. Dependencies include testcontainers and sqlalchemy. ```python from testcontainers.postgres import PostgresContainer import sqlalchemy with PostgresContainer("postgres:16") as postgres: psql_url = postgres.get_connection_url() engine = sqlalchemy.create_engine(psql_url) with engine.begin() as connection: version, = connection.execute(sqlalchemy.text("SELECT version()")).fetchone() version ``` -------------------------------- ### Install Development Environment with Make Source: https://testcontainers-python.readthedocs.io/en/latest/index This command sets up the local development environment for Testcontainers Python using Make. It assumes Poetry is already installed. ```bash make install ``` -------------------------------- ### Create and Query OpenSearch Index with Python Source: https://testcontainers-python.readthedocs.io/en/latest/modules/opensearch/README This snippet shows how to initialize an OpenSearch container, obtain a client, create an index, add a document, refresh the index, and perform a search. It requires the testcontainers-opensearch library. The output includes the results of index creation, refresh, and search operations. ```python from testcontainers.opensearch import OpenSearchContainer with OpenSearchContainer() as opensearch: client = opensearch.get_client() creation_result = client.index(index="test", body={"test": "test"}) refresh_result = client.indices.refresh(index="test") search_result = client.search(index="test", body={"query": {"match_all": {}}}) ``` -------------------------------- ### Spin up ArangoDB Container and Connect Source: https://testcontainers-python.readthedocs.io/en/latest/modules/arangodb/README This example demonstrates how to instantiate an ArangoDB container, connect to it using ArangoClient, and create a new database. It utilizes the `get_connection_url()` method for client configuration. ```python from testcontainers.arangodb import ArangoDbContainer from arango import ArangoClient with ArangoDbContainer("arangodb:3.11.8") as arango: client = ArangoClient(hosts=arango.get_connection_url()) # Connect sys_db = client.db(username="root", password="passwd") # Create a new database named "test". sys_db.create_database("test") ``` -------------------------------- ### Instantiate and Use Cassandra Container Source: https://testcontainers-python.readthedocs.io/en/latest/modules/cassandra/README Demonstrates how to use the CassandraContainer to spin up a Cassandra instance and connect to it using the official Cassandra Python driver. This example shows querying the release version of the Cassandra instance. ```python from testcontainers.cassandra import CassandraContainer from cassandra.cluster import Cluster, DCAwareRoundRobinPolicy with CassandraContainer("cassandra:4.1.4") as cassandra, Cluster( cassandra.get_contact_points(), load_balancing_policy=DCAwareRoundRobinPolicy(cassandra.get_local_datacenter()), ) as cluster: session = cluster.connect() result = session.execute("SELECT release_version FROM system.local;") result.one().release_version ``` -------------------------------- ### Start Datastore Emulator with DatastoreContainer in Python Source: https://testcontainers-python.readthedocs.io/en/latest/modules/google/README This snippet demonstrates how to initialize and use the DatastoreContainer to spin up a Google Cloud Datastore emulator. The container provides a datastore client to connect to the emulator without manually setting environment variables. ```python from testcontainers.google import DatastoreContainer config = DatastoreContainer() with config as datastore: datastore_client = datastore.get_datastore_client() ``` -------------------------------- ### Run ScyllaDB Container with Python Source: https://testcontainers-python.readthedocs.io/en/latest/modules/scylla/README This snippet shows how to instantiate and use the ScyllaContainer from the testcontainers-python library. It connects to the Scylla cluster and creates a keyspace. Ensure testcontainers-python and its dependencies are installed. ```python from testcontainers.scylla import ScyllaContainer with ScyllaContainer() as scylla: cluster = scylla.get_cluster() with cluster.connect() as session: result = session.execute( "CREATE KEYSPACE keyspace1 WITH replication " "= {'class': 'SimpleStrategy', 'replication_factor': '1'};") ``` -------------------------------- ### Create and Connect to MySQL Container with SQLAlchemy Source: https://testcontainers-python.readthedocs.io/en/latest/modules/mysql/README This example demonstrates how to instantiate a MySQL container, create a SQLAlchemy engine using its connection URL, and execute a simple query to retrieve the database version. It utilizes the `MySqlContainer` class and `sqlalchemy` library. ```python import sqlalchemy from testcontainers.mysql import MySqlContainer with MySqlContainer("mysql:5.7.17", dialect="pymysql") as mysql: engine = sqlalchemy.create_engine(mysql.get_connection_url()) with engine.begin() as connection: result = connection.execute(sqlalchemy.text("select version()")) version, = result.fetchone() ``` -------------------------------- ### Start and Connect to PostgreSQL Container with SQLAlchemy (Python) Source: https://testcontainers-python.readthedocs.io/en/latest/index Spins up a PostgreSQL database container and provides a SQLAlchemy-compatible connection URL. It demonstrates connecting to the database and fetching its version using SQLAlchemy and the default psycopg2 driver. The SQLAlchemy and psycopg packages are not direct dependencies of testcontainers[postgres]. ```python >>> from testcontainers.postgres import PostgresContainer >>> import sqlalchemy >>> with PostgresContainer("postgres:16") as postgres: ... psql_url = postgres.get_connection_url() ... engine = sqlalchemy.create_engine(psql_url) ... with engine.begin() as connection: ... version, = connection.execute(sqlalchemy.text("SELECT version()")).fetchone() >>> version 'PostgreSQL 16...' ``` -------------------------------- ### OracleDbContainer Usage Source: https://testcontainers-python.readthedocs.io/en/latest/modules/oracle-free/README This example demonstrates how to use the OracleDbContainer to spin up an Oracle database and connect to it using SQLAlchemy. ```APIDOC ## OracleDbContainer ### Description Oracle database container. ### Method N/A (Class definition) ### Endpoint N/A (Class definition) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```python >>> import sys, pytest >>> if sys.platform.startswith('win') or sys.platform == 'darwin': ... pytest.skip("linux only test") >>> import sqlalchemy >>> from testcontainers.oracle import OracleDbContainer >>> with OracleDbContainer() as oracle: ... engine = sqlalchemy.create_engine(oracle.get_connection_url()) ... with engine.begin() as connection: ... result = connection.execute(sqlalchemy.text("SELECT 1 FROM dual")) ... result.fetchall() [(1,)] ``` ### Response #### Success Response (200) N/A (Example shows successful connection and query execution) #### Response Example ```json { "result": "[(1,)]" } ``` ``` -------------------------------- ### MySqlContainer Usage Source: https://testcontainers-python.readthedocs.io/en/latest/modules/mysql/README Demonstrates how to use the MySqlContainer to start a MySQL instance and connect to it using SQLAlchemy. ```APIDOC ## MySqlContainer ### Description MySql database container. It spins up a MySql database to which you can connect with the credentials passed in the constructor. Alternatively, you may use the `get_connection_url()` method which returns a sqlalchemy-compatible url. ### Method N/A (Class instantiation) ### Endpoint N/A (Class instantiation) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Constructor Parameters - **image** (str, optional) - The Docker image to use for the MySQL container. Defaults to 'mysql:latest'. - **dialect** (str | None, optional) - The SQLAlchemy dialect to use. Defaults to None. - **username** (str | None, optional) - The username for the database connection. Defaults to None. - **root_password** (str | None, optional) - The root password for the database. Defaults to None. - **password** (str | None, optional) - The password for the database connection. Defaults to None. - **dbname** (str | None, optional) - The name of the database to create. Defaults to None. - **port** (int, optional) - The port to expose the MySQL container on. Defaults to 3306. - **seed** (str | None, optional) - Path to a directory containing SQL files to be loaded on initialization. Defaults to None. - **kwargs** - Additional keyword arguments to pass to the container. ### Request Example ```python from testcontainers.mysql import MySqlContainer import sqlalchemy with MySqlContainer("mysql:5.7.17", dialect="pymysql") as mysql: engine = sqlalchemy.create_engine(mysql.get_connection_url()) with engine.begin() as connection: result = connection.execute(sqlalchemy.text("select version()")) version, = result.fetchone() print(f"MySQL version: {version}") ``` ### Response #### Success Response (200) N/A (Class instantiation, interaction via SQLAlchemy engine) #### Response Example N/A ### Additional Features #### Loading SQL Seed Files The optional `seed` parameter enables arbitrary SQL files to be loaded. This is perfect for schema and sample data. This works by mounting the seed to `/docker-entrypoint-initdb.d/`, which containerized MySQL are set up to load automatically. #### Getting Connection URL The `get_connection_url()` method returns a sqlalchemy-compatible URL in the format `mysql+dialect://username:password@host:port/database`. ``` -------------------------------- ### LocalStackContainer Usage Source: https://testcontainers-python.readthedocs.io/en/latest/modules/localstack/README Demonstrates how to initialize and use the LocalStackContainer to get clients for AWS services. ```APIDOC ## LocalStackContainer ### Description Provides a way to run a LocalStack container for emulating AWS cloud services during testing. You can obtain clients for various AWS services like DynamoDB, S3, etc., from the running container. ### Method Instantiate the `LocalStackContainer` class. ### Endpoint N/A (This is a class for creating a Docker container) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from testcontainers.localstack import LocalStackContainer with LocalStackContainer(image="localstack/localstack:2.0.1") as localstack: dynamo_client = localstack.get_client("dynamodb") tables = dynamo_client.list_tables() ``` ### Response #### Success Response (Container Started) - The `localstack` object is a context manager that yields a running container instance. - `localstack.get_client(service_name)` returns a boto3 client for the specified AWS service. #### Response Example ```json { "TableNames": [], ... } ``` ``` -------------------------------- ### Instantiate OllamaContainer in Python Source: https://testcontainers-python.readthedocs.io/en/latest/modules/ollama/README This code snippet demonstrates how to instantiate an OllamaContainer. It shows how to initialize the container with a specific Ollama image and optionally specify a directory for model data. The example then lists available models. ```python >>> from testcontainers.ollama import OllamaContainer >>> with OllamaContainer() as ollama: ... ollama.list_models() [] ``` -------------------------------- ### AWSLambdaContainer Example with DockerImage Source: https://testcontainers-python.readthedocs.io/en/latest/modules/aws/README Demonstrates how to use AWSLambdaContainer with a custom DockerImage to run an AWS Lambda function. It shows how to create a DockerImage from a local path, instantiate the AWSLambdaContainer, send a request to the Lambda function, and wait for specific logs to confirm execution. ```python from testcontainers.aws import AWSLambdaContainer from testcontainers.core.waiting_utils import wait_for_logs from testcontainers.core.image import DockerImage with DockerImage(path="./modules/aws/tests/lambda_sample", tag="test-lambda:latest") as image: with AWSLambdaContainer(image=image, port=8080) as func: response = func.send_request(data={'payload': 'some data'}) assert response.status_code == 200 assert "Hello from AWS Lambda using Python" in response.json() delay = wait_for_logs(func, "START RequestId:") ``` -------------------------------- ### Azurite Container Example with BlobServiceClient (Python) Source: https://testcontainers-python.readthedocs.io/en/latest/modules/azurite/README This snippet demonstrates how to initialize an AzuriteContainer, retrieve its connection string, and then use that connection string to create an Azure BlobServiceClient. It requires the 'testcontainers' and 'azure-storage-blob' libraries. ```python from testcontainers.azurite import AzuriteContainer from azure.storage.blob import BlobServiceClient with AzuriteContainer() as azurite_container: connection_string = azurite_container.get_connection_string() client = BlobServiceClient.from_connection_string( connection_string, api_version="2019-12-12" ) ``` -------------------------------- ### Start K3s Cluster and Interact with Kubernetes API using K3sContainer Source: https://testcontainers-python.readthedocs.io/en/latest/modules/k3s/README This snippet demonstrates how to instantiate a K3sContainer, load its configuration into the Kubernetes client, and then list pods to verify the cluster's functionality. It requires the 'yaml' and 'kubernetes' libraries, along with 'testcontainers'. ```python import yaml from testcontainers.k3s import K3SContainer from kubernetes import client, config with K3SContainer() as k3s: config.load_kube_config_from_dict(yaml.safe_load(k3s.config_yaml())) pod = client.CoreV1Api().list_pod_for_all_namespaces(limit=1) assert len(pod.items) > 0, "Unable to get running nodes from k3s cluster" ``` -------------------------------- ### PostgresContainer Initialization and Usage Source: https://testcontainers-python.readthedocs.io/en/latest/modules/postgres/README This section details how to initialize a PostgresContainer, including its default image and configurable parameters. It also provides an example of how to obtain a connection URL and use it with SQLAlchemy to interact with the PostgreSQL database. ```APIDOC ## PostgresContainer ### Description Represents a PostgreSQL database container. It allows for easy setup and management of PostgreSQL instances for testing or development purposes. ### Class Definition ```python class PostgresContainer(_image: str = 'postgres:latest', _port: int = 5432, _username: str | None = None, _password: str | None = None, _dbname: str | None = None, _driver: str | None = 'psycopg2', **kwargs) ``` ### Parameters * `_image` (str): The Docker image for the PostgreSQL container. Defaults to 'postgres:latest'. * `_port` (int): The port number for the PostgreSQL service within the container. Defaults to 5432. * `_username` (str | None): The username for connecting to the PostgreSQL database. Defaults to None. * `_password` (str | None): The password for connecting to the PostgreSQL database. Defaults to None. * `_dbname` (str | None): The name of the database to be created and used. Defaults to None. * `_driver` (str | None): The database driver to use for generating the connection URL. If None, no driver is included. Defaults to 'psycopg2'. * `**kwargs`: Additional keyword arguments to pass to the underlying Docker container. ### Methods * `get_connection_url()`: Returns the connection URL for the PostgreSQL database. The format of the URL depends on the `_driver` parameter. ### Example ```python from testcontainers.postgres import PostgresContainer import sqlalchemy # Spin up a Postgres database container using a specific image version with PostgresContainer("postgres:16") as postgres: # Create a SQLAlchemy engine using the connection URL provided by the container engine = sqlalchemy.create_engine(postgres.get_connection_url()) # Execute a SQL query to get the PostgreSQL version with engine.begin() as connection: result = connection.execute(sqlalchemy.text("select version()")) version, = result.fetchone() print(version) # Expected output: 'PostgreSQL 16...' (version may vary) ``` ### Response #### Success Response (Example of `get_connection_url()` output) * `connection_url` (str) - The JDBC/ODBC connection string for the PostgreSQL database. #### Response Example (from `get_connection_url()`) ``` postgresql+psycopg2://user:password@host:port/dbname ``` #### Success Response (Example of query result) * `version` (str) - The version string of the running PostgreSQL instance. #### Response Example (query result) ``` 'PostgreSQL 16.3 (Debian 16.3-1.pgdg120+1)' ``` ``` -------------------------------- ### MinioContainer Class API Source: https://testcontainers-python.readthedocs.io/en/latest/_sources/modules/minio/README.rst This section details the methods and attributes available for the MinioContainer class, which allows for easy setup and management of a MinIO instance within a Docker container. ```APIDOC ## MinioContainer Class API ### Description Provides an interface to manage a MinIO object storage service running in a Docker container. It simplifies the process of spinning up a MinIO instance for testing purposes. ### Methods and Attributes This class inherits from `GenericContainer` and provides specific configurations for MinIO. **Key Attributes/Methods (Inherited and Specific):** - **`image`**: The Docker image used for MinIO (e.g., `minio/minio`). - **`port_register`**: Registers the MinIO HTTP port (9000). - **`get_access_key()`**: Returns the configured access key for MinIO. - **`get_secret_key()`**: Returns the configured secret key for MinIO. - **`get_endpoint_url()`**: Returns the URL to access the MinIO service. ### Usage Example ```python from testcontainers.minio import MinioContainer # Instantiate MinioContainer with MinioContainer() as minio: # Get MinIO service URL endpoint_url = minio.get_endpoint_url() print(f"MinIO Endpoint: {endpoint_url}") # Get credentials access_key = minio.get_access_key() secret_key = minio.get_secret_key() print(f"Access Key: {access_key}") print(f"Secret Key: {secret_key}") # Now you can use these details to configure your MinIO client # Example using boto3 (not shown here for brevity) ``` ### Response #### Success Response (Instantiation) - **`MinioContainer` object**: A configured and running MinIO container instance. #### Response Example (from `get_endpoint_url()`) ```json { "endpoint_url": "http://localhost:9000" } ``` #### Response Example (from `get_access_key()`) ```json { "access_key": "minioadmin" } ``` #### Response Example (from `get_secret_key()`) ```json { "secret_key": "minioadmin" } ``` ``` -------------------------------- ### Create and Test FastAPI Server Container (Python) Source: https://testcontainers-python.readthedocs.io/en/latest/modules/generic/README This example shows how to deploy a FastAPI application within a ServerContainer. It includes waiting for a specific log message indicating the server is running and then accessing the API using a client. It relies on ServerContainer and DockerImage. ```python >>> from testcontainers.generic import ServerContainer >>> from testcontainers.core.waiting_utils import wait_for_logs >>> with DockerImage(path="./modules/generic/tests/samples/fastapi", tag="fastapi-test:latest") as image: ... with ServerContainer(port=80, image=image) as fastapi_server: ... delay = wait_for_logs(fastapi_server, "Uvicorn running on http://0.0.0.0:80") ... fastapi_server.get_api_url = lambda: fastapi_server._create_connection_url() + "/api/v1/" ... client = fastapi_server.get_client() ... response = client.get("/") ... assert response.status_code == 200 ... assert response.json() == {"Status": "Working"} ``` -------------------------------- ### Spin up a Mailpit Server for Testing with Python Source: https://testcontainers-python.readthedocs.io/en/latest/modules/mailpit/README Demonstrates how to initialize and use a MailpitContainer for testing email functionalities. The example shows how to access the container's host IP and SMTP port, and then establish an SMTP connection for login. It assumes default Mailpit configuration allowing any user/password authentication. ```python >>> import smtplib >>> from testcontainers.mailpit import MailpitContainer >>> with MailpitContainer() as mailpit_container: ... host_ip = mailpit_container.get_container_host_ip() ... host_port = mailpit_container.get_exposed_smtp_port() ... server = smtplib.SMTP( ... mailpit_container.get_container_host_ip(), ... mailpit_container.get_exposed_smtp_port(), ... ) ... code, _ = server.login("any", "auth") ... assert code == 235 # authentication successful ... # use server.sendmail(...) to send emails ``` -------------------------------- ### Start Weaviate Container with Default Settings (Python) Source: https://testcontainers-python.readthedocs.io/en/latest/modules/weaviate/README This code snippet demonstrates how to initialize and use a WeaviateContainer with its default settings. It utilizes a context manager for both the container and its client, and verifies the container's liveness. ```python from testcontainers.weaviate import WeaviateContainer with WeaviateContainer() as container: with container.get_client() as client: client.is_live() ``` -------------------------------- ### Start CosmosDB MongoDB Emulator (Python) Source: https://testcontainers-python.readthedocs.io/en/latest/modules/cosmosdb/README This snippet shows how to initialize and use the CosmosDB MongoDB endpoint emulator. It requires specifying the MongoDB version and provides connection details including host, port, key, and server certificate for TLS. ```python from testcontainers.cosmosdb import CosmosDBMongoEndpointContainer with CosmosDBMongoEndpointContainer(mongodb_version="4.0") as emulator: print(f"Point your MongoDB client at {emulator.host}:{emulator.port} using key {emulator.key}") print(f"and eiher disable TLS server auth or trust the server's self signed cert (emulator.server_certificate_pem)") ``` -------------------------------- ### Spin up Postgres and connect with SQLAlchemy Source: https://testcontainers-python.readthedocs.io/en/latest/modules/postgres/README This code snippet demonstrates how to instantiate a PostgreSQL container using PostgresContainer, create a SQLAlchemy engine using the container's connection URL, and execute a simple query to get the database version. It requires the 'testcontainers' and 'sqlalchemy' libraries. ```python 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() print(version) ``` -------------------------------- ### Initialize and Use MongoDbContainer in Python Source: https://testcontainers-python.readthedocs.io/en/latest/modules/mongodb/README Demonstrates how to initialize a MongoDbContainer, establish a connection, and perform basic database operations like inserting and retrieving documents. This example requires the 'pymongo' library for MongoDB interaction. ```python from testcontainers.mongodb import MongoDbContainer with MongoDbContainer("mongo:7.0.7") as mongo: db = mongo.get_connection_client().test # Insert a database entry result = db.restaurants.insert_one( { "name": "Vella", "cuisine": "Italian", "restaurant_id": "123456" } ) # Find the restaurant document result = db.restaurants.find_one({"name": "Vella"}) print(result["restaurant_id"]) ``` -------------------------------- ### RedisContainer Class Source: https://testcontainers-python.readthedocs.io/en/latest/modules/redis/README This section describes the RedisContainer class, its parameters, and provides an example of how to use it to get a Redis client. ```APIDOC ## RedisContainer Class ### Description Provides a Redis container managed by Testcontainers. Allows easy setup and interaction with a Redis instance for testing purposes. ### Parameters #### Initialization Parameters - **image** (str, optional) - The Docker image to use for the Redis container. Defaults to 'redis:latest'. - **port** (int, optional) - The port to expose for the Redis container. Defaults to 6379. - **password** (str | None, optional) - The password for Redis authentication. Defaults to None. - **kwargs** - Additional keyword arguments to pass to the base container class. ### Example Usage ```python from testcontainers.redis import RedisContainer # Using RedisContainer with default settings with RedisContainer() as redis_container: redis_client = redis_container.get_client() # Use redis_client for your tests # Example with custom image and port with RedisContainer(image='redis:7.0', port=6380) as redis_container_custom: redis_client_custom = redis_container_custom.get_client() ``` ### Methods - **get_client()**: Returns a Redis client instance connected to the container. ``` -------------------------------- ### Initialize and Use QdrantContainer Source: https://testcontainers-python.readthedocs.io/en/latest/modules/qdrant/README Demonstrates how to initialize a QdrantContainer and obtain a client to interact with the Qdrant database. This requires the testcontainers library and assumes a Qdrant image is available. ```python from testcontainers.qdrant import QdrantContainer with QdrantContainer() as qdrant: client = qdrant.get_client() client.get_collections() ``` -------------------------------- ### Initialize and Use Neo4jContainer with Driver Source: https://testcontainers-python.readthedocs.io/en/latest/modules/neo4j/README Demonstrates how to create a Neo4jContainer, obtain a driver for it, and then use the driver to interact with the database. This is useful for integration testing of applications that rely on Neo4j. ```python from testcontainers.neo4j import Neo4jContainer with Neo4jContainer() as neo4j, neo4j.get_driver() as driver, driver.session() as session: result = session.run("MATCH (n) RETURN n LIMIT 1") record = result.single() ``` -------------------------------- ### Minio Container Example with Python API Source: https://testcontainers-python.readthedocs.io/en/latest/modules/minio/README This snippet demonstrates spinning up a Minio container, creating a bucket, writing an object to it, and then retrieving that object using the Minio Python client. It utilizes the MinioContainer class from testcontainers-python. ```python import io from testcontainers.minio import MinioContainer with MinioContainer() as minio: client = minio.get_client() client.make_bucket("test") test_content = b"Hello World" write_result = client.put_object( "test", "testfile.txt", io.BytesIO(test_content), length=len(test_content), ) retrieved_content = client.get_object("test", "testfile.txt").data ``` -------------------------------- ### Spin up RabbitMQ Broker and Connect with Pika - Python Source: https://testcontainers-python.readthedocs.io/en/latest/modules/rabbitmq/README This snippet demonstrates how to instantiate and use the RabbitMqContainer to set up a RabbitMQ instance. It then shows how to obtain connection parameters and establish a connection using the pika library. ```python import pika from testcontainers.rabbitmq import RabbitMqContainer with RabbitMqContainer("rabbitmq:3.9.10") as rabbitmq: connection = pika.BlockingConnection(rabbitmq.get_connection_params()) channel = connection.channel() ``` -------------------------------- ### RedpandaContainer Usage (Python) Source: https://testcontainers-python.readthedocs.io/en/latest/modules/kafka/README Illustrates the instantiation and basic usage of RedpandaContainer to get bootstrap server connection details. This container is based on the Redpanda Docker image. ```python from testcontainers.kafka import RedpandaContainer with RedpandaContainer() as redpanda: connection = redpanda.get_bootstrap_server() ``` -------------------------------- ### Instantiate and Use MosquittoContainer (Python) Source: https://testcontainers-python.readthedocs.io/en/latest/modules/mqtt/README Demonstrates how to create an instance of MosquittoContainer and retrieve an MQTT client from it. This is useful for testing applications that rely on an MQTT broker. ```python from testcontainers.mqtt import MosquittoContainer with MosquittoContainer() as mosquitto_broker: mqtt_client = mosquitto_broker.get_client() ``` -------------------------------- ### KafkaContainer with KRaft Protocol (Python) Source: https://testcontainers-python.readthedocs.io/en/latest/modules/kafka/README Shows how to configure and use KafkaContainer with the KRaft protocol enabled. This involves calling the `.with_kraft()` method before starting the container to manage Kafka without ZooKeeper. ```python from testcontainers.kafka import KafkaContainer with KafkaContainer().with_kraft() as kafka: connection = kafka.get_bootstrap_server() ``` -------------------------------- ### Build and Run Docker Container with Python Source: https://testcontainers-python.readthedocs.io/en/latest/_sources/core/README.rst This snippet demonstrates building a Docker image from a local path and then running a container from that image using testcontainers-python. It utilizes DockerImage for image building and DockerContainer for container instantiation, along with wait_for_logs for basic container readiness checks. ```python from testcontainers.core.container import DockerContainer from testcontainers.core.waiting_utils import wait_for_logs from testcontainers.core.image import DockerImage with DockerImage(path="./core/tests/image_fixtures/sample/", tag="test-sample:latest") as image: with DockerContainer(str(image)) as container: delay = wait_for_logs(container, "Test Sample Image") ``` -------------------------------- ### MosquittoContainer Initialization and Usage Source: https://testcontainers-python.readthedocs.io/en/latest/modules/mqtt/README Demonstrates how to initialize and use the MosquittoContainer to create an MQTT client. ```APIDOC ## MosquittoContainer Initialization and Usage ### Description This section details the initialization and usage of the `MosquittoContainer` for setting up an MQTT broker. ### Method Instantiation and context management ### Endpoint N/A (Class-based usage) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from testcontainers.mqtt import MosquittoContainer with MosquittoContainer() as mosquitto_broker: mqtt_client = mosquitto_broker.get_client() ``` ### Response #### Success Response (Initialization) - `mosquitto_broker` (MosquittoContainer) - An instance of the running Mosquitto container. - `mqtt_client` (object) - A client object connected to the Mosquitto broker (specific type depends on implementation, e.g., paho-mqtt client). #### Response Example ```json { "message": "Mosquitto container started and client obtained." } ``` ``` -------------------------------- ### Instantiate and Use ElasticSearchContainer Source: https://testcontainers-python.readthedocs.io/en/latest/modules/elasticsearch/README This code snippet demonstrates how to instantiate an ElasticSearchContainer, specify an Elasticsearch version and memory limit, and then interact with the running container to retrieve its version number. It assumes the Elasticsearch Docker image is available and the testcontainers library is installed. ```python import json import urllib from testcontainers.elasticsearch import ElasticSearchContainer with ElasticSearchContainer(f'elasticsearch:8.3.3', mem_limit='3G') as es: resp = urllib.request.urlopen(es.get_url()) json.loads(resp.read().decode())['version']['number'] ``` -------------------------------- ### Initialize and Use SqlServerContainer with SQLAlchemy Source: https://testcontainers-python.readthedocs.io/en/latest/modules/mssql/README This snippet shows how to instantiate a SqlServerContainer for a specific SQL Server image, retrieve its connection URL, and establish a database connection using SQLAlchemy. It demonstrates a common pattern for integrating SQL Server containers into Python applications for testing. ```python import sqlalchemy from testcontainers.mssql import SqlServerContainer with SqlServerContainer("mcr.microsoft.com/mssql/server:2022-CU12-ubuntu-22.04") as mssql: engine = sqlalchemy.create_engine(mssql.get_connection_url()) with engine.begin() as connection: result = connection.execute(sqlalchemy.text("select @@VERSION")) ``` -------------------------------- ### Spin up Memcached Server with MemcachedContainer Source: https://testcontainers-python.readthedocs.io/en/latest/modules/memcached/README This snippet demonstrates how to instantiate and use the MemcachedContainer to launch a Memcached server. It shows how to retrieve the host and port of the running container, which are essential for connecting to the Memcached instance. ```python from testcontainers.memcached import MemcachedContainer with MemcachedContainer() as memcached_container: host, port = memcached_container.get_host_and_port() ``` -------------------------------- ### Use NatsContainer for NATS Testing Source: https://testcontainers-python.readthedocs.io/en/latest/modules/nats/README This Python snippet shows how to use the NatsContainer to spin up a NATS server, connect to it using the nats-py client, publish a message, and subscribe to it. It relies on the `testcontainers` and `nats` libraries. The example demonstrates a complete, self-contained test for NATS functionality. ```python import asyncio from nats import connect as nats_connect from testcontainers.nats import NatsContainer async def test_doctest_usage(): with NatsContainer() as nats_container: client = await nats_connect(nats_container.nats_uri()) sub_tc = await client.subscribe("tc") await client.publish("tc", b"Test-Containers") next_message = await sub_tc.next_msg(timeout=5.0) await client.close() return next_message.data asyncio.run(test_doctest_usage()) ``` -------------------------------- ### SqlServerContainer Usage Source: https://testcontainers-python.readthedocs.io/en/latest/modules/mssql/README Demonstrates how to initialize and use the SqlServerContainer to create a SQL Server instance and connect to it using SQLAlchemy. ```APIDOC ## SqlServerContainer ### Description Represents a Microsoft SQL Server database container. It allows you to easily spin up a SQL Server instance for testing purposes. ### Method Instantiate the `SqlServerContainer` class. ### Endpoint N/A (This is a class for managing Docker containers) ### Parameters * **image** (str, optional) - Defaults to 'mcr.microsoft.com/mssql/server:2019-latest'. The Docker image to use for the SQL Server container. * **username** (str, optional) - Defaults to 'SA'. The username for connecting to the SQL Server instance. * **password** (str | None, optional) - The password for connecting to the SQL Server instance. If None, a random password will be generated. * **port** (int, optional) - Defaults to 1433. The host port to map to the container's SQL Server port. * **dbname** (str, optional) - Defaults to 'tempdb'. The default database name to use. * **dialect** (str, optional) - Defaults to 'mssql+pymssql'. The SQLAlchemy dialect to use for the connection URL. * **kwargs** - Additional keyword arguments to pass to the underlying Docker container. ### Request Example ```python import sqlalchemy from testcontainers.mssql import SqlServerContainer with SqlServerContainer("mcr.microsoft.com/mssql/server:2022-CU12-ubuntu-22.04") as mssql: engine = sqlalchemy.create_engine(mssql.get_connection_url()) with engine.begin() as connection: result = connection.execute(sqlalchemy.text("select @@VERSION")) print(result.scalar()) ``` ### Response #### Success Response (Container Lifecycle) * The container starts when entering the `with` block. * The container stops and is removed when exiting the `with` block. * `get_connection_url()` returns a SQLAlchemy connection string. #### Response Example ```json { "connection_url": "mssql+pymssql://SA:GeneratedPassword@localhost:1433/tempdb" } ``` #### Error Handling * If the Docker image is not found, a `docker.errors.ImageNotFound` exception will be raised. * If the container fails to start, a `testcontainers.core.container.DockerException` will be raised. ``` -------------------------------- ### Create Container from Built Image with testcontainers-python Source: https://testcontainers-python.readthedocs.io/en/latest/core/README Shows how to first build a Docker image using DockerImage and then create a container from that image using DockerContainer. This pattern is common for testing applications that rely on custom container images. It requires the 'testcontainers' library. ```python from testcontainers.core.container import DockerContainer from testcontainers.core.waiting_utils import wait_for_logs from testcontainers.core.image import DockerImage with DockerImage(path="./core/tests/image_fixtures/sample/", tag="test-sample:latest") as image: with DockerContainer(str(image)) as container: delay = wait_for_logs(container, "Test Sample Image") ```