test(backend): add Kafka to the shared integration bootstrap
This commit is contained in:
1 parent
65d66b6f7d
commit
1aa7a9feaf
11 files changed
+485
-32
No files matched your search
@@ -121,7 +121,7 @@ jobs:
|
||||
cache-dependency-path: backend/go.sum
|
||||
- name: Install Go dependencies
|
||||
run: make -C backend deps
|
||||
- name: Run PostgreSQL, Redis, and SeaweedFS integration shard
|
||||
- name: Run PostgreSQL, Redis, SeaweedFS, and Kafka integration shard
|
||||
env:
|
||||
TEST_SHARD_INDEX: ${{ matrix.shard }}
|
||||
TEST_SHARD_TOTAL: "2"
|
||||
|
||||
+5
-2
@@ -20,6 +20,8 @@ require (
|
||||
github.com/redis/go-redis/v9 v9.22.0
|
||||
github.com/testcontainers/testcontainers-go v0.44.0
|
||||
github.com/testcontainers/testcontainers-go/modules/postgres v0.44.0
|
||||
github.com/twmb/franz-go v1.22.1
|
||||
github.com/twmb/franz-go/pkg/kadm v1.19.0
|
||||
github.com/wahrwelt-kit/go-cachekit v0.7.0
|
||||
github.com/wahrwelt-kit/go-httpkit v0.7.0
|
||||
github.com/wahrwelt-kit/go-logkit v0.6.0
|
||||
@@ -212,7 +214,7 @@ require (
|
||||
github.com/karamaru-alpha/copyloopvar v1.2.2 // indirect
|
||||
github.com/kisielk/errcheck v1.20.0 // indirect
|
||||
github.com/kkHAIKE/contextcheck v1.1.6 // indirect
|
||||
github.com/klauspost/compress v1.19.2 // indirect
|
||||
github.com/klauspost/compress v1.20.0 // indirect
|
||||
github.com/knadh/koanf/maps v0.1.2 // indirect
|
||||
github.com/knadh/koanf/parsers/yaml v1.1.0 // indirect
|
||||
github.com/knadh/koanf/providers/env v1.1.0 // indirect
|
||||
@@ -278,7 +280,7 @@ require (
|
||||
github.com/pb33f/ordered-map/v2 v2.3.1 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.4.3 // indirect
|
||||
github.com/pganalyze/pg_query_go/v6 v6.2.2 // indirect
|
||||
github.com/pierrec/lz4/v4 v4.1.29 // indirect
|
||||
github.com/pierrec/lz4/v4 v4.1.30 // indirect
|
||||
github.com/pingcap/errors v0.11.5-0.20250523034308-74f78ae071ee // indirect
|
||||
github.com/pingcap/failpoint v0.0.0-20240528011301-b51a646c7c86 // indirect
|
||||
github.com/pingcap/log v1.1.0 // indirect
|
||||
@@ -343,6 +345,7 @@ require (
|
||||
github.com/tomarrell/wrapcheck/v2 v2.12.0 // indirect
|
||||
github.com/tommy-muehle/go-mnd/v2 v2.5.1 // indirect
|
||||
github.com/tursodatabase/libsql-client-go v0.0.0-20260528064733-9d5d30a29a60 // indirect
|
||||
github.com/twmb/franz-go/pkg/kmsg v1.14.0 // indirect
|
||||
github.com/ultraware/funlen v0.2.0 // indirect
|
||||
github.com/ultraware/whitespace v0.2.0 // indirect
|
||||
github.com/uudashr/gocognit v1.2.1 // indirect
|
||||
|
||||
+10
-4
@@ -483,8 +483,8 @@ github.com/kisielk/errcheck v1.20.0 h1:9rwHBNKzd4wkDWcROy3DvFGNqEPlkxBg305rvk7Ha
|
||||
github.com/kisielk/errcheck v1.20.0/go.mod h1:O+f80MKNwX8Oor2jwgpeQ9An7uJm+hRSgT+h22knRJU=
|
||||
github.com/kkHAIKE/contextcheck v1.1.6 h1:7HIyRcnyzxL9Lz06NGhiKvenXq7Zw6Q0UQu/ttjfJCE=
|
||||
github.com/kkHAIKE/contextcheck v1.1.6/go.mod h1:3dDbMRNBFaq8HFXWC1JyvDSPm43CmE6IuHam8Wr0rkg=
|
||||
github.com/klauspost/compress v1.19.2 h1:hMRETovs/pu/dVWN7zIT1PGG8t509MwT6bO7XSi26R8=
|
||||
github.com/klauspost/compress v1.19.2/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
||||
github.com/klauspost/compress v1.20.0 h1:a3C1ke2ohxFymNlb2HWAHjDeKCI90scRskErZkR0ezA=
|
||||
github.com/klauspost/compress v1.20.0/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
|
||||
github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE=
|
||||
github.com/klauspost/cpuid/v2 v2.2.10/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
|
||||
github.com/knadh/koanf/maps v0.1.2 h1:RBfmAW5CnZT+PJ1CVc1QSJKf4Xu9kxfQgYVQSu8hpbo=
|
||||
@@ -643,8 +643,8 @@ github.com/pelletier/go-toml/v2 v2.4.3 h1:GTRvJQutkOSftxIFD5xw9aepkYNuPWmVJpffdD
|
||||
github.com/pelletier/go-toml/v2 v2.4.3/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
||||
github.com/pganalyze/pg_query_go/v6 v6.2.2 h1:O0L6zMC226R82RF3X5n0Ki6HjytDsoAzuzp4ATVAHNo=
|
||||
github.com/pganalyze/pg_query_go/v6 v6.2.2/go.mod h1:Cn6+j4870kJz3iYNsb0VsNG04vpSWgEvBwc590J4qD0=
|
||||
github.com/pierrec/lz4/v4 v4.1.29 h1:CDQY6qZOLI4DW0Nx6R1vRrifrCeQHnNXkMb0hZWXFjg=
|
||||
github.com/pierrec/lz4/v4 v4.1.29/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4=
|
||||
github.com/pierrec/lz4/v4 v4.1.30 h1:cchX8N2DVP668WkElI9QMwVyoNabLkq1LofDHFeIrdg=
|
||||
github.com/pierrec/lz4/v4 v4.1.30/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4=
|
||||
github.com/pingcap/errors v0.11.0/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8=
|
||||
github.com/pingcap/errors v0.11.5-0.20250523034308-74f78ae071ee h1:/IDPbpzkzA97t1/Z1+C3KlxbevjMeaI6BQYxvivu4u8=
|
||||
github.com/pingcap/errors v0.11.5-0.20250523034308-74f78ae071ee/go.mod h1:X2r9ueLEUZgtx2cIogM0v4Zj5uvvzhuuiu7Pn8HzMPg=
|
||||
@@ -807,6 +807,12 @@ github.com/tommy-muehle/go-mnd/v2 v2.5.1 h1:NowYhSdyE/1zwK9QCLeRb6USWdoif80Ie+v+
|
||||
github.com/tommy-muehle/go-mnd/v2 v2.5.1/go.mod h1:WsUAkMJMYww6l/ufffCD3m+P7LEvr8TnZn9lwVDlgzw=
|
||||
github.com/tursodatabase/libsql-client-go v0.0.0-20260528064733-9d5d30a29a60 h1:TfQEwhr0Q9t+Bgs0TNk2eHZ9EGD107Mimic0kcoGS1M=
|
||||
github.com/tursodatabase/libsql-client-go v0.0.0-20260528064733-9d5d30a29a60/go.mod h1:08inkKyguB6CGGssc/JzhmQWwBgFQBgjlYFjxjRh7nU=
|
||||
github.com/twmb/franz-go v1.22.1 h1:J7Xixbb7k0Itl39eaBot5PIblZh9IL3ZKYgo2yzlf40=
|
||||
github.com/twmb/franz-go v1.22.1/go.mod h1:b2qISbZgMTJRcIsltVqPz4+Bb2Lw/9bN+/Gd0C07kYw=
|
||||
github.com/twmb/franz-go/pkg/kadm v1.19.0 h1:5Nx/WWFkpNUi8Z55Skxvn9x5HOCjw+BUntSNB1kLglk=
|
||||
github.com/twmb/franz-go/pkg/kadm v1.19.0/go.mod h1:emmsx5J7YPU9A7UHcSoz0fBMYVmCcJO2etylJeU0VHU=
|
||||
github.com/twmb/franz-go/pkg/kmsg v1.14.0 h1:gSxrBEKWl3qnsx3QKWol5OEVujuPmIoDkhMt3didFKM=
|
||||
github.com/twmb/franz-go/pkg/kmsg v1.14.0/go.mod h1:+DPt4NC8RmI6hqb8G09+3giKObE6uD2Eya6CfqBpeJY=
|
||||
github.com/ultraware/funlen v0.2.0 h1:gCHmCn+d2/1SemTdYMiKLAHFYxTYz7z9VIDRaTGyLkI=
|
||||
github.com/ultraware/funlen v0.2.0/go.mod h1:ZE0q4TsJ8T1SQcjmkhN/w+MceuatI6pBFSxxyteHIJA=
|
||||
github.com/ultraware/whitespace v0.2.0 h1:TYowo2m9Nfj1baEQBjuHzvMRbp19i+RCcRYrSWoFa+g=
|
||||
|
||||
@@ -5,6 +5,8 @@ package integration_test
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -13,6 +15,8 @@ import (
|
||||
"github.com/testcontainers/testcontainers-go"
|
||||
"github.com/testcontainers/testcontainers-go/modules/postgres"
|
||||
"github.com/testcontainers/testcontainers-go/wait"
|
||||
"github.com/twmb/franz-go/pkg/kadm"
|
||||
"github.com/twmb/franz-go/pkg/kgo"
|
||||
|
||||
"lincodex/backend/config"
|
||||
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
|
||||
@@ -25,6 +29,8 @@ const (
|
||||
postgresImage = "postgres:alpine"
|
||||
redisImage = "redis:alpine"
|
||||
seaweedfsImage = "chrislusf/seaweedfs:latest"
|
||||
// The same image and KRaft settings as deploy/docker/docker-compose.yml.
|
||||
kafkaImage = "apache/kafka:latest"
|
||||
|
||||
postgresDatabase = "health"
|
||||
postgresUser = "health"
|
||||
@@ -44,6 +50,16 @@ const (
|
||||
readinessTimeout = 5 * time.Second
|
||||
redisTimeout = 300 * time.Millisecond
|
||||
storageTimeout = 2 * time.Second
|
||||
kafkaStartupTimeout = time.Minute
|
||||
kafkaReadyTimeout = 30 * time.Second
|
||||
|
||||
kafkaClientPort = "9092/tcp"
|
||||
// kafkaListenersFile is written by a post-start hook once the host port is
|
||||
// mapped; the container entrypoint waits for it before launching the broker.
|
||||
kafkaListenersFile = "/tmp/advertised-listeners"
|
||||
// kafkaBrokerListener carries inter-broker traffic on container loopback.
|
||||
kafkaBrokerListener = "BROKER://127.0.0.1:19092"
|
||||
kafkaClusterIDSize = 16
|
||||
)
|
||||
|
||||
type service uint8
|
||||
@@ -52,29 +68,37 @@ const (
|
||||
postgresService service = iota
|
||||
redisService
|
||||
seaweedfsService
|
||||
kafkaService
|
||||
)
|
||||
|
||||
// defaultServices form the full readiness environment. Kafka is not part of
|
||||
// readiness, so it starts only for tests that select kafkaService.
|
||||
var defaultServices = []service{postgresService, redisService, seaweedfsService}
|
||||
|
||||
type testEnvironment struct {
|
||||
Config config.Config
|
||||
Postgres *postgresadapter.HealthChecker
|
||||
Redis *redisadapter.Cache
|
||||
SeaweedFS *seaweedfs.Storage
|
||||
// KafkaAdmin creates and deletes test topics; see kafka_helpers_test.go.
|
||||
KafkaAdmin *kadm.Client
|
||||
|
||||
owner *testing.T
|
||||
redisContainer testcontainers.Container
|
||||
seaweedfsContainer testcontainers.Container
|
||||
seaweedfsVolume string
|
||||
kafkaContainer testcontainers.Container
|
||||
}
|
||||
|
||||
// bootstrap creates an isolated environment owned by t. Child tests may reuse it.
|
||||
func bootstrap(t *testing.T, services ...service) *testEnvironment {
|
||||
t.Helper()
|
||||
if len(services) == 0 {
|
||||
services = []service{postgresService, redisService, seaweedfsService}
|
||||
services = defaultServices
|
||||
}
|
||||
for _, selected := range services {
|
||||
switch selected {
|
||||
case postgresService, redisService, seaweedfsService:
|
||||
case postgresService, redisService, seaweedfsService, kafkaService:
|
||||
default:
|
||||
t.Fatalf("unknown integration service: %d", selected)
|
||||
}
|
||||
@@ -114,6 +138,8 @@ func bootstrap(t *testing.T, services ...service) *testEnvironment {
|
||||
case seaweedfsService:
|
||||
env.prepareStorageVolume()
|
||||
env.startSeaweedFS(ctx, t)
|
||||
case kafkaService:
|
||||
env.startKafka(ctx, t)
|
||||
}
|
||||
started[selected] = true
|
||||
}
|
||||
@@ -281,6 +307,123 @@ func (env *testEnvironment) recreateSeaweedFS(ctx context.Context, t *testing.T)
|
||||
env.startSeaweedFS(ctx, t)
|
||||
}
|
||||
|
||||
func (env *testEnvironment) startKafka(ctx context.Context, t *testing.T) {
|
||||
t.Helper()
|
||||
clusterID := make([]byte, kafkaClusterIDSize)
|
||||
if _, err := rand.Read(clusterID); err != nil {
|
||||
t.Fatalf("generate Kafka cluster ID: %v", err)
|
||||
}
|
||||
container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
|
||||
ContainerRequest: testcontainers.ContainerRequest{
|
||||
Image: kafkaImage,
|
||||
ExposedPorts: []string{kafkaClientPort},
|
||||
Env: kafkaEnvironment(base64.RawURLEncoding.EncodeToString(clusterID)),
|
||||
// The advertised client address contains the host port, which is
|
||||
// known only after the container starts.
|
||||
Entrypoint: []string{"sh", "-c", "while [ ! -s " + kafkaListenersFile + " ]; do sleep 0.1; done; " +
|
||||
"KAFKA_ADVERTISED_LISTENERS=\"$(cat " + kafkaListenersFile + ")\" exec /__cacert_entrypoint.sh /etc/kafka/docker/run"},
|
||||
// The image declares these paths as volumes. Compose keeps data in a
|
||||
// named volume; a test broker needs no persistence, so tmpfs for all
|
||||
// three leaves no anonymous volumes behind.
|
||||
Tmpfs: map[string]string{
|
||||
"/var/lib/kafka/data": "rw,size=256m,mode=1777",
|
||||
"/etc/kafka/secrets": "rw,size=1m,mode=0755",
|
||||
"/mnt/shared/config": "rw,size=1m,mode=0755",
|
||||
},
|
||||
LifecycleHooks: []testcontainers.ContainerLifecycleHooks{{
|
||||
PostStarts: []testcontainers.ContainerHook{advertiseKafkaListeners},
|
||||
}},
|
||||
WaitingFor: wait.ForLog("Kafka Server started").WithStartupTimeout(kafkaStartupTimeout),
|
||||
},
|
||||
Started: true,
|
||||
})
|
||||
env.cleanupContainer(ctx, container, "Kafka")
|
||||
if err != nil {
|
||||
t.Fatalf("start Kafka container: %v", err)
|
||||
}
|
||||
env.kafkaContainer = container
|
||||
address, err := container.PortEndpoint(ctx, kafkaClientPort, "")
|
||||
if err != nil {
|
||||
t.Fatalf("get Kafka address: %v", err)
|
||||
}
|
||||
env.Config.KafkaBrokers = []string{address}
|
||||
if err := env.Config.ValidateKafka(); err != nil {
|
||||
t.Fatalf("invalid Kafka test configuration: %v", err)
|
||||
}
|
||||
// kadm serves topic metadata from a cache for up to MetadataMinAge (5s by
|
||||
// default); assertions about created or deleted topics need current state.
|
||||
env.KafkaAdmin = kadm.NewClient(env.newKafkaClient(env.owner, kgo.MetadataMinAge(readinessInterval)))
|
||||
waitForKafka(ctx, t, env.KafkaAdmin)
|
||||
}
|
||||
|
||||
// kafkaEnvironment mirrors the Compose broker: one KRaft broker and controller,
|
||||
// explicit topic creation, single replicas, and a bounded heap.
|
||||
func kafkaEnvironment(clusterID string) map[string]string {
|
||||
return map[string]string{
|
||||
"CLUSTER_ID": clusterID,
|
||||
"KAFKA_NODE_ID": "1",
|
||||
"KAFKA_PROCESS_ROLES": "broker,controller",
|
||||
// Clients reach PLAINTEXT through the mapped host port, which does not
|
||||
// resolve inside the container. Inter-broker traffic therefore uses a
|
||||
// loopback listener, like the controller.
|
||||
"KAFKA_LISTENERS": "PLAINTEXT://0.0.0.0:9092," + kafkaBrokerListener + ",CONTROLLER://127.0.0.1:9093",
|
||||
"KAFKA_LISTENER_SECURITY_PROTOCOL_MAP": "PLAINTEXT:PLAINTEXT,BROKER:PLAINTEXT,CONTROLLER:PLAINTEXT",
|
||||
"KAFKA_CONTROLLER_LISTENER_NAMES": "CONTROLLER",
|
||||
"KAFKA_INTER_BROKER_LISTENER_NAME": "BROKER",
|
||||
"KAFKA_CONTROLLER_QUORUM_VOTERS": "1@127.0.0.1:9093",
|
||||
"KAFKA_LOG_DIRS": "/var/lib/kafka/data",
|
||||
"KAFKA_AUTO_CREATE_TOPICS_ENABLE": "false",
|
||||
"KAFKA_NUM_PARTITIONS": "1",
|
||||
"KAFKA_DEFAULT_REPLICATION_FACTOR": "1",
|
||||
"KAFKA_MIN_INSYNC_REPLICAS": "1",
|
||||
"KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR": "1",
|
||||
"KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR": "1",
|
||||
"KAFKA_TRANSACTION_STATE_LOG_MIN_ISR": "1",
|
||||
"KAFKA_SHARE_COORDINATOR_STATE_TOPIC_REPLICATION_FACTOR": "1",
|
||||
"KAFKA_SHARE_COORDINATOR_STATE_TOPIC_MIN_ISR": "1",
|
||||
"KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS": "0",
|
||||
"KAFKA_HEAP_OPTS": "-Xms256m -Xmx512m",
|
||||
// A non-empty value keeps the image from opening a JMX port.
|
||||
"KAFKA_JMX_OPTS": "-Djava.rmi.server.hostname=127.0.0.1",
|
||||
}
|
||||
}
|
||||
|
||||
func advertiseKafkaListeners(ctx context.Context, container testcontainers.Container) error {
|
||||
if err := wait.ForMappedPort(kafkaClientPort).WaitUntilReady(ctx, container); err != nil {
|
||||
return fmt.Errorf("integration_test.advertiseKafkaListeners - wait for mapped port: %w", err)
|
||||
}
|
||||
address, err := container.PortEndpoint(ctx, kafkaClientPort, "")
|
||||
if err != nil {
|
||||
return fmt.Errorf("integration_test.advertiseKafkaListeners - get client address: %w", err)
|
||||
}
|
||||
listeners := "PLAINTEXT://" + address + "," + kafkaBrokerListener
|
||||
if err := container.CopyToContainer(ctx, []byte(listeners), kafkaListenersFile, 0o644); err != nil {
|
||||
return fmt.Errorf("integration_test.advertiseKafkaListeners - write listeners: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func waitForKafka(ctx context.Context, t *testing.T, admin *kadm.Client) {
|
||||
t.Helper()
|
||||
// The startup log line does not prove that the advertised listener is
|
||||
// reachable from the host through the mapped port.
|
||||
ctx, cancel := context.WithTimeout(ctx, kafkaReadyTimeout)
|
||||
defer cancel()
|
||||
ticker := time.NewTicker(readinessInterval)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
brokers, err := admin.ListBrokers(ctx)
|
||||
if err == nil && len(brokers) > 0 {
|
||||
return
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
t.Fatalf("wait for Kafka broker metadata: brokers %v, error %v", brokers, err)
|
||||
case <-ticker.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func waitForStorage(ctx context.Context, t *testing.T, storage *seaweedfs.Storage) {
|
||||
t.Helper()
|
||||
// The S3 listener starts before mini finishes provisioning configured buckets.
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
//go:build integration
|
||||
|
||||
package integration_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/twmb/franz-go/pkg/kadm"
|
||||
"github.com/twmb/franz-go/pkg/kerr"
|
||||
"github.com/twmb/franz-go/pkg/kgo"
|
||||
)
|
||||
|
||||
const (
|
||||
kafkaTopicPrefix = "integration-"
|
||||
kafkaReplicationFactor = 1
|
||||
kafkaOperationTimeout = 15 * time.Second
|
||||
)
|
||||
|
||||
// newKafkaClient returns a client for the test broker that closes when t
|
||||
// finishes. Options add producer or consumer settings to the seed brokers.
|
||||
func (env *testEnvironment) newKafkaClient(t *testing.T, options ...kgo.Opt) *kgo.Client {
|
||||
t.Helper()
|
||||
if env.kafkaContainer == nil {
|
||||
t.Fatal("Kafka was not selected in bootstrap")
|
||||
}
|
||||
options = append([]kgo.Opt{kgo.SeedBrokers(env.Config.KafkaBrokers...)}, options...)
|
||||
client, err := kgo.NewClient(options...)
|
||||
if err != nil {
|
||||
t.Fatalf("create Kafka client: %v", err)
|
||||
}
|
||||
t.Cleanup(client.Close)
|
||||
return client
|
||||
}
|
||||
|
||||
// newKafkaTopicName returns a name that no other test or shard uses.
|
||||
func newKafkaTopicName() string {
|
||||
return kafkaTopicPrefix + strings.ToLower(rand.Text())
|
||||
}
|
||||
|
||||
// createKafkaTopic creates a uniquely named topic and deletes it when t
|
||||
// finishes, including after a failure. The broker never creates topics on
|
||||
// demand, so tests create every topic they use.
|
||||
func (env *testEnvironment) createKafkaTopic(ctx context.Context, t *testing.T, partitions int32) string {
|
||||
t.Helper()
|
||||
topic := newKafkaTopicName()
|
||||
// Register deletion first: a request that times out may still create it.
|
||||
// The test context is already canceled when cleanup runs.
|
||||
cleanupCtx := context.WithoutCancel(ctx)
|
||||
t.Cleanup(func() { env.deleteKafkaTopic(cleanupCtx, t, topic) })
|
||||
ctx, cancel := context.WithTimeout(ctx, kafkaOperationTimeout)
|
||||
defer cancel()
|
||||
responses, err := env.KafkaAdmin.CreateTopics(ctx, partitions, kafkaReplicationFactor, nil, topic)
|
||||
if err == nil {
|
||||
var response kadm.CreateTopicResponse
|
||||
response, err = responses.On(topic, nil)
|
||||
if err == nil {
|
||||
err = response.Err
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("create Kafka topic %s: %v", topic, err)
|
||||
}
|
||||
return topic
|
||||
}
|
||||
|
||||
func (env *testEnvironment) deleteKafkaTopic(ctx context.Context, t *testing.T, topic string) {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithTimeout(ctx, cleanupTimeout)
|
||||
defer cancel()
|
||||
responses, err := env.KafkaAdmin.DeleteTopics(ctx, topic)
|
||||
if err == nil {
|
||||
var response kadm.DeleteTopicResponse
|
||||
response, err = responses.On(topic, nil)
|
||||
if err == nil {
|
||||
err = response.Err
|
||||
}
|
||||
}
|
||||
// A failed creation leaves nothing to delete.
|
||||
if err != nil && !errors.Is(err, kerr.UnknownTopicOrPartition) {
|
||||
t.Errorf("delete Kafka topic %s: %v", topic, err)
|
||||
}
|
||||
}
|
||||
|
||||
func produceKafkaRecords(ctx context.Context, t *testing.T, client *kgo.Client, records ...*kgo.Record) {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithTimeout(ctx, kafkaOperationTimeout)
|
||||
defer cancel()
|
||||
if err := client.ProduceSync(ctx, records...).FirstErr(); err != nil {
|
||||
t.Fatalf("produce %d Kafka records: %v", len(records), err)
|
||||
}
|
||||
}
|
||||
|
||||
// consumeKafkaRecords reads count records from the start of every partition of
|
||||
// topic without a consumer group, so no group offsets outlive the test.
|
||||
func (env *testEnvironment) consumeKafkaRecords(ctx context.Context, t *testing.T, topic string, count int) []*kgo.Record {
|
||||
t.Helper()
|
||||
consumer := env.newKafkaClient(t,
|
||||
kgo.ConsumeTopics(topic),
|
||||
kgo.ConsumeResetOffset(kgo.NewOffset().AtStart()),
|
||||
)
|
||||
ctx, cancel := context.WithTimeout(ctx, kafkaOperationTimeout)
|
||||
defer cancel()
|
||||
records := make([]*kgo.Record, 0, count)
|
||||
for len(records) < count {
|
||||
fetches := consumer.PollFetches(ctx)
|
||||
if err := ctx.Err(); err != nil {
|
||||
t.Fatalf("consume Kafka topic %s: received %d of %d records: %v", topic, len(records), count, err)
|
||||
}
|
||||
if err := fetches.Err(); err != nil {
|
||||
t.Fatalf("consume Kafka topic %s: %v", topic, err)
|
||||
}
|
||||
records = append(records, fetches.Records()...)
|
||||
}
|
||||
return records
|
||||
}
|
||||
|
||||
// kafkaTopicExists reports whether the broker metadata contains topic.
|
||||
func kafkaTopicExists(ctx context.Context, t *testing.T, admin *kadm.Client, topic string) bool {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithTimeout(ctx, kafkaOperationTimeout)
|
||||
defer cancel()
|
||||
topics, err := admin.ListTopics(ctx, topic)
|
||||
if err != nil {
|
||||
t.Fatalf("list Kafka topic %s: %v", topic, err)
|
||||
}
|
||||
if detail, ok := topics[topic]; ok && detail.Err != nil && !errors.Is(detail.Err, kerr.UnknownTopicOrPartition) {
|
||||
t.Fatalf("load Kafka topic %s: %v", topic, detail.Err)
|
||||
}
|
||||
return topics.Has(topic)
|
||||
}
|
||||
|
||||
// waitForKafkaTopicDeletion allows for the short delay before a deletion
|
||||
// accepted by the controller reaches broker metadata.
|
||||
func waitForKafkaTopicDeletion(ctx context.Context, t *testing.T, admin *kadm.Client, topic string) {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithTimeout(ctx, kafkaOperationTimeout)
|
||||
defer cancel()
|
||||
ticker := time.NewTicker(readinessInterval)
|
||||
defer ticker.Stop()
|
||||
for kafkaTopicExists(ctx, t, admin, topic) {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
t.Fatalf("Kafka topic %s still exists after cleanup", topic)
|
||||
case <-ticker.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
//go:build integration
|
||||
|
||||
package integration_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"slices"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"github.com/twmb/franz-go/pkg/kerr"
|
||||
"github.com/twmb/franz-go/pkg/kgo"
|
||||
)
|
||||
|
||||
const (
|
||||
kafkaOrderingPartitions = 3
|
||||
kafkaRecordsPerKey = 5
|
||||
kafkaRecordType = "integration.technical-check"
|
||||
)
|
||||
|
||||
// TestKafkaAgainstContainer checks the test harness and broker settings with
|
||||
// technical records. It does not exercise an outbox relay or product events.
|
||||
func TestKafkaAgainstContainer(t *testing.T) {
|
||||
env := bootstrap(t, kafkaService)
|
||||
ctx := t.Context()
|
||||
|
||||
t.Run("keyed records keep headers and partition order", func(t *testing.T) {
|
||||
topic := env.createKafkaTopic(ctx, t, kafkaOrderingPartitions)
|
||||
producer := env.newKafkaClient(t)
|
||||
keys := []string{"aggregate-a", "aggregate-b", "aggregate-c"}
|
||||
sent := make([]*kgo.Record, 0, len(keys)*kafkaRecordsPerKey)
|
||||
for sequence := range kafkaRecordsPerKey {
|
||||
for _, key := range keys {
|
||||
sent = append(sent, technicalRecord(topic, key, sequence))
|
||||
}
|
||||
}
|
||||
produceKafkaRecords(ctx, t, producer, sent...)
|
||||
|
||||
received := env.consumeKafkaRecords(ctx, t, topic, len(sent))
|
||||
if len(received) != len(sent) {
|
||||
t.Fatalf("received %d records, want %d", len(received), len(sent))
|
||||
}
|
||||
byKey := make(map[string][]*kgo.Record, len(keys))
|
||||
for _, record := range received {
|
||||
byKey[string(record.Key)] = append(byKey[string(record.Key)], record)
|
||||
}
|
||||
for _, key := range keys {
|
||||
assertKeyedSequence(t, key, byKey[key])
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("missing topic is not created on demand", func(t *testing.T) {
|
||||
topic := newKafkaTopicName()
|
||||
// The client asks the broker to create unknown topics; the broker
|
||||
// setting must refuse, so a missing topic surfaces as an error.
|
||||
producer := env.newKafkaClient(t,
|
||||
kgo.AllowAutoTopicCreation(),
|
||||
kgo.MetadataMinAge(readinessInterval),
|
||||
)
|
||||
produceCtx, cancel := context.WithTimeout(ctx, kafkaOperationTimeout)
|
||||
defer cancel()
|
||||
err := producer.ProduceSync(produceCtx, technicalRecord(topic, "aggregate-a", 0)).FirstErr()
|
||||
if !errors.Is(err, kerr.UnknownTopicOrPartition) {
|
||||
t.Fatalf("produce to missing topic: %v, want %v", err, kerr.UnknownTopicOrPartition)
|
||||
}
|
||||
if kafkaTopicExists(ctx, t, env.KafkaAdmin, topic) {
|
||||
t.Fatalf("broker created missing topic %s", topic)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("topic cleanup runs when the test finishes", func(t *testing.T) {
|
||||
var topic string
|
||||
t.Run("owner", func(t *testing.T) {
|
||||
topic = env.createKafkaTopic(ctx, t, 1)
|
||||
produceKafkaRecords(ctx, t, env.newKafkaClient(t), technicalRecord(topic, "aggregate-a", 0))
|
||||
if !kafkaTopicExists(ctx, t, env.KafkaAdmin, topic) {
|
||||
t.Fatalf("created topic %s is missing", topic)
|
||||
}
|
||||
})
|
||||
if topic == "" {
|
||||
t.Fatal("owner test did not create a topic")
|
||||
}
|
||||
waitForKafkaTopicDeletion(ctx, t, env.KafkaAdmin, topic)
|
||||
})
|
||||
}
|
||||
|
||||
func technicalRecord(topic, key string, sequence int) *kgo.Record {
|
||||
return &kgo.Record{
|
||||
Topic: topic,
|
||||
Key: []byte(key),
|
||||
Value: []byte(`{"sequence":` + strconv.Itoa(sequence) + `}`),
|
||||
Headers: []kgo.RecordHeader{
|
||||
{Key: "event-type", Value: []byte(kafkaRecordType)},
|
||||
{Key: "sequence", Value: []byte(strconv.Itoa(sequence))},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// assertKeyedSequence checks that records with one key share a partition and
|
||||
// arrive in production order with their payload and headers intact.
|
||||
func assertKeyedSequence(t *testing.T, key string, records []*kgo.Record) {
|
||||
t.Helper()
|
||||
if len(records) != kafkaRecordsPerKey {
|
||||
t.Fatalf("key %s: received %d records, want %d", key, len(records), kafkaRecordsPerKey)
|
||||
}
|
||||
for sequence, record := range records {
|
||||
want := technicalRecord(record.Topic, key, sequence)
|
||||
if record.Partition != records[0].Partition {
|
||||
t.Errorf("key %s: record %d in partition %d, first in %d", key, sequence, record.Partition, records[0].Partition)
|
||||
}
|
||||
if sequence > 0 && record.Offset <= records[sequence-1].Offset {
|
||||
t.Errorf("key %s: offset %d does not follow %d", key, record.Offset, records[sequence-1].Offset)
|
||||
}
|
||||
if string(record.Value) != string(want.Value) {
|
||||
t.Errorf("key %s: record %d value %q, want %q", key, sequence, record.Value, want.Value)
|
||||
}
|
||||
if !slices.EqualFunc(record.Headers, want.Headers, func(got, want kgo.RecordHeader) bool {
|
||||
return got.Key == want.Key && string(got.Value) == string(want.Value)
|
||||
}) {
|
||||
t.Errorf("key %s: record %d headers %v, want %v", key, sequence, record.Headers, want.Headers)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -83,16 +83,31 @@ class IntegrationSuiteTests(unittest.TestCase):
|
||||
self.assertIn("-count=1", args)
|
||||
return selected
|
||||
|
||||
def test_shards_are_disjoint_and_cover_every_package(self):
|
||||
selected = []
|
||||
for index in (1, 2, 3):
|
||||
result, calls = self.run_suite({"TEST_SHARD_INDEX": str(index), "TEST_SHARD_TOTAL": "3"})
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
shard = self.selected(calls)
|
||||
self.assertTrue(shard)
|
||||
selected.extend(shard)
|
||||
def listed(self, stdout):
|
||||
listed = []
|
||||
for line in stdout.splitlines():
|
||||
if line.startswith(" "):
|
||||
package, _, name = line.strip().partition(": ")
|
||||
listed.append((package, name))
|
||||
return listed
|
||||
|
||||
def test_shards_partition_every_package_and_match_their_listing(self):
|
||||
expected = [(package, name) for package, names in FIXTURE.items() for name in names]
|
||||
self.assertCountEqual(selected, expected)
|
||||
for total in range(1, len(expected) + 1):
|
||||
with self.subTest(total=total):
|
||||
selected = []
|
||||
for index in range(1, total + 1):
|
||||
settings = {"TEST_SHARD_INDEX": str(index), "TEST_SHARD_TOTAL": str(total)}
|
||||
result, calls = self.run_suite(settings)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
shard = self.selected(calls)
|
||||
self.assertTrue(shard)
|
||||
listing, _ = self.run_suite(settings, list_only=True)
|
||||
self.assertEqual(listing.returncode, 0, listing.stderr)
|
||||
self.assertCountEqual(self.listed(listing.stdout), shard)
|
||||
selected.extend(shard)
|
||||
# Equal multisets: every test runs in exactly one shard.
|
||||
self.assertCountEqual(selected, expected)
|
||||
|
||||
def test_default_runs_full_suite(self):
|
||||
result, calls = self.run_suite()
|
||||
|
||||
@@ -44,6 +44,7 @@ The repository contains a verifiable technical scaffold, not a product. Values b
|
||||
| chi | v5.3.2 | backend/go.mod |
|
||||
| pgx | v5.11.0 | backend/go.mod |
|
||||
| testcontainers-go | v0.44.0, including modules/postgres | backend/go.mod |
|
||||
| franz-go (`kgo`, `kadm`) | v1.22.1, kadm v1.19.0; integration tests only | backend/go.mod |
|
||||
|
||||
What exists now:
|
||||
|
||||
@@ -52,11 +53,11 @@ What exists now:
|
||||
- Mail: the outbound `MailSender` port, the `disabled` transport, and the `EMAIL_PROVIDER` selection in bootstrap. Only `disabled` works in this build; `resend` and `smtp` fail startup after their settings are validated. Nothing sends mail yet. See [DEPLOY.md](DEPLOY.md#mail) and [ARCHITECTURE.md](ARCHITECTURE.md#mail-transport).
|
||||
- OpenAPI contracts api/core/ and api/ml/ with schema merge, bundles, lint, and generation for Go (ogen), TypeScript (Orval), and Python (datamodel-code-generator). The SPA has an interface scaffold with placeholder screens, a generated API client, and MSW handlers.
|
||||
- Compose projects: core (`deploy/docker/docker-compose.yml`: PostgreSQL, Redis, SeaweedFS, Kafka, backend, frontend), ML (`docker-compose.ml.yml`), and monitoring (`docker-compose.monitoring.yml`).
|
||||
- Kafka: one KRaft node in the core Compose project with an internal-only listener, a named volume, a health check, and a memory limit. backend/config parses and validates `KAFKA_BROKERS`, but the backend has no Go Kafka client, topics, or readiness check for Kafka.
|
||||
- Kafka: one KRaft node in the core Compose project with an internal-only listener, a named volume, a health check, and a memory limit. backend/config parses and validates `KAFKA_BROKERS`, but the application has no Kafka client, topics, or readiness check for Kafka. The franz-go client is used only by the integration test helpers; see [TESTING.md](TESTING.md#integration-test-bootstrap).
|
||||
- CI jobs in .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix of two shards), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke`, and the required `aggregate` result. See [TESTING.md](TESTING.md) for sharding.
|
||||
- Observability: Prometheus, Loki, Alloy, Grafana with provisioned datasources and dashboards, and PostgreSQL, Redis, and node exporters. The React app does not send telemetry yet.
|
||||
|
||||
Not implemented yet: registration and login (their contract is declared; the operations answer 501 or 401), consents, profiles, the questionnaire and assessment, the company cabinet, needs and matching, invitations and contacts, the Resend and SMTP transports and mail delivery, the Go Kafka client, the outbox relay, notifications, support, and an end-to-end business suite. backend/db/migrations/ contains the outbox table, the identity storage tables (`users`, `email_tokens`, `sessions`), and the `policy_versions` table and no other business schema; no product rule reads the policy yet; registration, verification, and session behavior on top of that storage comes in later tasks, product usecase and adapter directories other than the password hashing and policy pieces contain only placeholders, and `make -C deploy test-e2e` runs only a technical Playwright smoke of the SPA, API health, and error routes on a throwaway stack, not a business flow (see [TESTING.md](TESTING.md#browser-e2e-suite)). The target design is in [ARCHITECTURE.md](ARCHITECTURE.md).
|
||||
Not implemented yet: registration and login (their contract is declared; the operations answer 501 or 401), consents, profiles, the questionnaire and assessment, the company cabinet, needs and matching, invitations and contacts, the Resend and SMTP transports and mail delivery, a Kafka client in the application, the outbox relay, notifications, support, and an end-to-end business suite. backend/db/migrations/ contains the outbox table, the identity storage tables (`users`, `email_tokens`, `sessions`), and the `policy_versions` table and no other business schema; no product rule reads the policy yet; registration, verification, and session behavior on top of that storage comes in later tasks, product usecase and adapter directories other than the password hashing and policy pieces contain only placeholders, and `make -C deploy test-e2e` runs only a technical Playwright smoke of the SPA, API health, and error routes on a throwaway stack, not a business flow (see [TESTING.md](TESTING.md#browser-e2e-suite)). The target design is in [ARCHITECTURE.md](ARCHITECTURE.md).
|
||||
|
||||
## Install and work loop
|
||||
|
||||
|
||||
+9
-5
@@ -20,7 +20,7 @@ Useful focused commands:
|
||||
| make -C api check | Schema merge, bundles, OpenAPI lint, merge-script tests |
|
||||
| make -C backend test | Go unit suite with race detector |
|
||||
| make -C backend test-fast | Faster Go tests without race instrumentation |
|
||||
| make -C backend test-int | Go integration tests with Testcontainers/PostgreSQL/Redis/SeaweedFS |
|
||||
| make -C backend test-int | Go integration tests with Testcontainers/PostgreSQL/Redis/SeaweedFS/Kafka |
|
||||
| make -C frontend check | Prettier, ESLint, Stylelint, TypeScript, Vitest, FSD boundaries, build |
|
||||
| make -C ml check | Ruff, mypy, pytest, and wheel build |
|
||||
| make -C ml check-generated | Pydantic models match the ML bundle without rewriting files |
|
||||
@@ -37,7 +37,7 @@ Security checks run separately: `make -C security check` scans source/dependenci
|
||||
|
||||
## Current scaffold coverage
|
||||
|
||||
Existing checks cover health/readiness, backend PostgreSQL, Redis, and SeaweedFS connectivity, migration up, down to zero, and up again on an isolated database, concurrent migration runners that apply each migration once, the transactional outbox (atomic commit, rollback on error, panic, and context cancellation, nested-transaction rejection, an observed row-lock wait between concurrent transactions, edge payloads, and constraints), identity storage (a unique normalized email, hash-only storage of email and session tokens, exactly one successful consumption of a token under parallel confirmations and an observed lock wait between two consumes, rejection of expired, invalidated, and superseded tokens, including a re-registration that commits during a confirmation, session idle, absolute, and revocation limits and touch throttling, batch cleanup of unverified accounts that skips locked accounts without waiting, a deadlock reported as a retryable conflict, cascade deletes, rollback with the surrounding transaction, and constraints), cache operations and TTL, S3 operations and object persistence, metrics, the API client, ML schemas, and current endpoint availability. There are no registration, login, assessment, search, invitation, or file workflows and no real model inference to validate as product behavior.
|
||||
Existing checks cover health/readiness, backend PostgreSQL, Redis, and SeaweedFS connectivity, migration up, down to zero, and up again on an isolated database, concurrent migration runners that apply each migration once, the transactional outbox (atomic commit, rollback on error, panic, and context cancellation, nested-transaction rejection, an observed row-lock wait between concurrent transactions, edge payloads, and constraints), identity storage (a unique normalized email, hash-only storage of email and session tokens, exactly one successful consumption of a token under parallel confirmations and an observed lock wait between two consumes, rejection of expired, invalidated, and superseded tokens, including a re-registration that commits during a confirmation, session idle, absolute, and revocation limits and touch throttling, batch cleanup of unverified accounts that skips locked accounts without waiting, a deadlock reported as a retryable conflict, cascade deletes, rollback with the surrounding transaction, and constraints), cache operations and TTL, S3 operations and object persistence, the Kafka test harness (keyed records with headers and per-partition order, refusal to create a missing topic on demand, and topic cleanup), metrics, the API client, ML schemas, and current endpoint availability. There are no registration, login, assessment, search, invitation, or file workflows, no outbox relay or product events in Kafka, and no real model inference to validate as product behavior.
|
||||
|
||||
API verification checks the OpenAPI subset exercised by pinned tools, fixtures, and contracts that actually ran. Its result applies only to those inputs. CI YAML in the repository does not mean a workflow has run on GitHub.
|
||||
|
||||
@@ -63,10 +63,14 @@ The suite does not cover candidate or employer workflows, sign-in, mail delivery
|
||||
|
||||
The shared helper lives in `backend/integration_test/bootstrap_test.go`. Calling `env := bootstrap(t)` starts PostgreSQL, Redis, and SeaweedFS, waits for adapter readiness, and returns an environment with configuration and clients. To test one adapter, use `bootstrap(t, postgresService)`, `bootstrap(t, redisService)`, or `bootstrap(t, seaweedfsService)`. Multiple services can be selected.
|
||||
|
||||
Call bootstrap once in the parent test and share its environment with its subtests. Each call creates separate containers with dynamic ports and a separate SeaweedFS volume when needed. Cleanup is registered through `t.Cleanup`, including partial startup. Redis outage and SeaweedFS recreation scenarios manage resources through environment helpers without affecting other tests. Tests fail when Docker is unavailable.
|
||||
Call bootstrap once in the parent test and share its environment with its subtests. Each call creates separate containers with dynamic ports and a separate SeaweedFS volume when needed. Cleanup is registered through `t.Cleanup`, including partial startup. Redis outage and SeaweedFS recreation scenarios manage resources through environment helpers without affecting other tests. Tests fail when Docker is unavailable. Testcontainers also tries the Docker context and default sockets when `DOCKER_HOST` is unreachable, so an invalid `DOCKER_HOST` alone does not simulate a missing Docker.
|
||||
|
||||
Bootstrap starts infrastructure and clients. When PostgreSQL is selected, it applies every embedded migration with the startup runner. `postgres_helpers_test.go` adds `env.newPool` for a pool to that database, `env.createIsolatedDatabase` for a separate database in the same container when a test changes the whole schema (for example up, down, and up again), `env.newPoolWithMaxConns` for concurrency tests that need one connection per transaction, and `truncateTables` for resetting shared tables between sequential subtests. Tests reach the transaction behind a unit of work only through `postgres.TransactionForIntegrationTest`, which is compiled only with the `integration` build tag. Test-only aggregates live in their own schema created by the test, not in production migrations. The application HTTP server, ML, and product fixtures are not included yet. The full-environment test exercises combined PostgreSQL, Redis, and SeaweedFS readiness.
|
||||
|
||||
Kafka is not part of `bootstrap(t)` and starts only for tests that select `bootstrap(t, kafkaService)`. It runs the same `apache/kafka:latest` image as Compose with the same KRaft settings, including `KAFKA_AUTO_CREATE_TOPICS_ENABLE=false`. The client listener is advertised on the dynamic host port, inter-broker and controller traffic stay on container loopback, and the data and declared image volumes use tmpfs, so a test broker leaves no volumes. Bootstrap sets `env.Config.KafkaBrokers` and creates `env.KafkaAdmin` from franz-go `kadm`.
|
||||
|
||||
`kafka_helpers_test.go` contains the helpers. `env.createKafkaTopic(ctx, t, partitions)` creates a topic with a unique random name and registers its deletion in `t.Cleanup` before creation, so the topic is removed even when the test fails. The broker never creates topics on demand: a test creates every topic it uses. `env.newKafkaClient(t, options...)` returns a `kgo` client that closes when `t` finishes. `produceKafkaRecords` and `env.consumeKafkaRecords` have bounded timeouts; the consumer reads partitions from the start without a consumer group, so no group offsets remain. The container is terminated in the cleanup of the test that called bootstrap, including after a failure.
|
||||
|
||||
## Integration test sharding
|
||||
|
||||
`make -C backend test-int` runs the full suite through `backend/scripts/run-integration-suite.py`. The runner discovers every top-level `Test*` in `./integration_test/...`, sorts by package and name, and distributes tests round-robin. Each test belongs to exactly one shard with all its subtests. Changing the test set may change the assignment; duration-based balancing is not implemented.
|
||||
@@ -77,9 +81,9 @@ TEST_SHARD_INDEX=1 TEST_SHARD_TOTAL=2 make -C backend test-int
|
||||
TEST_SHARD_INDEX=2 TEST_SHARD_TOTAL=2 make -C backend test-int
|
||||
```
|
||||
|
||||
Indexes start at 1. Set both variables together; invalid settings, an empty suite, excess shards, and discovery failures fail the command. `test-int-list` compiles test packages and lists selected tests without starting containers. `make -C backend test-scripts` verifies complete, disjoint coverage, parent-test selection, and runner failure propagation. It is included in `make -C backend check`.
|
||||
Indexes start at 1. Set both variables together; invalid settings, an empty suite, excess shards, and discovery failures fail the command. `test-int-list` compiles test packages and lists selected tests without starting containers. `make -C backend test-scripts` verifies for every shard count that each test runs in exactly one shard, that a shard listing matches the tests the shard runs, parent-test selection, and runner failure propagation. It is included in `make -C backend check`.
|
||||
|
||||
CI uses a separate matrix of two integration jobs with `GOFLAGS=-race` and `fail-fast: false`. Every shard must pass before aggregate and deployment smoke succeed. Run `GOFLAGS='-race -shuffle=on' make -C backend test-int` locally to check races and order independence. Shards use their own containers; runners do not share a database. Increase the matrix size together with `TEST_SHARD_TOTAL` when suite duration warrants more runners.
|
||||
CI uses a separate matrix of two integration jobs with `GOFLAGS=-race` and `fail-fast: false`. Every shard must pass before aggregate and deployment smoke succeed. Run `GOFLAGS='-race -shuffle=on' make -C backend test-int` locally to check races and order independence. Shards use their own containers; runners do not share a database or a broker, so a Kafka test passes in whichever shard it lands. Increase the matrix size together with `TEST_SHARD_TOTAL` when suite duration warrants more runners.
|
||||
|
||||
## Future software validation
|
||||
|
||||
|
||||
@@ -44,6 +44,7 @@ Frontend зависимости выбираются из актуальных s
|
||||
| chi | v5.3.2 | backend/go.mod |
|
||||
| pgx | v5.11.0 | backend/go.mod |
|
||||
| testcontainers-go | v0.44.0, включая modules/postgres | backend/go.mod |
|
||||
| franz-go (`kgo`, `kadm`) | v1.22.1, kadm v1.19.0; только integration tests | backend/go.mod |
|
||||
|
||||
Что есть сейчас:
|
||||
|
||||
@@ -52,11 +53,11 @@ Frontend зависимости выбираются из актуальных s
|
||||
- Почта: outbound порт `MailSender`, транспорт `disabled` и выбор `EMAIL_PROVIDER` в bootstrap. В этой сборке работает только `disabled`; `resend` и `smtp` после проверки своих настроек останавливают запуск. Пока ничто не отправляет письма. См. [DEPLOY.md](DEPLOY.md#почта) и [ARCHITECTURE.md](ARCHITECTURE.md#почтовый-транспорт).
|
||||
- OpenAPI контракты api/core/ и api/ml/ с объединением схем, bundles, lint и генерацией для Go (ogen), TypeScript (Orval) и Python (datamodel-code-generator). В SPA есть каркас интерфейса с экранами-заготовками, generated API client и MSW handlers.
|
||||
- Compose проекты: core (`deploy/docker/docker-compose.yml`: PostgreSQL, Redis, SeaweedFS, Kafka, backend, frontend), ML (`docker-compose.ml.yml`) и monitoring (`docker-compose.monitoring.yml`).
|
||||
- Kafka: один узел KRaft в core Compose проекте с listener только во внутренней сети, именованным volume, healthcheck и лимитом памяти. backend/config разбирает и проверяет `KAFKA_BROKERS`, но в backend нет Go клиента Kafka, топиков и проверки Kafka в readiness.
|
||||
- Kafka: один узел KRaft в core Compose проекте с listener только во внутренней сети, именованным volume, healthcheck и лимитом памяти. backend/config разбирает и проверяет `KAFKA_BROKERS`, но в приложении нет клиента Kafka, топиков и проверки Kafka в readiness. Клиент franz-go используется только helpers интеграционных тестов; см. [TESTING.md](TESTING.md#bootstrap-интеграционных-тестов).
|
||||
- CI jobs в .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix из двух шардов), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke` и обязательный итог `aggregate`. Шардирование описано в [TESTING.md](TESTING.md).
|
||||
- Observability: Prometheus, Loki, Alloy, Grafana с provisioned datasources и dashboards, exporters для PostgreSQL, Redis и node. React-приложение пока не отправляет телеметрию.
|
||||
|
||||
Еще не реализованы: регистрация и вход (их контракт объявлен; операции отвечают 501 или 401), согласия, профили, анкета и тестирование, кабинет компании, потребности и подбор, приглашения и контакты, транспорты Resend и SMTP и отправка почты, Go клиент Kafka, relay для outbox, уведомления, поддержка и бизнес-E2E suite. В backend/db/migrations/ есть таблица outbox, таблицы хранения identity (`users`, `email_tokens`, `sessions`) и таблица `policy_versions`, другой бизнес-схемы нет; ни одно продуктовое правило пока не читает политику; регистрация, подтверждение и сессии поверх этого хранения появятся в следующих задачах, каталоги продуктовых usecase и адаптеров, кроме частей для хеширования паролей и политики, содержат только заглушки, а `make -C deploy test-e2e` запускает только технический smoke на Playwright для SPA, health API и маршрутов ошибок на одноразовом стеке, а не бизнес-сценарий (см. [TESTING.md](TESTING.md#браузерный-e2e-набор)). Целевая архитектура описана в [ARCHITECTURE.md](ARCHITECTURE.md).
|
||||
Еще не реализованы: регистрация и вход (их контракт объявлен; операции отвечают 501 или 401), согласия, профили, анкета и тестирование, кабинет компании, потребности и подбор, приглашения и контакты, транспорты Resend и SMTP и отправка почты, клиент Kafka в приложении, relay для outbox, уведомления, поддержка и бизнес-E2E suite. В backend/db/migrations/ есть таблица outbox, таблицы хранения identity (`users`, `email_tokens`, `sessions`) и таблица `policy_versions`, другой бизнес-схемы нет; ни одно продуктовое правило пока не читает политику; регистрация, подтверждение и сессии поверх этого хранения появятся в следующих задачах, каталоги продуктовых usecase и адаптеров, кроме частей для хеширования паролей и политики, содержат только заглушки, а `make -C deploy test-e2e` запускает только технический smoke на Playwright для SPA, health API и маршрутов ошибок на одноразовом стеке, а не бизнес-сценарий (см. [TESTING.md](TESTING.md#браузерный-e2e-набор)). Целевая архитектура описана в [ARCHITECTURE.md](ARCHITECTURE.md).
|
||||
|
||||
## Установка и цикл работы
|
||||
|
||||
|
||||
+9
-5
@@ -20,7 +20,7 @@ make test запускает backend, frontend и ML тесты. make check та
|
||||
| make -C api check | Объединение схем, bundles, OpenAPI lint и тесты merge script |
|
||||
| make -C backend test | Go unit suite с race detector |
|
||||
| make -C backend test-fast | Быстрый Go test без race instrumentation |
|
||||
| make -C backend test-int | Go integration tests с Testcontainers/PostgreSQL/Redis/SeaweedFS |
|
||||
| make -C backend test-int | Go integration tests с Testcontainers/PostgreSQL/Redis/SeaweedFS/Kafka |
|
||||
| make -C frontend check | Prettier, ESLint, Stylelint, TypeScript, Vitest, FSD boundaries и build |
|
||||
| make -C ml check | Ruff, mypy, pytest и сборку wheel |
|
||||
| make -C ml check-generated | Соответствие Pydantic-моделей ML bundle без перезаписи файлов |
|
||||
@@ -37,7 +37,7 @@ make -C ml check-generated использует datamodel-code-generator --check
|
||||
|
||||
## Что покрывает текущий каркас
|
||||
|
||||
Существующие проверки относятся к health/readiness, проверке соединения backend с PostgreSQL, Redis и SeaweedFS, миграциям up, down до нуля и повторному up на изолированной базе, конкурентным runner миграций, которые применяют каждую миграцию один раз, transactional outbox (атомарная фиксация, откат при ошибке, panic и отмене контекста, отказ во вложенной транзакции, наблюдаемое ожидание блокировки строки между параллельными транзакциями, граничные payload и ограничения), хранению identity (уникальный нормализованный email, хранение только хешей email-токенов и токенов сессий, ровно одно успешное погашение токена при параллельных подтверждениях и наблюдаемое ожидание блокировки между двумя погашениями, отказ для истекших, аннулированных и замененных токенов, в том числе при повторной регистрации во время подтверждения, пределы простоя, абсолютного срока и отзыва сессии и ограничение частоты записи активности, пакетная очистка неподтвержденных аккаунтов, которая пропускает заблокированные аккаунты без ожидания, взаимная блокировка как повторяемый конфликт, каскадное удаление, откат вместе с внешней транзакцией и ограничения), операциям кеша и TTL, S3-операциям и сохранению объектов, метрикам, API client, ML schema и доступности текущих endpoint. В каркасе нет сценариев регистрации, входа, тестирования, поиска, приглашений или работы с файлами и нет реального model inference, которые можно было бы проверить как бизнес-результат.
|
||||
Существующие проверки относятся к health/readiness, проверке соединения backend с PostgreSQL, Redis и SeaweedFS, миграциям up, down до нуля и повторному up на изолированной базе, конкурентным runner миграций, которые применяют каждую миграцию один раз, transactional outbox (атомарная фиксация, откат при ошибке, panic и отмене контекста, отказ во вложенной транзакции, наблюдаемое ожидание блокировки строки между параллельными транзакциями, граничные payload и ограничения), хранению identity (уникальный нормализованный email, хранение только хешей email-токенов и токенов сессий, ровно одно успешное погашение токена при параллельных подтверждениях и наблюдаемое ожидание блокировки между двумя погашениями, отказ для истекших, аннулированных и замененных токенов, в том числе при повторной регистрации во время подтверждения, пределы простоя, абсолютного срока и отзыва сессии и ограничение частоты записи активности, пакетная очистка неподтвержденных аккаунтов, которая пропускает заблокированные аккаунты без ожидания, взаимная блокировка как повторяемый конфликт, каскадное удаление, откат вместе с внешней транзакцией и ограничения), операциям кеша и TTL, S3-операциям и сохранению объектов, тестовой обвязке Kafka (записи с ключом и заголовками и порядок внутри партиции, отказ создавать отсутствующий топик по запросу и очистка топиков), метрикам, API client, ML schema и доступности текущих endpoint. В каркасе нет сценариев регистрации, входа, тестирования, поиска, приглашений или работы с файлами, нет relay для outbox и продуктовых событий в Kafka и нет реального model inference, которые можно было бы проверить как бизнес-результат.
|
||||
|
||||
API verify проверяет выбранный OpenAPI subset через pinned toolchain; его результат относится только к реально запущенным fixture и контрактам. CI YAML в репозитории не означает, что workflow уже выполнился на GitHub.
|
||||
|
||||
@@ -63,10 +63,14 @@ Deployment smoke проверяет инфраструктурные маршр
|
||||
|
||||
Общий helper находится в `backend/integration_test/bootstrap_test.go`. Вызов `env := bootstrap(t)` поднимает PostgreSQL, Redis и SeaweedFS, дожидается готовности адаптеров и возвращает окружение с конфигурацией и клиентами. Для проверки одного адаптера используйте `bootstrap(t, postgresService)`, `bootstrap(t, redisService)` или `bootstrap(t, seaweedfsService)`. Можно передать несколько сервисов.
|
||||
|
||||
Вызывайте bootstrap один раз в родительском тесте и используйте окружение в его подтестах. Каждый вызов создает отдельные контейнеры с динамическими портами; для SeaweedFS также создается отдельный volume. Очистка зарегистрирована через `t.Cleanup`, включая частично запущенное окружение. Сценарии остановки Redis и пересоздания SeaweedFS управляют ресурсами через helpers этого окружения и не затрагивают другие тесты. При отсутствии Docker тесты завершаются ошибкой.
|
||||
Вызывайте bootstrap один раз в родительском тесте и используйте окружение в его подтестах. Каждый вызов создает отдельные контейнеры с динамическими портами; для SeaweedFS также создается отдельный volume. Очистка зарегистрирована через `t.Cleanup`, включая частично запущенное окружение. Сценарии остановки Redis и пересоздания SeaweedFS управляют ресурсами через helpers этого окружения и не затрагивают другие тесты. При отсутствии Docker тесты завершаются ошибкой. Если `DOCKER_HOST` недоступен, Testcontainers пробует также Docker context и стандартные сокеты, поэтому одного неверного `DOCKER_HOST` недостаточно, чтобы смоделировать отсутствие Docker.
|
||||
|
||||
Bootstrap поднимает инфраструктуру и клиенты. Если выбран PostgreSQL, он применяет все встроенные миграции тем же runner, что и старт сервиса. `postgres_helpers_test.go` добавляет `env.newPool` для пула к этой базе, `env.createIsolatedDatabase` для отдельной базы в том же контейнере, когда тест меняет всю схему (например up, down и повторный up), `env.newPoolWithMaxConns` для тестов конкурентности, которым нужно одно соединение на транзакцию, и `truncateTables` для сброса общих таблиц между последовательными подтестами. Тесты получают транзакцию из unit of work только через `postgres.TransactionForIntegrationTest`, который компилируется только с build tag `integration`. Тестовые агрегаты живут в собственной схеме, которую создает тест, а не в продуктовых миграциях. HTTP-сервер приложения, ML и продуктовые фикстуры пока не входят в него. Проверка полного окружения использует общий readiness PostgreSQL, Redis и SeaweedFS.
|
||||
|
||||
Kafka не входит в `bootstrap(t)` и запускается только для тестов, которые выбирают `bootstrap(t, kafkaService)`. Используется тот же образ `apache/kafka:latest`, что и в Compose, с теми же настройками KRaft, включая `KAFKA_AUTO_CREATE_TOPICS_ENABLE=false`. Клиентский listener объявляется на динамическом порту хоста, трафик между брокерами и контроллером остается на loopback контейнера, а данные и объявленные в образе volume размещаются в tmpfs, поэтому тестовый брокер не оставляет volume. Bootstrap заполняет `env.Config.KafkaBrokers` и создает `env.KafkaAdmin` на основе `kadm` из franz-go.
|
||||
|
||||
Helpers находятся в `kafka_helpers_test.go`. `env.createKafkaTopic(ctx, t, partitions)` создает топик с уникальным случайным именем и до создания регистрирует его удаление в `t.Cleanup`, поэтому топик удаляется и после падения теста. Брокер не создает топики по запросу: тест сам создает каждый нужный ему топик. `env.newKafkaClient(t, options...)` возвращает клиент `kgo`, который закрывается по завершении `t`. У `produceKafkaRecords` и `env.consumeKafkaRecords` ограниченные таймауты; consumer читает партиции с начала без consumer group, поэтому смещения группы не остаются. Контейнер останавливается и удаляется в cleanup теста, который вызвал bootstrap, в том числе после падения.
|
||||
|
||||
## Шардирование интеграционных тестов
|
||||
|
||||
`make -C backend test-int` запускает полный набор через `backend/scripts/run-integration-suite.py`. Runner автоматически обнаруживает все верхнеуровневые `Test*` в `./integration_test/...`, сортирует их по пакету и имени, затем распределяет по шардам по кругу. Каждый тест попадает ровно в один шард вместе со всеми своими подтестами. Изменение набора тестов может изменить распределение; балансировка по длительности пока не используется.
|
||||
@@ -77,9 +81,9 @@ TEST_SHARD_INDEX=1 TEST_SHARD_TOTAL=2 make -C backend test-int
|
||||
TEST_SHARD_INDEX=2 TEST_SHARD_TOTAL=2 make -C backend test-int
|
||||
```
|
||||
|
||||
Индексы начинаются с 1. Обе переменные задаются вместе; неверные параметры, пустой набор, лишние шарды и ошибки обнаружения завершают команду ошибкой. `test-int-list` компилирует тестовый пакет и выводит выбранные тесты без запуска контейнеров. `make -C backend test-scripts` проверяет полное покрытие без пересечений, выбор родительских тестов и передачу ошибок runner. Он входит в `make -C backend check`.
|
||||
Индексы начинаются с 1. Обе переменные задаются вместе; неверные параметры, пустой набор, лишние шарды и ошибки обнаружения завершают команду ошибкой. `test-int-list` компилирует тестовый пакет и выводит выбранные тесты без запуска контейнеров. `make -C backend test-scripts` проверяет для каждого числа шардов, что каждый тест выполняется ровно в одном шарде, что список шарда совпадает с тестами, которые шард запускает, выбор родительских тестов и передачу ошибок runner. Он входит в `make -C backend check`.
|
||||
|
||||
CI запускает отдельную matrix из двух integration jobs с `GOFLAGS=-race` и `fail-fast: false`. Результат всех шардов обязателен для aggregate и deployment smoke. `GOFLAGS='-race -shuffle=on' make -C backend test-int` позволяет локально проверить гонки и независимость порядка. Шарды используют свои контейнеры; общая БД между runner не создается. Число шардов увеличивается в matrix вместе с `TEST_SHARD_TOTAL`, когда длительность suite оправдывает дополнительные runner.
|
||||
CI запускает отдельную matrix из двух integration jobs с `GOFLAGS=-race` и `fail-fast: false`. Результат всех шардов обязателен для aggregate и deployment smoke. `GOFLAGS='-race -shuffle=on' make -C backend test-int` позволяет локально проверить гонки и независимость порядка. Шарды используют свои контейнеры; общие БД и брокер между runner не создаются, поэтому тест Kafka проходит в любом шарде, куда он попал. Число шардов увеличивается в matrix вместе с `TEST_SHARD_TOTAL`, когда длительность suite оправдывает дополнительные runner.
|
||||
|
||||
## Будущая программная валидация
|
||||
|
||||
|
||||
Reference in new issue
Block a user