Created
June 25, 2025 16:20
-
-
Save AlexAkulov/12644f01ef36d5faade8b3cedd86fbe8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
Author
AlexAkulov
commented
Jun 25, 2025
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment