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
@@ -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