testcontainers-go
A comprehensive guide for using Testcontainers for Go to write reliable integration tests with Docker containers in Go projects. Supports 62+ pre-configured modules for databases, message queues, cloud services, and more. Use this skill when writing Go integration tests, setting up test databases (PostgreSQL, MySQL, Redis, MongoDB), testing with message queues (Kafka, RabbitMQ), or creating container-based test infrastructure. Covers modules, generic containers, networking, cleanup, wait strategies, CI/CD integration, and common anti-patterns.
What this skill does
# Testcontainers for Go Integration Testing
You are an expert Go developer specializing in integration testing with Testcontainers. When this skill is active, you should:
- **Always prefer pre-configured modules** over generic containers when a module exists
- **Follow the cleanup-before-error-check pattern** in every test you write
- **Use proper wait strategies** instead of `time.Sleep()` — never suggest `time.Sleep()` as a synchronization mechanism
- **Generate complete, runnable test code** including all necessary imports
- **Apply Go testing conventions** such as table-driven tests, `t.Parallel()`, build tags, and subtests
## Description
This skill helps you write integration tests using Testcontainers for Go, a Go library that provides lightweight, throwaway instances of common databases, message queues, web browsers, or anything that can run in a Docker container.
**Key capabilities:**
- Use 62+ pre-configured modules for common services (databases, message queues, cloud services, etc.)
- Set up and manage Docker containers in Go tests
- Configure networking, volumes, and environment variables
- Implement proper cleanup and resource management
- Debug and troubleshoot container issues
## When to Use This Skill
**Trigger keywords:** integration test, testcontainers, docker test, container test, database test, test with postgres, test with redis, test with kafka, real database test, end-to-end test infrastructure, test environment setup, test cleanup, test isolation.
Use this skill when you need to:
- Write integration tests that require real services (databases, message queues, etc.)
- Test against multiple versions or configurations of dependencies
- Create reproducible test environments
- Avoid mocking external dependencies in integration tests
- Set up ephemeral test infrastructure
- Run integration tests in CI/CD pipelines (GitHub Actions, GitLab CI, etc.)
- Share container setup across multiple tests in a package
## Prerequisites
- **Docker or Podman** installed and running
- **Go 1.24+** (check `go.mod` for project-specific requirements)
- **Docker socket** accessible at standard locations (Docker Desktop on macOS/Windows, `/var/run/docker.sock` on Linux)
## Decision Guide
Use this decision tree to choose the right approach:
```
Need a container for testing?
├── Is there a pre-configured module? (check module list below)
│ ├── YES → Use the module (Section 2)
│ └── NO → Use a generic container (Section 3)
│
├── Need multiple containers to communicate?
│ └── YES → Create a custom network (Section 5)
│
├── Need shared setup across tests in a package?
│ └── YES → Use TestMain pattern (Section 10)
│
├── Need to separate integration tests from unit tests?
│ └── YES → Use build tags (Section 10)
│
└── Running in CI/CD?
└── YES → See CI/CD Integration (Section 11)
```
## Instructions
### 1. Installation & Setup
Add testcontainers-go to your project:
```bash
go get github.com/testcontainers/testcontainers-go
```
For pre-configured modules (recommended):
```bash
# Example: PostgreSQL module
go get github.com/testcontainers/testcontainers-go/modules/postgres
# Example: Kafka module
go get github.com/testcontainers/testcontainers-go/modules/kafka
# Example: Redis module
go get github.com/testcontainers/testcontainers-go/modules/redis
```
**Verify Docker availability:**
```go
func TestDockerAvailable(t *testing.T) {
testcontainers.SkipIfProviderIsNotHealthy(t)
// Test will skip if Docker is not running
}
```
---
### 2. Using Pre-Configured Modules (Recommended Approach)
**Testcontainers for Go provides 62+ pre-configured modules** that offer production-ready configurations, sensible defaults, and helper methods. **Always prefer modules over generic containers** when available.
#### Why Use Modules?
- **Sensible defaults**: Pre-configured ports, environment variables, and wait strategies
- **Connection helpers**: Built-in methods like `ConnectionString()`, `Endpoint()`
- **Specialized features**: Module-specific functionality (e.g., Postgres snapshots, Kafka topic management)
- **Automatic credentials**: Secure credential generation and management
- **Battle-tested**: Used in production by thousands of projects
#### Available Module Categories
**Databases (17 modules):**
- `postgres`, `mysql`, `mariadb`, `mongodb`, `redis`, `valkey`
- `cockroachdb`, `clickhouse`, `memcached`, `influxdb`
- `arangodb`, `cassandra`, `scylladb`, `dynamodb`
- `dolt`, `databend`, `surrealdb`
**Message Queues (6 modules):**
- `kafka`, `rabbitmq`, `nats`, `pulsar`, `redpanda`, `solace`
**Search & Vector Databases (9 modules):**
- `elasticsearch`, `opensearch`, `meilisearch`
- `weaviate`, `qdrant`, `chroma`, `milvus`, `vearch`, `pinecone`
**Cloud & Infrastructure (6 modules):**
- `gcloud`, `azure`, `azurite`, `localstack`, `dind`, `k3s`
**Services & Tools (13 modules):**
- `consul`, `etcd`, `neo4j`, `couchbase`, `vault`, `openldap`
- `artemis`, `inbucket`, `mockserver`, `nebulagraph`, `minio`
- `toxiproxy`, `aerospike`
**Development (10 modules):**
- `compose`, `registry`, `k6`, `ollama`, `grafana-lgtm`
- `dockermodelrunner`, `dockermcpgateway`, `socat`, `mssql`
#### Basic Module Usage Pattern
```go
package myapp_test
import (
"context"
"testing"
"github.com/stretchr/testify/require"
"github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/modules/postgres"
)
func TestWithPostgres(t *testing.T) {
ctx := context.Background()
// Start PostgreSQL container with sensible defaults
pgContainer, err := postgres.Run(ctx, "postgres:16-alpine")
testcontainers.CleanupContainer(t, pgContainer)
require.NoError(t, err)
// Get connection string - credentials auto-generated
connStr, err := pgContainer.ConnectionString(ctx)
require.NoError(t, err)
// connStr: "postgres://postgres:password@localhost:49153/postgres?sslmode=disable"
// Use connection string with your database driver
db, err := sql.Open("postgres", connStr)
require.NoError(t, err)
defer db.Close()
// Run your tests...
}
```
#### Module Configuration with Options
Modules support three levels of customization:
**Level 1: Simple Options (via testcontainers.CustomizeRequestOption)**
```go
pgContainer, err := postgres.Run(
ctx,
"postgres:16-alpine",
testcontainers.WithEnv(map[string]string{
"POSTGRES_DB": "myapp_test",
}),
testcontainers.WithLabels(map[string]string{
"env": "test",
}),
)
```
**Level 2: Module-Specific Options**
```go
// PostgreSQL with init scripts
pgContainer, err := postgres.Run(
ctx,
"postgres:16-alpine",
postgres.WithInitScripts("./testdata/init.sql"),
postgres.WithDatabase("myapp_test"),
postgres.WithUsername("custom_user"),
postgres.WithPassword("custom_pass"),
)
// Redis with configuration
redisContainer, err := redis.Run(
ctx,
"redis:7-alpine",
redis.WithSnapshotting(10, 1),
redis.WithLogLevel(redis.LogLevelVerbose),
)
// Kafka with custom config
kafkaContainer, err := kafka.Run(
ctx,
"confluentinc/confluent-local:7.5.0",
kafka.WithClusterID("test-cluster"),
)
```
**Level 3: Advanced Configuration with Lifecycle Hooks**
```go
// PostgreSQL with custom initialization
pgContainer, err := postgres.Run(
ctx,
"postgres:16-alpine",
postgres.WithDatabase("myapp"),
testcontainers.WithLifecycleHooks(
testcontainers.ContainerLifecycleHooks{
PostStarts: []testcontainers.ContainerHook{
func(ctx context.Context, c testcontainers.Container) error {
// Custom initialization after container starts
return nil
},
},
},
),
)
```
#### Module-Specific Helper Methods
Most modules provide convenience methods beyond `ConnectionString()`:
```go
// PostgreSQL: Snapshot & Restore for test isolation
func TestDatabaseIsolation(t *Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.