簡體   English   中英

在 testcontainers 中使用 PostgreSQLContainer 和圖像 on-the-fly

[英]Use PostgreSQLContainer with image on-the-fly in testcontainers

目標

我想使用定制的 PostgreSQL 映像,並帶有測試容器的語言環境支持。

在 postgres 方面

我准備Dockerfile ,如postgres 圖像文檔中所述:

您可以使用簡單的 Dockerfile 擴展基於 Debian 的映像以設置不同的語言環境。 以下示例將默認語言環境設置為 de_DE.utf8:

來自 postgres:14.3

運行 localedef -i de_DE -c -f UTF-8 -A /usr/share/locale/locale.alias de_DE.UTF-8

ENV LANG de_DE.utf8

因此,該圖像的工作方式基本上沒有任何變化,但在語言環境支持方面具有更多功能。

在測試容器方面

我想按照testcontainers 文檔中的描述使用它:

只需將 ImageFromDockerfile 的配置實例作為構造函數參數傳遞給 GenericContainer。 Testcontainers 將 docker 構建一個臨時容器鏡像,並在創建容器時使用它。

public GenericContainer dslContainer = new GenericContainer(
new ImageFromDockerfile()
        .withFileFromString("folder/someFile.txt", "hello")
        .withFileFromClasspath("test.txt", "mappable-resource/test-resource.txt")
        .withFileFromClasspath("Dockerfile", "mappable-dockerfile/Dockerfile"))

問題

在上面的示例中, testcontainers 使用GenericContainer GenericContainer公開構造函數public GenericContainer(final Future<String> image) ,它允許它與ImageFromDockerfile一起使用。 遺憾的是PostgreSQLContainer沒有提供這樣的構造函數,但我仍然想使用這個 class 因為它有幾個內部設置可以很好地支持 postgres。 PostgreSQLContainer中有兩個構造函數,但它們只接受圖像名稱。

我能想到的唯一解決方案是基本上制作原始PostgreSQLContainer的本地副本並添加缺少的構造函數。 這似乎工作正常,但由於顯而易見的原因,它是一個骯臟的黑客。

問題

我的問題是:我是否錯過了使用 testcontainers 提供的工具完成任務的其他方法? 還是在測試容器中添加這樣的公共構造函數是一個改進的領域?

我相信解決方案是:

import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.containers.wait.strategy.LogMessageWaitStrategy;
import org.testcontainers.images.builder.ImageFromDockerfile;
import org.testcontainers.utility.DockerImageName;

import java.net.URI;
import java.nio.file.Paths;
import java.time.Duration;

import static java.time.temporal.ChronoUnit.SECONDS;

public class Demo {

    public static void main(String[] args) throws Exception {
        // the most buggy part - need to investigate
        // how to work properly with ImageFromDockerfile
        URI path = Demo.class.getResource("/PostgreSQLde").toURI();
        ImageFromDockerfile image = new ImageFromDockerfile()
                .withDockerfile(Paths.get(path));
        DockerImageName imageName = DockerImageName.parse(image.get())
                .asCompatibleSubstituteFor(PostgreSQLContainer.IMAGE);
        new PostgreSQLContainer<>(imageName)
                .waitingFor(new LogMessageWaitStrategy()
                        // oops
                        .withRegEx(".*Datenbanksystem ist bereit, um Verbindungen anzunehmen.*\\s")
                        .withTimes(2)
                        .withStartupTimeout(Duration.of(60, SECONDS)))
                .start();
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM