testcontainers-modules

repository·main·Indexed 41 days ago

https://github.com/testcontainers/testcontainers-rs-modules-community

Community-maintained Docker module definitions for the Rust testcontainers ecosystem (v0.15.0). Provides pre-configured containers for services including Postgres, Redis, MinIO, OpenLDAP, AnvilNode, Arrow FlightSQL, Dex, and Google Cloud SDK emulators (Bigtable, Firestore, Datastore, Pub/Sub, and Spanner).

Tokens
11K
Snippets
43
Records
55
Agent score
48%

What's inside testcontainers-modules

  1. Use modules with SyncRunner or AsyncRunner

    main

    Once the features are enabled, you can start containers using either AsyncRunner or SyncRunner. For synchronous tests, ensure the blocking feature is enabled and use SyncRunner.

    use testcontainers_modules::{postgres, testcontainers::runners::SyncRunner};
    
    #[test]
    fn test_with_postgres() {
        let container = postgres::Postgres::default().start().unwrap();
        let host_ip = container.get_host().unwrap();
        let host_port = container.get_host_port_ipv4(5432).unwrap();
    }
  2. Override module defaults like version, tag, and ENV-variables

    main

    You can customize a module's configuration by using methods provided by RunnableImage. This allows you to specify a custom Docker image tag or set environment variables for the container.

    use testcontainers_modules::{
        redis::Redis,
        testcontainers::{ContainerRequest, ImageExt}
    };
    
    /// Create a Redis module with `6.2-alpine` tag and custom password
    fn create_redis() -> ContainerRequest<Redis> {
        Redis::default()
            .with_tag("6.2-alpine")
            .with_env_var("REDIS_PASSWORD", "my_secret_password")
    }
  3. Configure TLS for OpenLDAP testing

    main

    To test TLS connections with the OpenLDAP container, you must provide a certificate and a private key. The project includes a generate-certs.sh script that automates the generation of all required TLS artifacts.

    Note: If you generate new certificates for your tests, ensure you verify the OpenSSL version used, as compatibility may depend on the version (e.g., OpenSSL 3.0.13).

    # Use the provided script to generate TLS artifacts
    ./generate-certs.sh
    
    # Verify your openssl version
    openssl version
  4. Install testcontainers-modules

    main

    To use community modules, add testcontainers-modules to your Cargo.toml and enable the specific features for the modules you need (e.g., postgres, minio).

    If you intend to use modules within synchronous tests, you must also enable the blocking feature to allow usage with SyncRunner.

    # Example Cargo.toml dependency configuration
    [dev-dependencies]
    testcontainers-modules = { version = "0.15.0", features = ["postgres", "blocking"] }
  5. Available Testcontainer Modules

    main

    The testcontainers-rs-modules-community crate provides a collection of community-maintained Testcontainers for various databases, messaging systems, and infrastructure tools. Each module is gated behind a specific Cargo feature. To use a module, you must enable its corresponding feature in your Cargo.toml.

    Available modules include:

    • Databases: postgres, mysql, mariadb, mssql_server, oracle, cockroach_db, cassandra, scylladb, mongodb, redis, valkey, clickhouse, cratedb, databend, surrealdb, rqlite, neo4j, orientdb.
    • Search & Analytics: elastic_search, meilisearch, solr, weaviate, victoria_metrics.
    • Messaging & Streaming: kafka, rabbitmq, nats, pulsar, elasticmq, mosquitto, zookeeper.
    • Cloud & Storage Emulators: localstack, azurite, minio, rustfs, fakecloud, google_cloud_sdk_emulators.
    • Identity & Security: hashicorp_vault, dex, zitadel, consul, openldap.
    • Blockchain/Ethereum: anvil, parity_parity, trufflesuite_ganachecli.
    • Other Infrastructure: selenium, gitea, k3s, kwok, hickory_dns, cncf_distribution, arrow_flightsql.
  6. Use the Postgres Testcontainer

    main

    The Postgres struct allows you to start a PostgreSQL instance for testing purposes. By default, it uses the 11-alpine image with the database name, user, and password all set to postgres.

    To use it, call Postgres::default() and then .start() (using a runner like SyncRunner). You can then retrieve the host and port to construct a connection string for your database client.

    use testcontainers_modules::{postgres, testcontainers::runners::SyncRunner};
    
    let postgres_instance = postgres::Postgres::default().start().unwrap();
    
    let connection_string = format!(
        "postgres://postgres:postgres@{}:{}/postgres",
        postgres_instance.get_host().unwrap(),
        postgres_instance.get_host_port_ipv4(5432).unwrap()
    );
  7. Use the Valkey Testcontainer

    main

    The Valkey struct allows you to start a Valkey instance (a high-performance data structure server) for testing. By default, it uses the valkey/valkey:8.0.2-alpine image and exposes port 6379. Because Valkey is compatible with the Redis protocol, you can use standard Redis client libraries to communicate with it.

    use redis::Commands;
    use testcontainers_modules::{
        testcontainers::runners::SyncRunner,
        valkey::{Valkey, VALKEY_PORT},
    };
    
    let valkey_instance = Valkey::default().start().unwrap();
    let host_ip = valkey_instance.get_host().unwrap();
    let host_port = valkey_instance.get_host_port_ipv4(VALKEY_PORT).unwrap();
    
    let url = format!("redis://{host_ip}:{host_port}");
    let client = redis::Client::open(url.as_ref()).unwrap();
    let mut con = client.get_connection().unwrap();
    
    con.set::<_, _, ()>("my_key", 42).unwrap();
    let result: i64 = con.get("my_key").unwrap();
  8. Use the Dex Testcontainer

    main

    Dex is a lightweight OpenID Connect provider. You can use the Dex struct to spin up a Dex instance in your tests using the official dexidp/dex Docker image. The container exposes its HTTP endpoint on port 5556.

    use testcontainers::runners::SyncRunner;
    use testcontainers_modules::dex;
    
    let dex = dex::Dex::default()
        .with_simple_user()
        .with_simple_client()
        .start()
        .unwrap();
    let port = dex.get_host_port_ipv4(5556).unwrap();
  9. Enable specific modules via Cargo features

    main

    Modules in this crate are conditionally compiled. To use a specific module, you must enable its feature in your Cargo.toml. For example, to use the postgres and redis modules, add the following to your dependencies:

    [dependencies]
    testcontainers-rs-modules-community = {
        version = "0.15.0",
        features = ["postgres", "redis"]
    }
  10. Use the K3s Testcontainer

    main

    The K3s module provides a Testcontainer for running a single-node, fully-functional Kubernetes cluster using the official rancher/k3s image. You can interact with the cluster using standard Kubernetes APIs via the exposed KUBE_SECURE_PORT.

    To use K3s effectively in tests, it is recommended to:

    1. Use .with_conf_mount(path) to mount a host directory for configuration files.
    2. Use .with_privileged(true) and .with_userns_mode("host") to ensure the container has the necessary permissions to run Kubernetes components.
    3. Use .read_kube_config() to retrieve the k3s.yaml file from the mounted host directory to connect your Kubernetes client.
    use std::env::temp_dir;
    
    use testcontainers_modules::{
        k3s::{K3s, KUBE_SECURE_PORT},
        testcontainers::{runners::SyncRunner, ImageExt},
    };
    
    let k3s_instance = K3s::default()
        .with_conf_mount(&temp_dir())
        .with_privileged(true)
        .with_userns_mode("host")
        .start()
        .unwrap();
    
    let kube_port = k3s_instance.get_host_port_ipv4(KUBE_SECURE_PORT);
    let kube_conf = k3s_instance
        .image()
        .read_kube_config()
        .expect("Cannot read kube conf");
    // use kube_port and kube_conf to connect and control k3s cluster