MSP-8974 fix tests
This commit is contained in:
1 parent
71498785ea
commit
fa8bc6c1b7
50 files changed
+392
-2975
No files matched your search
-74
@@ -1,74 +0,0 @@
|
||||
# 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
@@ -1,69 +0,0 @@
|
||||
// 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
|
||||
}
|
||||
+72
@@ -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
@@ -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
@@ -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
|
||||
}
|
||||
Reference in new issue
Block a user