test(backend): add Kafka to the shared integration bootstrap

This commit is contained in:
shira committed 2026-10-06 02:13:28 +03:00
1 parent 65d66b6f7d
commit 1aa7a9feaf
11 files changed
+485 -32

No files matched your search

+5 -2
View File
@@ -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
View File
@@ -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=
+145 -2
View File
@@ -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:
}
}
}
+124
View File
@@ -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)
}
}
}
+24 -9
View File
@@ -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()