#container #docker #test-containers #podman

rustainers

以简单、有见地的方式运行测试容器

3个版本 (重大更新)

0.12.0 2024年3月27日
0.11.0 2023年11月30日
0.10.0 2023年11月21日

#111 in 测试

Download history 33/week @ 2024-04-09 57/week @ 2024-04-16 25/week @ 2024-04-23 59/week @ 2024-04-30 98/week @ 2024-05-07 65/week @ 2024-05-14 24/week @ 2024-05-21 22/week @ 2024-05-28 40/week @ 2024-06-04 6/week @ 2024-06-11 46/week @ 2024-07-02 51/week @ 2024-07-09 82/week @ 2024-07-16 169/week @ 2024-07-23

每月下载 348次
3 crates 中使用

MIT/Apache

180KB
4.5K SLoC

Build status Crates.io Documentation

rustainers

rustainers 是一种简单、有见地的方式来运行测试容器。

TL;DR

有关此crate的更多信息,请参阅 crate文档

或者查看 示例目录

与testcontainers的差异

此crate是testcontainers-rs crate的替代方案。

主要差异包括

目前,实现基于CLI命令。我们可能会在以后添加基于Rust API的更多运行器。

运行简单的容器

你需要一个 Runner 来启动镜像。你可以使用 Runner::auto 函数来检测可用的运行器,或者使用 Runner::dockerRunner::podmanRunner::nerdctl 函数来选择特定的运行器。

然后你需要创建一个可运行的镜像,查看模块 images 以使用现有镜像,或创建自己的镜像。

您只需要启动您的镜像。运行中的容器可以提供一些方法来帮助您使用该容器,例如访问容器的连接URL。

use rustainers::runner::{Runner, RunOption};
use rustainers::images::Postgres;

async fn pg() -> anyhow::Result<()> {
    let runner = Runner::auto()?;
    let image = Postgres::default().with_tag("15.2");
    let container = runner.start(image).await?;

    let url = container.url().await?;
    do_something_with_postgres(url).await?;
    Ok(())
}

async fn do_something_with_postgres(url: String) -> anyhow::Result<()> { 
    Ok(())
}

容器的生命周期

当您启动一个可运行的镜像时,运行器首先检查容器的状态。它可能已经存在,或者我们可能需要创建它。

然后,运行器等待所有等待策略完成,例如,它可以检查容器的健康状态。

然后,它返回一个容器。这个容器引用了一个可运行的镜像,这个镜像可以提供辅助函数来检索数据库URL等。

容器被丢弃时,默认情况下,它会停止容器。

您可以选择分离容器以避免在丢弃时停止。

使用compose

要运行由docker-compose文件定义的容器,您也需要一个运行器。

然后,您可以使用compose_start来启动您的容器。

use rdkafka::producer::{FutureProducer, FutureRecord};
use rdkafka::ClientConfig;
use tracing::{info, Level};

use rustainers::compose::images::KafkaSchemaRegistry;
use rustainers::runner::Runner;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let runner = Runner::auto()?;
    let image = KafkaSchemaRegistry::build_single_kraft().await?;
    let containers = runner.compose_start(image).await?;
    info!("Now I can use {containers}");
    do_something_with_kafka(&containers).await?;

   Ok(())
}

async fn do_something_with_kafka(image: &KafkaSchemaRegistry) -> anyhow::Result<()> {
    let topic = "plop";
    let broker_address = image.broker_address().await?;
    info!("Using kafka broker: {broker_address}");

    let schema_registry_url = image.schema_registry_endpoint().await?;
    info!("Using schema registry: {schema_registry_url}");

    // ...
    Ok(())
}

创建自定义镜像

请参阅images模块文档。

创建自定义compose镜像

请参阅compose::images模块文档。

依赖关系

~7–19MB
~286K SLoC