Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

testcontainers

БесплатноБез исполняемых скриптовНе проверен

Use when integration tests need a real database, message broker or browser (Postgres, Redis, Kafka, Selenium) in a container, or when containerized tests are…

testlandот testland★ 18 звёзд на GitHub

Об этом скилле

testcontainers

Overview

Testcontainers is "a library that provides easy and lightweight APIs for bootstrapping local development and test dependencies with real services wrapped in Docker containers" (tc-getting-started). It exists for Java, Go, .NET, Node.js, Clojure, Elixir, Haskell, Python, Ruby, Rust, PHP, and Native (C) (tc-getting-started).

The shape is the same in every language:

  1. The test process declares the container it needs (image + exposed ports + wait strategy + optional env / volumes / network).
  2. The library starts the container, waits for it to be ready, and maps the exposed port to a random free host port so multiple tests can run in parallel without port collisions (tc-getting-started).
  3. The test reads getHost() + getMappedPort(<container-port>) to build a connection URL.
  4. After the test, the container is destroyed - even on SIGKILL.

The cleanup guarantee is enforced by Ryuk, a sidecar reaper: "Testcontainers attaches a set of labels to the created resources (containers, volumes, networks etc) and Ryuk automatically performs resource clean up by matching those labels. This works reliably even when the test process exits abnormally (e.g. sending a SIGKILL)" (tc-getting-started).

When to use

  • Integration tests need a real Postgres / MySQL / Redis / Kafka / MongoDB / Elasticsearch - not a fake or in-memory substitute that drifts from production behavior.
  • E2E tests need a real Selenium / Playwright browser container.
  • A test process must spin up its own dependencies because shared CI databases create cross-job interference.
  • The team wants a single API surface across Java / Node / Python / Go rather than per-language ad-hoc docker scripts.

If the team needs multiple related containers wired with their own network and lifecycle (e.g. app + db + cache), evaluate docker-compose-tests first - it expresses the topology in declarative YAML rather than imperative test code.

Step 1 - Pick the language module

Language Package / Coordinate
Java org.testcontainers:testcontainers (Maven / Gradle)
Node.js npm install --save-dev testcontainers
Python pip install testcontainers[<module>] (e.g. [postgres])
Go go get github.com/testcontainers/testcontainers-go
.NET dotnet add package Testcontainers

Java requires "a supported JVM testing framework" with Jupiter / JUnit 5 as the recommended option (tc-java). Python uses an "extras" notation: pip install testcontainers[postgres] installs both the core library and the Postgres module (tc-python).

Step 2 - Author the container declaration

Java (GenericContainer)

Per tc-getting-started:

GenericContainer container = new GenericContainer("postgres:15")
        .withExposedPorts(5432)
        .waitingFor(new LogMessageWaitStrategy()
            .withRegEx(".*database system is ready to accept connections.*\\s")
            .withTimes(2)
            .withStartupTimeout(Duration.of(60, ChronoUnit.SECONDS)));
container.start();

var jdbcUrl = "jdbc:postgresql://"
            + container.getHost()
            + ":" + container.getMappedPort(5432)
            + "/test";
// ...perform DB operations...
container.stop();

The LogMessageWaitStrategy example uses withTimes(2) because Postgres logs the "ready to accept connections" line twice during startup - once for the bootstrap process and once for the listener.

Node.js (GenericContainer)

The with* builder API mirrors Java; .start() returns a Promise:

import { GenericContainer, Wait } from 'testcontainers';

const container = await new GenericContainer('postgres:15')
  .withExposedPorts(5432)
  .withEnvironment({ POSTGRES_PASSWORD: 'test' })
  .withWaitStrategy(Wait.forLogMessage(/database system is ready/, 2))
  .start();

const url = `postgresql://postgres:test@${container.getHost()}:${container.getMappedPort(5432)}/postgres`;
// ...
await container.stop();

Python (context manager, preferred)

Per tc-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)
    # ...

The with-statement guarantees stop() runs on exit - including on exception. Prefer the per-service modules (PostgresContainer, MySqlContainer, KafkaContainer) over raw DockerContainer when they exist; they ship sensible defaults and a typed connection-URL hel

Полный SKILL.md на GitHub

Установить testcontainers в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

.tessl-plugin/plugin.jsonevals/api-container-cannot-reach-database/criteria.jsonevals/api-container-cannot-reach-database/task.mdevals/containers-linger-after-go-suite/criteria.jsonevals/containers-linger-after-go-suite/task.mdevals/db-restarts-for-every-pytest-test/criteria.jsonevals/db-restarts-for-every-pytest-test/task.mdevals/fixed-host-port-collides-in-ci/criteria.jsonevals/fixed-host-port-collides-in-ci/task.mdevals/local-loop-never-reuses-the-index/criteria.jsonevals/local-loop-never-reuses-the-index/task.mdevals/network-teardown-races-across-suites/criteria.jsonevals/network-teardown-races-across-suites/task.mdevals/parallel-methods-share-one-container/criteria.jsonevals/parallel-methods-share-one-container/task.mdevals/ready-log-fires-before-listener-binds/criteria.jsonevals/ready-log-fires-before-listener-binds/task.mdevals/service-container-cannot-reach-test-stub/criteria.jsonevals/service-container-cannot-reach-test-stub/task.mdevals/suite-sleeps-waiting-for-broker/criteria.jsonevals/suite-sleeps-waiting-for-broker/task.md

FAQ

Что делает скилл testcontainers?

Use when integration tests need a real database, message broker or browser (Postgres, Redis, Kafka, Selenium) in a container, or when containerized tests are flaky: a fixed sleep waiting for a service, a container reported ready before it accepts connections, parallel tests sharing one container's data, or network teardown errors. Starts throwaway containers from inside the test process with Testcontainers (Java, Node.js, Python, Go, .NET, Ruby and more), wiring the container lifecycle, mapped host ports, wait strategies (port, log, HTTP, SQL), networks, Ryuk cleanup and the experimental withReuse for local dev.

Как установить скилл testcontainers?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл testcontainers запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить testcontainers с