Skip to content

Instantly share code, notes, and snippets.

@AlexAkulov
Created June 25, 2025 16:20
Show Gist options
  • Save AlexAkulov/12644f01ef36d5faade8b3cedd86fbe8 to your computer and use it in GitHub Desktop.
Save AlexAkulov/12644f01ef36d5faade8b3cedd86fbe8 to your computer and use it in GitHub Desktop.
package main
import (
"context"
"testing"
"time"
"github.com/jackc/pgx/v5"
"github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/modules/postgres"
"github.com/testcontainers/testcontainers-go/wait"
)
func setupDB(t *testing.T) (conn *pgx.Conn, terminate func()) {
t.Helper()
ctx := context.Background()
// Запускаем контейнер PostgreSQL
container, err := postgres.Run(ctx,
"postgres:15-alpine",
postgres.WithDatabase("testdb"),
postgres.WithUsername("testuser"),
postgres.WithPassword("testpass"),
testcontainers.WithWaitStrategy(
wait.ForListeningPort("5432/tcp").WithStartupTimeout(10*time.Second),
),
)
if err != nil {
t.Fatalf("failed to start container: %v", err)
}
endpoint, err := container.ConnectionString(ctx, "sslmode=disable")
if err != nil {
t.Fatalf("failed to get connection string: %v", err)
}
conn, err = pgx.Connect(ctx, endpoint)
if err != nil {
t.Fatalf("failed to connect to postgres: %v", err)
}
// Миграция: создаем таблицу
_, err = conn.Exec(ctx, `
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL
);
`)
if err != nil {
t.Fatalf("failed to run migration: %v", err)
}
// Возврат функции очистки
return conn, func() {
conn.Close(ctx)
container.Terminate(ctx)
}
}
func insertUser(ctx context.Context, conn *pgx.Conn, name string) error {
_, err := conn.Exec(ctx, `INSERT INTO users(name) VALUES($1)`, name)
return err
}
func countUsers(ctx context.Context, conn *pgx.Conn) (int, error) {
var count int
err := conn.QueryRow(ctx, `SELECT COUNT(*) FROM users`).Scan(&count)
return count, err
}
func TestInsertUser(t *testing.T) {
conn, terminate := setupDB(t)
defer terminate()
ctx := context.Background()
if err := insertUser(ctx, conn, "Alice"); err != nil {
t.Fatalf("failed to insert user: %v", err)
}
count, err := countUsers(ctx, conn)
if err != nil {
t.Fatalf("failed to count users: %v", err)
}
if count != 1 {
t.Fatalf("expected 1 user, got %d", count)
}
}
@AlexAkulov
Copy link
Author

 % go test -v
=== RUN   TestInsertUser
2025/06/25 21:18:37 github.com/testcontainers/testcontainers-go - Connected to docker: 
  Server Version: 27.3.1
  API Version: 1.47
  Operating System: OrbStack
  Total Memory: 8991 MB
  Testcontainers for Go Version: v0.37.0
  Resolved Docker Host: unix:///var/run/docker.sock
  Resolved Docker Socket Path: /var/run/docker.sock
  Test SessionID: 8a7c4a88effd4fc57aa7cf1ec0df4329a87a87295622173a5438437e59b5a758
  Test ProcessID: 6ec0f94b-f2b6-4ede-a518-53c8a8851e6a
2025/06/25 21:18:37 🐳 Creating container for image postgres:15-alpine
2025/06/25 21:18:37 🐳 Creating container for image testcontainers/ryuk:0.11.0
2025/06/25 21:18:37 ✅ Container created: 45b04620f982
2025/06/25 21:18:37 🐳 Starting container: 45b04620f982
2025/06/25 21:18:37 ✅ Container started: 45b04620f982
2025/06/25 21:18:37 ⏳ Waiting for container id 45b04620f982 image: testcontainers/ryuk:0.11.0. Waiting for: &{Port:8080/tcp timeout:<nil> PollInterval:100ms skipInternalCheck:false}
2025/06/25 21:18:37 🔔 Container is ready: 45b04620f982
2025/06/25 21:18:37 ✅ Container created: d9a5fad29d98
2025/06/25 21:18:37 🐳 Starting container: d9a5fad29d98
2025/06/25 21:18:37 ✅ Container started: d9a5fad29d98
2025/06/25 21:18:37 ⏳ Waiting for container id d9a5fad29d98 image: postgres:15-alpine. Waiting for: &{timeout:<nil> deadline:0x140001222d0 Strategies:[0x140001246c0]}
2025/06/25 21:18:39 🔔 Container is ready: d9a5fad29d98
2025/06/25 21:18:39 🐳 Stopping container: d9a5fad29d98
2025/06/25 21:18:39 ✅ Container stopped: d9a5fad29d98
2025/06/25 21:18:39 🐳 Terminating container: d9a5fad29d98
2025/06/25 21:18:39 🚫 Container terminated: d9a5fad29d98
--- PASS: TestInsertUser (2.51s)
PASS
ok      test       2.765s

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment