MSP-8974 fix tests

This commit is contained in:
chashintv committed 2026-11-23 12:58:04 +03:00
1 parent 71498785ea
commit fa8bc6c1b7
50 files changed
+392 -2975

No files matched your search

+72
View File
@@ -0,0 +1,72 @@
# Package `httpt`
Пакет `httpt` предназначен для упрощения написания HTTP-тестов (юнит- и интеграционных) с использованием клиента и сервера на базе `isp-kit`.
## Types
### MockServer
Структура `MockServer` представляет собой обёртку над HTTP-сервером, позволяющую удобно мокать отдельные endpoint'ы с использованием `endpoint.Wrapper` и роутера `router.Router`.
**Methods:**
#### `NewMock(t *test.Test) *MockServer`
Создаёт `MockServer`, автоматически запускает сервер и регистрирует его закрытие в `t.Cleanup`. Подходит для юнит-тестов с ручной маршрутизацией и моками.
#### `(m *MockServer) POST(path string, handler any) *MockServer`
Регистрирует POST-обработчик на указанный путь.
#### `(m *MockServer) GET(path string, handler any) *MockServer`
Регистрирует GET-обработчик на указанный путь.
#### `(m *MockServer) Mock(method string, path string, handler any) *MockServer`
Регистрирует обработчик на указанный путь и метод с использованием `Wrapper.Endpoint`.
#### `(m *MockServer) Client(opts ...httpcli.Option) *httpcli.Client`
Создаёт HTTP-клиент, настроенный на тестовый сервер.
#### `(m *MockServer) BaseURL() string`
Возвращает базовый URL тестового сервера.
## Functions
### `TestServer(t *test.Test, handler http.Handler, opts ...httpcli.Option) (*httptest.Server, *httpcli.Client)`
Создаёт `httptest.Server` с указанным HTTP-обработчиком и возвращает его вместе с клиентом `httpcli.Client`. Подходит для end-to-end тестов.
Автоматически управляет закрытием ресурсов (`srv.Close`) по окончании теста.
## Usage
### Example usage in test
```go
package mypkg_test
import (
"net/http"
"testing"
"github.com/txix-open/isp-kit/http/httpt"
"github.com/txix-open/isp-kit/test"
)
func TestExample(t *testing.T) {
testCtx := test.New(t)
srv, cli := httpt.TestServer(testCtx, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("ok"))
}))
resp, err := cli.Get("/")
testCtx.Assert().NoError(err)
testCtx.Assert().Equal(200, resp.StatusCode)
testCtx.Assert().BodyEqual(resp, "ok")
_ = srv // для дополнительных проверок, если нужно
}
```
+20
View File
@@ -0,0 +1,20 @@
package httpt
import (
"net/http"
"net/http/httptest"
"github.com/txix-open/isp-kit/http/httpcli"
"github.com/txix-open/isp-kit/http/httpclix"
"github.com/txix-open/isp-kit/test"
)
// TestServer creates and starts an HTTP test server with the provided handler,
// returning both the server and a configured client. The server listens on
// a random local port and the client is pre-configured with the server's URL.
func TestServer(t *test.Test, handler http.Handler, opts ...httpcli.Option) (*httptest.Server, *httpcli.Client) {
srv := httptest.NewServer(handler)
cli := httpclix.Default(opts...)
cli.GlobalRequestConfig().BaseUrl = srv.URL
return srv, cli
}
+72
View File
@@ -0,0 +1,72 @@
// Package httpt provides test helpers for HTTP server and client operations.
// It creates mock HTTP servers on random local ports for testing.
package httpt
import (
"net/http"
"net/http/httptest"
"github.com/txix-open/isp-kit/http/endpoint"
"github.com/txix-open/isp-kit/http/endpoint/httplog"
"github.com/txix-open/isp-kit/http/httpcli"
"github.com/txix-open/isp-kit/http/router"
"github.com/txix-open/isp-kit/test"
)
// MockServer provides a mock HTTP server for testing.
// It uses httptest.Server and allows registering handlers for specific
// HTTP methods and paths.
type MockServer struct {
Wrapper endpoint.Wrapper
srv *httptest.Server
router *router.Router
}
// NewMock creates a new mock HTTP server.
// The server listens on a random local port and is automatically
// shut down when the test completes.
func NewMock(t *test.Test) *MockServer {
router := router.New()
srv := httptest.NewServer(router)
t.T().Cleanup(func() {
srv.Close()
})
wrapper := endpoint.DefaultWrapper(t.Logger(), httplog.Log(t.Logger(), true))
return &MockServer{
Wrapper: wrapper,
srv: srv,
router: router,
}
}
// Client creates a new HTTP client configured to send requests to the
// mock server's base URL. Optional client configuration can be provided.
func (m *MockServer) Client(opts ...httpcli.Option) *httpcli.Client {
cli := httpcli.New(opts...)
cli.GlobalRequestConfig().BaseUrl = m.BaseURL()
return cli
}
// BaseURL returns the base URL of the mock server.
func (m *MockServer) BaseURL() string {
return m.srv.URL
}
// POST registers a handler for POST requests at the specified path.
// Returns the MockServer for method chaining.
func (m *MockServer) POST(path string, handler any) *MockServer {
return m.Mock(http.MethodPost, path, handler)
}
// GET registers a handler for GET requests at the specified path.
// Returns the MockServer for method chaining.
func (m *MockServer) GET(path string, handler any) *MockServer {
return m.Mock(http.MethodGet, path, handler)
}
// Mock registers a handler for the specified HTTP method and path.
// Returns the MockServer for method chaining.
func (m *MockServer) Mock(method string, path string, handler any) *MockServer {
m.router.Handler(method, path, m.Wrapper.Endpoint(handler))
return m
}