MSP-8172 Add vendor
This commit is contained in:
1 parent
5175d87e08
commit
eb066cb055
2619 files changed
+757077
-2
No files matched your search
+87
@@ -0,0 +1,87 @@
|
||||
# Package `test`
|
||||
|
||||
Пакет `test` предоставляет обёртку над `testing.T`, а также автоматическую инициализацию конфигурации и логгера для использования в юнит- и интеграционных тестах.
|
||||
|
||||
## Types
|
||||
|
||||
### Test
|
||||
|
||||
Структура `Test` служит основным контейнером для всех зависимостей, часто используемых в тестах: конфигурация, логгер, контекст `testing.T`, а также вспомогательные утверждения `require.Assertions`.
|
||||
|
||||
**Fields:**
|
||||
|
||||
#### `id string`
|
||||
|
||||
Случайно сгенерированный идентификатор теста (hex-строка длиной 8 символов).
|
||||
|
||||
#### `cfg *config.Config`
|
||||
|
||||
Конфигурация, созданная с помощью `config.New()`.
|
||||
|
||||
#### `logger log.Logger`
|
||||
|
||||
Логгер, инициализированный в режиме разработки и с уровнем `Debug`.
|
||||
|
||||
#### `t *testing.T`
|
||||
|
||||
Ссылка на контекст текущего теста.
|
||||
|
||||
#### `assertions *require.Assertions`
|
||||
|
||||
Обёртка `require.New(t)` для удобства утверждений.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `New(t *testing.T) (*Test, *require.Assertions)`
|
||||
|
||||
Создаёт и возвращает структуру `Test`, а также объект `require.Assertions`.
|
||||
|
||||
Автоматически выполняет:
|
||||
|
||||
- инициализацию конфигурации и логгера,
|
||||
- генерацию короткого идентификатора теста,
|
||||
- создание обёртки `require.New(t)`.
|
||||
|
||||
#### `(t *Test) Config() *config.Config`
|
||||
|
||||
Возвращает объект конфигурации, связанный с текущим тестом.
|
||||
|
||||
#### `(t *Test) Logger() log.Logger`
|
||||
|
||||
Возвращает логгер, связанный с текущим тестом.
|
||||
|
||||
#### `(t *Test) Assert() *require.Assertions`
|
||||
|
||||
Возвращает объект `require.Assertions` для выполнения проверок внутри теста.
|
||||
|
||||
#### `(t *Test) Id() string`
|
||||
|
||||
Возвращает идентификатор текущего теста (4 байта в hex-представлении).
|
||||
|
||||
#### `(t *Test) T() *testing.T`
|
||||
|
||||
Возвращает оригинальный объект `*testing.T`, переданный в `New()`.
|
||||
|
||||
## Usage
|
||||
|
||||
### Example usage in test
|
||||
|
||||
```go
|
||||
package mypkg_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"github.com/txix-open/isp-kit/test"
|
||||
)
|
||||
|
||||
func TestSomething(t *testing.T) {
|
||||
testCtx, assert := test.New(t)
|
||||
|
||||
cfg := testCtx.Config()
|
||||
logger := testCtx.Logger()
|
||||
id := testCtx.Id()
|
||||
|
||||
logger.Info("Running test", log.String("id", id))
|
||||
assert.NotNil(cfg)
|
||||
}
|
||||
```
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
# Package `dbt`
|
||||
|
||||
Пакет `dbt` предназначен для создания и управления изолированной тестовой базой данных PostgreSQL с уникальной схемой на каждый запуск тестов.
|
||||
|
||||
## Types
|
||||
|
||||
### TestDb
|
||||
|
||||
Структура `TestDb` инкапсулирует клиента базы данных `dbx.Client`, используемого для работы с тестовой схемой, а также предоставляет удобные методы для выполнения SQL-запросов с автоматической проверкой ошибок.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `New(t *test.Test, opts ...dbx.Option) *TestDb`
|
||||
|
||||
Создаёт новое подключение к базе данных с уникальной схемой, которая будет автоматически удалена по завершению теста. Внутри создаётся контекст с таймаутом, извлекаемым из конфигурации (`PG_OPEN_TIMEOUT`).
|
||||
|
||||
#### `(db *TestDb) DB() (*dbx.Client, error)`
|
||||
|
||||
Возвращает клиент `dbx.Client`.
|
||||
|
||||
#### `(db *TestDb) Must() must`
|
||||
|
||||
Возвращает структуру `must`, предоставляющую обёртки над методами выполнения SQL-запросов с автоматическими ассерциями.
|
||||
|
||||
#### `(db *TestDb) Schema() string`
|
||||
|
||||
Возвращает имя схемы, с которой работает экземпляр `TestDb`.
|
||||
|
||||
#### `(db *TestDb) Close() error`
|
||||
|
||||
Удаляет схему из базы данных (`DROP SCHEMA ... CASCADE`) и закрывает подключение. В случае ошибок оборачивает их с дополнительным контекстом.
|
||||
|
||||
### must
|
||||
|
||||
Структура `must` предоставляет методы для безопасного выполнения SQL-запросов с проверками через `require.Assertions`. Используется исключительно в тестах.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `(m must) Exec(query string, args ...any) sql.Result`
|
||||
|
||||
Выполняет SQL-запрос и проверяет, что ошибка отсутствует.
|
||||
|
||||
#### `(m must) Select(resultPtr any, query string, args ...any)`
|
||||
|
||||
Выполняет SQL-запрос, ожидающий множество строк, и проверяет отсутствие ошибки.
|
||||
|
||||
#### `(m must) SelectRow(resultPtr any, query string, args ...any)`
|
||||
|
||||
Выполняет SQL-запрос, ожидающий одну строку, и проверяет отсутствие ошибки.
|
||||
|
||||
#### `(m must) ExecNamed(query string, arg any) sql.Result`
|
||||
|
||||
Выполняет именованный SQL-запрос и проверяет отсутствие ошибки.
|
||||
|
||||
#### `(m must) Count(query string, args ...any) int`
|
||||
|
||||
Выполняет SQL-запрос, возвращающий одно числовое значение (count), и проверяет отсутствие ошибки.
|
||||
|
||||
### `Config(t \*test.Test) dbx.Config`
|
||||
|
||||
Формирует конфигурацию для подключения к базе данных на основе значений из тестовой конфигурации. Создаёт уникальное имя схемы (`test_<id>`) для каждого запуска теста.
|
||||
|
||||
## Usage
|
||||
|
||||
### Default usage flow
|
||||
|
||||
```go
|
||||
package mypkg_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/txix-open/isp-kit/test"
|
||||
"github.com/txix-open/isp-kit/test/dbt"
|
||||
)
|
||||
|
||||
func TestExample(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
testCtx := test.New(t)
|
||||
db := dbt.New(testCtx)
|
||||
|
||||
// Пример использования метода must.Exec
|
||||
db.Must().Exec(`CREATE TABLE example (id SERIAL PRIMARY KEY, name TEXT)`)
|
||||
db.Must().Exec(`INSERT INTO example (name) VALUES ($1)`, "test")
|
||||
|
||||
var count int
|
||||
db.Must().SelectRow(&count, `SELECT COUNT(*) FROM example`)
|
||||
testCtx.Assert().Equal(1, count)
|
||||
|
||||
// Очистка схемы произойдёт автоматически по завершению
|
||||
}
|
||||
```
|
||||
+144
@@ -0,0 +1,144 @@
|
||||
// Package dbt provides test helpers for database operations using dbx.
|
||||
// It creates isolated test schemas that are automatically cleaned up after
|
||||
// each test.
|
||||
package dbt
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"runtime"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/txix-open/isp-kit/db"
|
||||
"github.com/txix-open/isp-kit/dbx"
|
||||
"github.com/txix-open/isp-kit/test"
|
||||
)
|
||||
|
||||
// TestDb wraps dbx.Client and provides database operations for testing.
|
||||
// It automatically creates and manages an isolated schema for each test.
|
||||
type TestDb struct {
|
||||
*dbx.Client
|
||||
|
||||
must must
|
||||
schema string
|
||||
}
|
||||
|
||||
// New creates a new TestDb instance with an isolated schema for testing.
|
||||
// The schema is automatically created and will be dropped when the test
|
||||
// completes. Additional dbx options can be provided to customize the
|
||||
// database client.
|
||||
//
|
||||
// nolint:mnd
|
||||
func New(t *test.Test, opts ...dbx.Option) *TestDb {
|
||||
dbConfig := Config(t)
|
||||
dbOpenTimeout := t.Config().Optional().Duration("PG_OPEN_TIMEOUT", 15*time.Second)
|
||||
ctx, cancel := context.WithTimeout(t.T().Context(), dbOpenTimeout)
|
||||
defer cancel()
|
||||
opts = append([]dbx.Option{
|
||||
dbx.WithCreateSchema(true),
|
||||
}, opts...)
|
||||
cli, err := dbx.Open(ctx, dbConfig, opts...)
|
||||
t.Assert().NoError(err, "open test db cli, schema: %s", dbConfig.Schema)
|
||||
|
||||
db := &TestDb{
|
||||
Client: cli,
|
||||
schema: dbConfig.Schema,
|
||||
must: must{
|
||||
db: cli.Client,
|
||||
assert: t.Assert(),
|
||||
},
|
||||
}
|
||||
t.T().Cleanup(func() {
|
||||
err := db.Close()
|
||||
t.Assert().NoError(err)
|
||||
})
|
||||
return db
|
||||
}
|
||||
|
||||
// DB returns the underlying dbx client.
|
||||
func (db *TestDb) DB() (*dbx.Client, error) {
|
||||
return db.Client, nil
|
||||
}
|
||||
|
||||
// Must returns a must helper for performing database operations with
|
||||
// automatic assertion on errors. This is intended for test code.
|
||||
func (db *TestDb) Must() must {
|
||||
return db.must
|
||||
}
|
||||
|
||||
// Schema returns the name of the test schema.
|
||||
func (db *TestDb) Schema() string {
|
||||
return db.schema
|
||||
}
|
||||
|
||||
// Close drops the test schema and closes the database connection.
|
||||
func (db *TestDb) Close() error {
|
||||
_, err := db.Exec(context.Background(), fmt.Sprintf("DROP SCHEMA %s CASCADE", db.schema))
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "drop schema")
|
||||
}
|
||||
err = db.Client.Close()
|
||||
return errors.WithMessage(err, "close db")
|
||||
}
|
||||
|
||||
// must provides database operations that automatically assert no errors.
|
||||
// Each method panics if an error occurs, making it suitable for test code
|
||||
// where failures should be immediate.
|
||||
type must struct {
|
||||
db *db.Client
|
||||
assert *require.Assertions
|
||||
}
|
||||
|
||||
// Exec executes a SQL query without arguments and panics on error.
|
||||
func (m must) Exec(query string, args ...any) sql.Result {
|
||||
res, err := m.db.Exec(context.Background(), query, args...)
|
||||
m.assert.NoError(err)
|
||||
return res
|
||||
}
|
||||
|
||||
// Select selects rows into the provided pointer and panics on error.
|
||||
func (m must) Select(resultPtr any, query string, args ...any) {
|
||||
err := m.db.Select(context.Background(), resultPtr, query, args...)
|
||||
m.assert.NoError(err)
|
||||
}
|
||||
|
||||
// SelectRow selects a single row into the provided pointer and panics on error.
|
||||
func (m must) SelectRow(resultPtr any, query string, args ...any) {
|
||||
err := m.db.SelectRow(context.Background(), resultPtr, query, args...)
|
||||
m.assert.NoError(err)
|
||||
}
|
||||
|
||||
// ExecNamed executes a SQL query with named arguments and panics on error.
|
||||
func (m must) ExecNamed(query string, arg any) sql.Result {
|
||||
res, err := m.db.ExecNamed(context.Background(), query, arg)
|
||||
m.assert.NoError(err)
|
||||
return res
|
||||
}
|
||||
|
||||
// Count returns the count of rows matching the query and panics on error.
|
||||
func (m must) Count(query string, args ...any) int {
|
||||
value := 0
|
||||
m.SelectRow(&value, query, args...)
|
||||
return value
|
||||
}
|
||||
|
||||
// Config creates a dbx.Config for testing with an isolated schema named
|
||||
// after the test. Connection parameters can be overridden using environment
|
||||
// variables: PG_HOST, PG_PORT, PG_DB, PG_USER, PG_PASS.
|
||||
func Config(t *test.Test) dbx.Config {
|
||||
cfg := t.Config()
|
||||
schema := fmt.Sprintf("test_%s", t.Id()) // name must start from none digit
|
||||
dbConfig := dbx.Config{
|
||||
Host: cfg.Optional().String("PG_HOST", "127.0.0.1"),
|
||||
Port: cfg.Optional().Int("PG_PORT", 5432), // nolint:mnd
|
||||
Database: cfg.Optional().String("PG_DB", "test"),
|
||||
Username: cfg.Optional().String("PG_USER", "test"),
|
||||
Password: cfg.Optional().String("PG_PASS", "test"),
|
||||
Schema: schema,
|
||||
MaxOpenConn: runtime.NumCPU(),
|
||||
}
|
||||
return dbConfig
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
# Package `fake`
|
||||
|
||||
Пакет `fake` предназначен для генерации тестовых данных произвольных структур с использованием библиотеки `go-faker/faker`.
|
||||
|
||||
## Types
|
||||
|
||||
### Option
|
||||
|
||||
Тип `Option` представляет собой алиас для `options.OptionFunc` из библиотеки `go-faker/faker`, используемый для настройки генерации случайных данных.
|
||||
|
||||
## Functions
|
||||
|
||||
### `It[T any](opts ...Option) T`
|
||||
|
||||
Генерирует случайное значение произвольного типа `T` с использованием указанных опций. По умолчанию устанавливает минимальный и максимальный размер срезов равным 1. Если генерация завершается с ошибкой, вызывает `panic`.
|
||||
|
||||
#### `MinSliceSize(value uint) Option`
|
||||
|
||||
Возвращает опцию, задающую минимальный размер случайно генерируемых срезов и отображений.
|
||||
|
||||
#### `MaxSliceSize(value uint) Option`
|
||||
|
||||
Возвращает опцию, задающую максимальный размер случайно генерируемых срезов и отображений.
|
||||
|
||||
## Usage
|
||||
|
||||
### Default usage flow
|
||||
|
||||
```go
|
||||
package mypkg_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"github.com/txix-open/isp-kit/test/fake"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
Name string
|
||||
Email string
|
||||
Tags []string
|
||||
}
|
||||
|
||||
func TestFakeUser(t *testing.T) {
|
||||
user := fake.It[User]()
|
||||
require.NotEmpty(t, user.Name)
|
||||
require.NotEmpty(t, user.Email)
|
||||
require.Len(t, user.Tags, 1) // благодаря Min/MaxSliceSize по умолчанию
|
||||
}
|
||||
```
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
// Package fake provides utilities for generating fake test data using
|
||||
// the faker library. It offers a simple interface to create populated
|
||||
// structs for testing.
|
||||
package fake
|
||||
|
||||
import (
|
||||
"github.com/go-faker/faker/v4"
|
||||
"github.com/go-faker/faker/v4/pkg/options"
|
||||
)
|
||||
|
||||
// Option is an alias for faker configuration options.
|
||||
type Option = options.OptionFunc
|
||||
|
||||
// MinSliceSize sets the minimum size for randomly generated slices and maps.
|
||||
func MinSliceSize(value uint) Option {
|
||||
return options.WithRandomMapAndSliceMinSize(value)
|
||||
}
|
||||
|
||||
// MaxSliceSize sets the maximum size for randomly generated slices and maps.
|
||||
func MaxSliceSize(value uint) Option {
|
||||
return options.WithRandomMapAndSliceMaxSize(value)
|
||||
}
|
||||
|
||||
// It generates and returns a fake instance of type T.
|
||||
// By default, it configures slices and maps to have a size of 1.
|
||||
// Additional options can be provided to customize the generation behavior.
|
||||
//
|
||||
// Panics if the faker library encounters an error during generation.
|
||||
//
|
||||
// nolint:ireturn
|
||||
func It[T any](opts ...Option) T {
|
||||
allOpts := []Option{
|
||||
MinSliceSize(1),
|
||||
MaxSliceSize(1),
|
||||
}
|
||||
allOpts = append(allOpts, opts...)
|
||||
var result T
|
||||
err := faker.FakeData(&result, allOpts...)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return result
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
# Package `grpct`
|
||||
|
||||
Пакет `grpct` предназначен для упрощения написания юнит- и интеграционных тестов gRPC-сервисов на базе `isp-kit`.
|
||||
|
||||
## Types
|
||||
|
||||
### MockServer
|
||||
|
||||
Структура `MockServer` представляет собой обёртку над gRPC-сервером, позволяющую удобно мокать отдельные endpoint'ы.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `NewMock(t *test.Test) (*MockServer, *client.Client)`
|
||||
|
||||
Создаёт `MockServer` и соответствующий gRPC-клиент. Полезно для юнит-тестов и простых сценариев мокирования.
|
||||
|
||||
#### `(m *MockServer) Mock(endpoint string, handler any) *MockServer`
|
||||
|
||||
Регистрирует указанный `handler` на переданный `endpoint` с использованием `endpoint.Wrapper`.
|
||||
|
||||
## Functions
|
||||
|
||||
### `TestServer(t *test.Test, service isp.BackendServiceServer) (*grpc.Server, *client.Client)`
|
||||
|
||||
Создаёт полноценный `grpc.Server` с переданным `BackendServiceServer` и возвращает его вместе с клиентом. Подходит для end-to-end тестов.
|
||||
|
||||
Автоматически управляет закрытием ресурсов (`Shutdown` сервера и `Close` клиента) по окончании теста.
|
||||
|
||||
## Usage
|
||||
|
||||
### Create mock gRPC server and mock handler
|
||||
|
||||
```go
|
||||
package mypkg_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpct"
|
||||
"github.com/txix-open/isp-kit/test"
|
||||
)
|
||||
|
||||
func TestExample(t *testing.T) {
|
||||
testCtx := test.New(t)
|
||||
mockSrv, cli := grpct.NewMock(testCtx)
|
||||
mockSrv.Mock("/example.Service/Method", handlerFn)
|
||||
|
||||
resp, err := cli.Invoke(testCtx.Context(), "/example.Service/Method", req, &reply)
|
||||
testCtx.Assert().NoError(err)
|
||||
testCtx.Assert().Equal(expected, reply)
|
||||
}
|
||||
```
|
||||
|
||||
### Create test gRPC server from implementation
|
||||
|
||||
```go
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpct"
|
||||
"github.com/txix-open/isp-kit/test"
|
||||
)
|
||||
|
||||
func TestRealService(t *testing.T) {
|
||||
testCtx := test.New(t)
|
||||
srv, cli := grpct.TestServer(testCtx, myServiceImpl)
|
||||
|
||||
resp, err := cli.Invoke(testCtx.Context(), "/my.Service/Endpoint", req, &reply)
|
||||
testCtx.Assert().NoError(err)
|
||||
testCtx.Assert().Equal(expected, reply)
|
||||
|
||||
_ = srv // используется для дополнительных проверок, если необходимо
|
||||
}
|
||||
```
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
// Package grpct provides test helpers for gRPC server and client operations.
|
||||
// It creates mock gRPC servers on random local ports for testing.
|
||||
package grpct
|
||||
|
||||
import (
|
||||
"net"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/grpc/client"
|
||||
"github.com/txix-open/isp-kit/grpc/endpoint"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
"github.com/txix-open/isp-kit/test"
|
||||
)
|
||||
|
||||
// MockServer provides a mock gRPC server for testing.
|
||||
// It allows registering handlers for specific endpoints.
|
||||
type MockServer struct {
|
||||
Wrapper endpoint.Wrapper
|
||||
srv *grpc.Server
|
||||
router *grpc.Mux
|
||||
}
|
||||
|
||||
// NewMock creates a new mock gRPC server and client pair.
|
||||
// The server listens on a random local port and is automatically
|
||||
// shut down when the test completes.
|
||||
func NewMock(t *test.Test) (*MockServer, *client.Client) {
|
||||
srv, cli := TestServer(t, grpc.NewMux())
|
||||
router := grpc.NewMux()
|
||||
srv.Upgrade(router)
|
||||
return &MockServer{
|
||||
Wrapper: endpoint.DefaultWrapper(t.Logger()),
|
||||
srv: srv,
|
||||
router: router,
|
||||
}, cli
|
||||
}
|
||||
|
||||
// Mock registers a handler for the specified endpoint.
|
||||
// Returns the MockServer for method chaining.
|
||||
func (m *MockServer) Mock(endpoint string, handler any) *MockServer {
|
||||
m.router.Handle(endpoint, m.Wrapper.Endpoint(handler))
|
||||
return m
|
||||
}
|
||||
|
||||
// TestServer creates and starts a gRPC server with the provided service,
|
||||
// returning both the server and a configured client. The server listens
|
||||
// on a random local port and is automatically shut down when the test completes.
|
||||
func TestServer(t *test.Test, service isp.BackendServiceServer) (*grpc.Server, *client.Client) {
|
||||
assert := t.Assert()
|
||||
|
||||
var lc net.ListenConfig
|
||||
listener, err := lc.Listen(t.T().Context(), "tcp", "127.0.0.1:")
|
||||
assert.NoError(err)
|
||||
srv := grpc.NewServer()
|
||||
cli, err := client.Default()
|
||||
assert.NoError(err)
|
||||
t.T().Cleanup(func() {
|
||||
err := cli.Close()
|
||||
assert.NoError(err)
|
||||
srv.Shutdown()
|
||||
})
|
||||
srv.Upgrade(service)
|
||||
go func() {
|
||||
err := srv.Serve(listener)
|
||||
assert.NoError(err)
|
||||
}()
|
||||
|
||||
cli.Upgrade([]string{listener.Addr().String()})
|
||||
return srv, cli
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
# Package `rct`
|
||||
|
||||
Пакет `rct` предназначен для тестирования схемы и валидации удалённой конфигурации, используемой с `isp-kit`.
|
||||
|
||||
## Functions
|
||||
|
||||
### `Test[T any](t *testing.T, defaultRemoteConfigPath string, remoteConfig T)`
|
||||
|
||||
Проверяет, что удалённая конфигурация соответствует сгенерированной JSON-схеме и проходит валидацию.
|
||||
|
||||
* Проверяет отсутствие устаревшего тега `valid`
|
||||
* Проверяет соответствие структуры JSON-схеме
|
||||
* Выполняет валидацию значений с помощью `validator.Default`
|
||||
|
||||
### `FindTag[T any](v T, tag string) bool`
|
||||
|
||||
Рекурсивно проверяет, содержит ли структура тег с указанным именем.
|
||||
|
||||
## Usage
|
||||
|
||||
### Example usage in test
|
||||
|
||||
```go
|
||||
package mypkg_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/txix-open/isp-kit/rct"
|
||||
)
|
||||
|
||||
type RemoteCfg struct {
|
||||
Name string `json:"name" validate:"required"`
|
||||
}
|
||||
|
||||
func TestRemoteCfg(t *testing.T) {
|
||||
rct.Test(t, "conf/default_remote_config.json", RemoteCfg{})
|
||||
}
|
||||
```
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"string": "value",
|
||||
"integer": 122,
|
||||
"child": {
|
||||
"value": "123"
|
||||
}
|
||||
}
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
// Package rct provides test helpers for remote configuration validation.
|
||||
// It validates that configuration structures match their JSON schemas and
|
||||
// can be properly unmarshaled from configuration files.
|
||||
package rct
|
||||
|
||||
import (
|
||||
"os"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/txix-open/isp-kit/json"
|
||||
"github.com/txix-open/isp-kit/rc"
|
||||
"github.com/txix-open/isp-kit/validator"
|
||||
"github.com/xeipuuv/gojsonschema"
|
||||
)
|
||||
|
||||
// Test validates that the provided configuration structure matches its
|
||||
// generated JSON schema and can be properly unmarshaled from the default
|
||||
// configuration file. It also verifies that the configuration passes
|
||||
// validator tag validation.
|
||||
//
|
||||
// The function checks:
|
||||
// - No deprecated 'valid' tags are present
|
||||
// - The default configuration file is valid against the generated schema
|
||||
// - The configuration can be unmarshaled from the file
|
||||
// - The configuration passes validation
|
||||
//
|
||||
// nolint:lll
|
||||
func Test[T any](t *testing.T, defaultRemoteConfigPath string, remoteConfig T) {
|
||||
require := require.New(t)
|
||||
|
||||
validatorTag := "valid"
|
||||
require.Falsef(FindTag(remoteConfig, validatorTag), "'%s' tag is not longer supported, you must use https://github.com/go-playground/validator", validatorTag)
|
||||
|
||||
defaultRemoteConfig, err := os.ReadFile(defaultRemoteConfigPath)
|
||||
require.NoError(err)
|
||||
|
||||
jsonSchema := rc.GenerateConfigSchema(remoteConfig)
|
||||
jsonSchemaData, err := json.Marshal(jsonSchema)
|
||||
require.NoError(err)
|
||||
|
||||
remoteConfigAsMap := make(map[string]any)
|
||||
err = json.Unmarshal(defaultRemoteConfig, &remoteConfigAsMap)
|
||||
require.NoError(err)
|
||||
|
||||
schemaLoader := gojsonschema.NewBytesLoader(jsonSchemaData)
|
||||
configLoader := gojsonschema.NewGoLoader(remoteConfigAsMap)
|
||||
result, err := gojsonschema.Validate(schemaLoader, configLoader)
|
||||
require.NoError(err)
|
||||
|
||||
for _, resultError := range result.Errors() {
|
||||
require.Empty(resultError.String())
|
||||
}
|
||||
|
||||
err = json.Unmarshal(defaultRemoteConfig, &remoteConfig)
|
||||
require.NoError(err)
|
||||
err = validator.Default.ValidateToError(remoteConfig)
|
||||
require.NoError(err)
|
||||
}
|
||||
|
||||
// FindTag recursively searches a type for the specified struct tag.
|
||||
// It traverses structs, maps, arrays, and slices to find any field
|
||||
// that has the given tag. Returns true if the tag is found.
|
||||
func FindTag[T any](v T, tag string) bool {
|
||||
t := reflect.TypeOf(v)
|
||||
if t == nil {
|
||||
return false
|
||||
}
|
||||
queue := []reflect.Type{t}
|
||||
for len(queue) > 0 {
|
||||
cur := queue[0]
|
||||
queue = queue[1:]
|
||||
if cur.Kind() == reflect.Ptr {
|
||||
cur = cur.Elem()
|
||||
}
|
||||
// nolint:exhaustive
|
||||
switch cur.Kind() {
|
||||
case reflect.Struct:
|
||||
for field := range cur.Fields() {
|
||||
if field.Tag.Get(tag) != "" {
|
||||
return true
|
||||
}
|
||||
queue = append(queue, field.Type)
|
||||
}
|
||||
case reflect.Map, reflect.Array, reflect.Slice:
|
||||
queue = append(queue, cur.Elem())
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
// Package test provides a test helper that wraps testing.TB and automatically
|
||||
// initializes configuration and logger for unit and integration tests.
|
||||
//
|
||||
// The Test struct serves as a central container for commonly used test
|
||||
// dependencies including configuration, logger, testing.TB context, and
|
||||
// require.Assertions for assertions.
|
||||
package test
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/txix-open/isp-kit/config"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
)
|
||||
|
||||
const (
|
||||
testIdLength = 4
|
||||
)
|
||||
|
||||
// Test is a test helper that wraps testing.TB and provides access to
|
||||
// initialized configuration, logger, and assertion utilities.
|
||||
type Test struct {
|
||||
id string
|
||||
cfg *config.Config
|
||||
logger log.Logger
|
||||
t testing.TB
|
||||
assertions *require.Assertions
|
||||
}
|
||||
|
||||
// New creates and returns a Test instance and require.Assertions.
|
||||
//
|
||||
// It automatically initializes configuration and logger, generates a
|
||||
// unique test identifier, and creates require assertions. The function
|
||||
// marks the calling test as a helper.
|
||||
func New(tb testing.TB) (*Test, *require.Assertions) {
|
||||
tb.Helper()
|
||||
|
||||
assert := require.New(tb)
|
||||
cfg, err := config.New()
|
||||
assert.NoError(err)
|
||||
|
||||
logger, err := log.New(log.WithDevelopmentMode(), log.WithLevel(log.DebugLevel))
|
||||
assert.NoError(err)
|
||||
|
||||
idBytes := make([]byte, testIdLength)
|
||||
_, err = rand.Read(idBytes)
|
||||
assert.NoError(err)
|
||||
return &Test{
|
||||
id: hex.EncodeToString(idBytes),
|
||||
t: tb,
|
||||
cfg: cfg,
|
||||
logger: logger,
|
||||
assertions: assert,
|
||||
}, assert
|
||||
}
|
||||
|
||||
// Config returns the configuration instance associated with the test.
|
||||
func (t *Test) Config() *config.Config {
|
||||
return t.cfg
|
||||
}
|
||||
|
||||
// Logger returns the logger instance associated with the test.
|
||||
// The logger is configured in development mode with debug level.
|
||||
//
|
||||
// nolint:ireturn
|
||||
func (t *Test) Logger() log.Logger {
|
||||
return t.logger
|
||||
}
|
||||
|
||||
// Assert returns the require.Assertions instance for performing
|
||||
// assertions within the test.
|
||||
func (t *Test) Assert() *require.Assertions {
|
||||
return t.assertions
|
||||
}
|
||||
|
||||
// Id returns the unique identifier for the test as a hexadecimal string.
|
||||
func (t *Test) Id() string {
|
||||
return t.id
|
||||
}
|
||||
|
||||
// T returns the underlying testing.TB instance.
|
||||
func (t *Test) T() testing.TB {
|
||||
return t.t
|
||||
}
|
||||
Reference in new issue
Block a user