Skip to main content

Module test

Module test 

Source
Expand description

§🔬 Test Environment Infrastructure

This module provides utilities for bootstrapping and managing an isolated integration test environment powered by Docker containers and an async server runtime.

It is designed to:

  • Provision and manage test containers (e.g., Postgres, Keycloak)
  • Coordinate initialization and shutdown across threads
  • Provide global access to running containers
  • Ensure deterministic teardown after tests complete
  • Offer structured logging with colored output

The module is intended for integration and end-to-end testing scenarios where external dependencies must be provisioned dynamically.


§Architecture Overview

The test environment follows a controlled lifecycle with three main phases:

  1. Setup Phase

    • Initializes logging
    • Starts required containers
    • Executes optional post-initialization tasks
    • Signals readiness to the test runtime
  2. Execution Phase

    • Tests run against the live server and provisioned services
    • Containers remain active and globally accessible
  3. Teardown Phase

    • Receives shutdown signal
    • Stops and removes all registered containers
    • Releases global resources

Synchronization between phases is handled using global channels and locks.


§Global Resource Management

The module maintains global state using OnceLock to guarantee safe, single initialization across threads:

  • Docker Client A shared connection to the Docker daemon used for container inspection and removal.

  • Container Registry A global, thread-safe map storing container names and their IDs. This enables coordinated teardown after tests complete.

  • Lifecycle Channels Internal channels synchronize initialization completion and shutdown signals between threads.


§Logging

Logging is automatically configured during setup using env_logger.

Features:

  • Colored log levels
  • Timestamped output
  • Module-aware formatting
  • Environment-driven log filtering (RUST_LOG)
  • Suppression of noisy framework logs by default

This improves readability during test execution and debugging.


§Public API

§setup

Bootstraps the full test environment.

Responsibilities:

  • Initializes logging
  • Executes user-provided initialization logic
  • Starts the application server
  • Runs optional post-initialization tasks
  • Blocks until environment is ready

The initialization closure must return:

  • A collection of container handles (to prevent premature drop)
  • Application Settings used to start the server

§teardown

Gracefully shuts down the environment by:

  • Sending a stop signal to all containers
  • Removing containers from Docker
  • Waiting for shutdown confirmation

This function should be called once after all tests complete.

§get_container

Retrieves metadata for a registered container by name using the Docker API.

§add_container

Registers a container in the global container map so it can be stopped automatically during teardown.


§Blocking Execution Helper

The module provides an internal utility for executing async code from synchronous contexts by creating a dedicated Tokio runtime. This is used primarily during container shutdown and cleanup.


§Container Utilities

The containers submodule provides helpers for starting commonly used infrastructure services.

§Supported Services

  • Postgres Starts a database container with optional initialization scripts, network configuration, and credentials.

  • Keycloak Starts an identity provider container with realm import support and readiness checks.

Each container:

  • Waits for readiness before returning
  • Registers itself for automatic teardown
  • Returns a connection URI for test usage

§Error Handling

All operations use the module-specific TestError type, which captures:

  • Container creation failures
  • Filesystem path resolution errors
  • Custom runtime errors

§Typical Usage Pattern

ⓘ
#[ctor::ctor]
pub fn setup() {
    rust_microservice::test::setup(
        async || {
            let mut settings = load_test_settings();

            // This vector serves as a workaround for Testcontainers’ automatic cleanup,
            // ensuring that containers remain available until all tests have completed.
            let mut containers: Vec<Box<dyn Any + Send>> = vec![];

            let postgres = start_postgres_container(&mut settings).await;
            if let Ok(postgres) = postgres {
                containers.push(Box::new(postgres.0));
            }

            let keycloak = start_keycloak_container(&mut settings).await;
            if let Ok(keycloak) = keycloak {
                containers.push(Box::new(keycloak.0));
            }

            (containers, settings)
        },
        || async {
            info!("Getting authorization token ...");
            let oauth2_token = get_auth_token().await.unwrap_or("".to_string());
            TOKEN.set(oauth2_token);
            info!("Authorization token: {}...", token()[..50].bright_blue());
        },
    );
}

Teardown is handled automatically by the dtor attribute.

ⓘ
#[ctor::dtor]
pub fn teardown() {
    rust_microservice::test::teardown();
}

§Concurrency Model

The environment runs inside a dedicated multi-thread Tokio runtime spawned in a background thread. This allows synchronous test code to coordinate with async infrastructure without requiring async test functions.

Communication is performed via channels that coordinate:

  • Initialization completion
  • Container stop commands
  • Shutdown confirmation

§Intended Use Cases

This module is suitable for:

  • Integration testing
  • End-to-end testing
  • CI environments requiring ephemeral infrastructure
  • Local development with disposable dependencies

It is not intended for production runtime container management.


§Safety Guarantees

  • Containers remain alive for the full test lifecycle
  • Teardown is deterministic and blocking
  • Global state is initialized exactly once
  • Async resources are properly awaited before shutdown

§Notes

The environment assumes Docker is available and reachable using default configuration. Failure to connect to the Docker daemon will cause setup to abort.

All containers are forcefully removed during teardown to ensure a clean test environment for subsequent runs.

Modules§

containers

Enums§

TestError

Functions§

add_container
Adds a container to the container map.
get_container
Retrieves a container by its name from the container map.
setup
Sets up the test environment by initializing the log, printing an ASCII art banner, and spawning a new thread that will execute the given closure.
teardown
Shuts down the test environment by blocking on the shutdown signal.

Type Aliases§

Result