Merge pull request #4 from xdrm-io/test/coverage
improve test coverage to 80% for every package
This commit is contained in:
commit
39978a6743
|
@ -17,6 +17,12 @@ func TestCombination(t *testing.T) {
|
||||||
Active: []string{},
|
Active: []string{},
|
||||||
Granted: true,
|
Granted: true,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
Name: "empty requirements none given",
|
||||||
|
Required: [][]string{{}},
|
||||||
|
Active: []string{},
|
||||||
|
Granted: true,
|
||||||
|
},
|
||||||
{
|
{
|
||||||
Name: "no requirement 1 given",
|
Name: "no requirement 1 given",
|
||||||
Required: [][]string{},
|
Required: [][]string{},
|
||||||
|
|
|
@ -0,0 +1,79 @@
|
||||||
|
package api_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/xdrm-io/aicra/api"
|
||||||
|
"github.com/xdrm-io/aicra/internal/ctx"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestContextGetRequest(t *testing.T) {
|
||||||
|
req, err := http.NewRequest(http.MethodGet, "/random", nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("cannot create http request: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// store in bare context
|
||||||
|
c := context.Background()
|
||||||
|
c = context.WithValue(c, ctx.Request, req)
|
||||||
|
|
||||||
|
// fetch from context
|
||||||
|
fetched := api.GetRequest(c)
|
||||||
|
if fetched != req {
|
||||||
|
t.Fatalf("fetched http request %v ; expected %v", fetched, req)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestContextGetNilRequest(t *testing.T) {
|
||||||
|
// fetch from bare context
|
||||||
|
fetched := api.GetRequest(context.Background())
|
||||||
|
if fetched != nil {
|
||||||
|
t.Fatalf("fetched http request %v from empty context; expected nil", fetched)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestContextGetResponseWriter(t *testing.T) {
|
||||||
|
res := httptest.NewRecorder()
|
||||||
|
|
||||||
|
// store in bare context
|
||||||
|
c := context.Background()
|
||||||
|
c = context.WithValue(c, ctx.Response, res)
|
||||||
|
|
||||||
|
// fetch from context
|
||||||
|
fetched := api.GetResponseWriter(c)
|
||||||
|
if fetched != res {
|
||||||
|
t.Fatalf("fetched http response writer %v ; expected %v", fetched, res)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestContextGetNilResponseWriter(t *testing.T) {
|
||||||
|
// fetch from bare context
|
||||||
|
fetched := api.GetResponseWriter(context.Background())
|
||||||
|
if fetched != nil {
|
||||||
|
t.Fatalf("fetched http response writer %v from empty context; expected nil", fetched)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestContextGetAuth(t *testing.T) {
|
||||||
|
auth := &api.Auth{}
|
||||||
|
|
||||||
|
// store in bare context
|
||||||
|
c := context.Background()
|
||||||
|
c = context.WithValue(c, ctx.Auth, auth)
|
||||||
|
|
||||||
|
// fetch from context
|
||||||
|
fetched := api.GetAuth(c)
|
||||||
|
if fetched != auth {
|
||||||
|
t.Fatalf("fetched api auth %v ; expected %v", fetched, auth)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestContextGetNilAuth(t *testing.T) {
|
||||||
|
// fetch from bare context
|
||||||
|
fetched := api.GetAuth(context.Background())
|
||||||
|
if fetched != nil {
|
||||||
|
t.Fatalf("fetched api auth %v from empty context; expected nil", fetched)
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,63 +0,0 @@
|
||||||
package api
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"net/http"
|
|
||||||
)
|
|
||||||
|
|
||||||
// ResponseData defines format for response parameters to return
|
|
||||||
type ResponseData map[string]interface{}
|
|
||||||
|
|
||||||
// Response represents an API response to be sent
|
|
||||||
type Response struct {
|
|
||||||
Data ResponseData
|
|
||||||
Status int
|
|
||||||
Headers http.Header
|
|
||||||
err Err
|
|
||||||
}
|
|
||||||
|
|
||||||
// EmptyResponse creates an empty response.
|
|
||||||
func EmptyResponse() *Response {
|
|
||||||
return &Response{
|
|
||||||
Status: http.StatusOK,
|
|
||||||
Data: make(ResponseData),
|
|
||||||
err: ErrFailure,
|
|
||||||
Headers: make(http.Header),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithError sets the error
|
|
||||||
func (res *Response) WithError(err Err) *Response {
|
|
||||||
res.err = err
|
|
||||||
return res
|
|
||||||
}
|
|
||||||
|
|
||||||
func (res *Response) Error() string {
|
|
||||||
return res.err.Error()
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetData adds/overrides a new response field
|
|
||||||
func (res *Response) SetData(name string, value interface{}) {
|
|
||||||
res.Data[name] = value
|
|
||||||
}
|
|
||||||
|
|
||||||
// MarshalJSON implements the 'json.Marshaler' interface and is used
|
|
||||||
// to generate the JSON representation of the response
|
|
||||||
func (res *Response) MarshalJSON() ([]byte, error) {
|
|
||||||
fmt := make(map[string]interface{})
|
|
||||||
for k, v := range res.Data {
|
|
||||||
fmt[k] = v
|
|
||||||
}
|
|
||||||
fmt["error"] = res.err
|
|
||||||
return json.Marshal(fmt)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (res *Response) ServeHTTP(w http.ResponseWriter, r *http.Request) error {
|
|
||||||
w.WriteHeader(res.err.Status)
|
|
||||||
encoded, err := json.Marshal(res)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
w.Write(encoded)
|
|
||||||
return nil
|
|
||||||
}
|
|
12
builder.go
12
builder.go
|
@ -20,7 +20,7 @@ type Builder struct {
|
||||||
middlewares []func(http.Handler) http.Handler
|
middlewares []func(http.Handler) http.Handler
|
||||||
// custom middlewares only wrapping the service handler of a request
|
// custom middlewares only wrapping the service handler of a request
|
||||||
// they will benefit from the request's context that contains service-specific
|
// they will benefit from the request's context that contains service-specific
|
||||||
// information (e.g. required permisisons from the configuration)
|
// information (e.g. required permissions from the configuration)
|
||||||
ctxMiddlewares []func(http.Handler) http.Handler
|
ctxMiddlewares []func(http.Handler) http.Handler
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -52,9 +52,6 @@ func (b *Builder) Validate(t validator.Type) error {
|
||||||
// the service associated with the request has not been found at this stage.
|
// the service associated with the request has not been found at this stage.
|
||||||
// This stage is perfect for logging or generic request management.
|
// This stage is perfect for logging or generic request management.
|
||||||
func (b *Builder) With(mw func(http.Handler) http.Handler) {
|
func (b *Builder) With(mw func(http.Handler) http.Handler) {
|
||||||
if b.conf == nil {
|
|
||||||
b.conf = &config.Server{}
|
|
||||||
}
|
|
||||||
if b.middlewares == nil {
|
if b.middlewares == nil {
|
||||||
b.middlewares = make([]func(http.Handler) http.Handler, 0)
|
b.middlewares = make([]func(http.Handler) http.Handler, 0)
|
||||||
}
|
}
|
||||||
|
@ -69,9 +66,6 @@ func (b *Builder) With(mw func(http.Handler) http.Handler) {
|
||||||
// data that can be access with api.GetRequest(), api.GetResponseWriter(),
|
// data that can be access with api.GetRequest(), api.GetResponseWriter(),
|
||||||
// api.GetAuth(), etc methods.
|
// api.GetAuth(), etc methods.
|
||||||
func (b *Builder) WithContext(mw func(http.Handler) http.Handler) {
|
func (b *Builder) WithContext(mw func(http.Handler) http.Handler) {
|
||||||
if b.conf == nil {
|
|
||||||
b.conf = &config.Server{}
|
|
||||||
}
|
|
||||||
if b.ctxMiddlewares == nil {
|
if b.ctxMiddlewares == nil {
|
||||||
b.ctxMiddlewares = make([]func(http.Handler) http.Handler, 0)
|
b.ctxMiddlewares = make([]func(http.Handler) http.Handler, 0)
|
||||||
}
|
}
|
||||||
|
@ -85,14 +79,14 @@ func (b *Builder) Setup(r io.Reader) error {
|
||||||
b.conf = &config.Server{}
|
b.conf = &config.Server{}
|
||||||
}
|
}
|
||||||
if b.conf.Services != nil {
|
if b.conf.Services != nil {
|
||||||
panic(errAlreadySetup)
|
return errAlreadySetup
|
||||||
}
|
}
|
||||||
return b.conf.Parse(r)
|
return b.conf.Parse(r)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Bind a dynamic handler to a REST service (method and pattern)
|
// Bind a dynamic handler to a REST service (method and pattern)
|
||||||
func (b *Builder) Bind(method, path string, fn interface{}) error {
|
func (b *Builder) Bind(method, path string, fn interface{}) error {
|
||||||
if b.conf.Services == nil {
|
if b.conf == nil || b.conf.Services == nil {
|
||||||
return errNotSetup
|
return errNotSetup
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
176
builder_test.go
176
builder_test.go
|
@ -8,6 +8,7 @@ import (
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/xdrm-io/aicra/api"
|
"github.com/xdrm-io/aicra/api"
|
||||||
|
"github.com/xdrm-io/aicra/internal/dynfunc"
|
||||||
"github.com/xdrm-io/aicra/validator"
|
"github.com/xdrm-io/aicra/validator"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -34,6 +35,8 @@ func addBuiltinTypes(b *Builder) error {
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestAddType(t *testing.T) {
|
func TestAddType(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
builder := &Builder{}
|
builder := &Builder{}
|
||||||
err := builder.Validate(validator.BoolType{})
|
err := builder.Validate(validator.BoolType{})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
@ -49,7 +52,180 @@ func TestAddType(t *testing.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestSetupNoType(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
builder := &Builder{}
|
||||||
|
err := builder.Setup(strings.NewReader("[]"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %s", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestSetupTwice(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
builder := &Builder{}
|
||||||
|
err := builder.Setup(strings.NewReader("[]"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %s", err)
|
||||||
|
}
|
||||||
|
// double Setup() must fail
|
||||||
|
err = builder.Setup(strings.NewReader("[]"))
|
||||||
|
if err != errAlreadySetup {
|
||||||
|
t.Fatalf("expected error %v, got %v", errAlreadySetup, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBindBeforeSetup(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
builder := &Builder{}
|
||||||
|
// binding before Setup() must fail
|
||||||
|
err := builder.Bind(http.MethodGet, "/path", func() {})
|
||||||
|
if err != errNotSetup {
|
||||||
|
t.Fatalf("expected error %v, got %v", errNotSetup, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBindUnknownService(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
builder := &Builder{}
|
||||||
|
err := builder.Setup(strings.NewReader("[]"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %s", err)
|
||||||
|
}
|
||||||
|
err = builder.Bind(http.MethodGet, "/path", func() {})
|
||||||
|
if !errors.Is(err, errUnknownService) {
|
||||||
|
t.Fatalf("expected error %v, got %v", errUnknownService, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestBindInvalidHandler(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
builder := &Builder{}
|
||||||
|
err := builder.Setup(strings.NewReader(`[
|
||||||
|
{
|
||||||
|
"method": "GET",
|
||||||
|
"path": "/path",
|
||||||
|
"scope": [[]],
|
||||||
|
"info": "info",
|
||||||
|
"in": {},
|
||||||
|
"out": {}
|
||||||
|
}
|
||||||
|
]`))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %s", err)
|
||||||
|
}
|
||||||
|
err = builder.Bind(http.MethodGet, "/path", func() {})
|
||||||
|
|
||||||
|
if err == nil {
|
||||||
|
t.Fatalf("expected an error")
|
||||||
|
}
|
||||||
|
|
||||||
|
if !errors.Is(err, dynfunc.ErrMissingHandlerContextArgument) {
|
||||||
|
t.Fatalf("expected a dynfunc.Err got %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestBindGet(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
builder := &Builder{}
|
||||||
|
err := builder.Setup(strings.NewReader(`[
|
||||||
|
{
|
||||||
|
"method": "GET",
|
||||||
|
"path": "/path",
|
||||||
|
"scope": [[]],
|
||||||
|
"info": "info",
|
||||||
|
"in": {},
|
||||||
|
"out": {}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"method": "POST",
|
||||||
|
"path": "/path",
|
||||||
|
"scope": [[]],
|
||||||
|
"info": "info",
|
||||||
|
"in": {},
|
||||||
|
"out": {}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"method": "PUT",
|
||||||
|
"path": "/path",
|
||||||
|
"scope": [[]],
|
||||||
|
"info": "info",
|
||||||
|
"in": {},
|
||||||
|
"out": {}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"method": "DELETE",
|
||||||
|
"path": "/path",
|
||||||
|
"scope": [[]],
|
||||||
|
"info": "info",
|
||||||
|
"in": {},
|
||||||
|
"out": {}
|
||||||
|
}
|
||||||
|
]`))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
err = builder.Get("/path", func(context.Context) (*struct{}, api.Err) { return nil, api.ErrSuccess })
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error %v", err)
|
||||||
|
}
|
||||||
|
err = builder.Post("/path", func(context.Context) (*struct{}, api.Err) { return nil, api.ErrSuccess })
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error %v", err)
|
||||||
|
}
|
||||||
|
err = builder.Put("/path", func(context.Context) (*struct{}, api.Err) { return nil, api.ErrSuccess })
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error %v", err)
|
||||||
|
}
|
||||||
|
err = builder.Delete("/path", func(context.Context) (*struct{}, api.Err) { return nil, api.ErrSuccess })
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUnhandledService(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
builder := &Builder{}
|
||||||
|
err := builder.Setup(strings.NewReader(`[
|
||||||
|
{
|
||||||
|
"method": "GET",
|
||||||
|
"path": "/path",
|
||||||
|
"scope": [[]],
|
||||||
|
"info": "info",
|
||||||
|
"in": {},
|
||||||
|
"out": {}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"method": "POST",
|
||||||
|
"path": "/path",
|
||||||
|
"scope": [[]],
|
||||||
|
"info": "info",
|
||||||
|
"in": {},
|
||||||
|
"out": {}
|
||||||
|
}
|
||||||
|
]`))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
err = builder.Get("/path", func(context.Context) (*struct{}, api.Err) { return nil, api.ErrSuccess })
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = builder.Build()
|
||||||
|
if !errors.Is(err, errMissingHandler) {
|
||||||
|
t.Fatalf("expected a %v error, got %v", errMissingHandler, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
func TestBind(t *testing.T) {
|
func TestBind(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
tcases := []struct {
|
tcases := []struct {
|
||||||
Name string
|
Name string
|
||||||
Config string
|
Config string
|
||||||
|
|
53
handler.go
53
handler.go
|
@ -2,6 +2,7 @@ package aicra
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
|
@ -27,21 +28,25 @@ func (s Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||||
|
|
||||||
// ServeHTTP implements http.Handler and wraps it in middlewares (adapters)
|
// ServeHTTP implements http.Handler and wraps it in middlewares (adapters)
|
||||||
func (s Handler) resolve(w http.ResponseWriter, r *http.Request) {
|
func (s Handler) resolve(w http.ResponseWriter, r *http.Request) {
|
||||||
// 1ind a matching service from config
|
// match service from config
|
||||||
var service = s.conf.Find(r)
|
var service = s.conf.Find(r)
|
||||||
if service == nil {
|
if service == nil {
|
||||||
handleError(api.ErrUnknownService, w, r)
|
newResponse().WithError(api.ErrUnknownService).ServeHTTP(w, r)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// extract request data
|
// extract request data
|
||||||
var input, err = extractInput(service, *r)
|
var input, err = extractInput(service, *r)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
handleError(api.ErrMissingParam, w, r)
|
if errors.Is(err, reqdata.ErrInvalidType) {
|
||||||
|
newResponse().WithError(api.ErrInvalidParam).ServeHTTP(w, r)
|
||||||
|
} else {
|
||||||
|
newResponse().WithError(api.ErrMissingParam).ServeHTTP(w, r)
|
||||||
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// find a matching handler
|
// match handler
|
||||||
var handler *apiHandler
|
var handler *apiHandler
|
||||||
for _, h := range s.handlers {
|
for _, h := range s.handlers {
|
||||||
if h.Method == service.Method && h.Path == service.Pattern {
|
if h.Method == service.Method && h.Path == service.Pattern {
|
||||||
|
@ -49,13 +54,13 @@ func (s Handler) resolve(w http.ResponseWriter, r *http.Request) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// fail on no matching handler
|
// no handler found
|
||||||
if handler == nil {
|
if handler == nil {
|
||||||
handleError(api.ErrUncallableService, w, r)
|
newResponse().WithError(api.ErrUncallableService).ServeHTTP(w, r)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// build context with builtin data
|
// add info into context
|
||||||
c := r.Context()
|
c := r.Context()
|
||||||
c = context.WithValue(c, ctx.Request, r)
|
c = context.WithValue(c, ctx.Request, r)
|
||||||
c = context.WithValue(c, ctx.Response, w)
|
c = context.WithValue(c, ctx.Response, w)
|
||||||
|
@ -63,63 +68,55 @@ func (s Handler) resolve(w http.ResponseWriter, r *http.Request) {
|
||||||
|
|
||||||
// create http handler
|
// create http handler
|
||||||
var h http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
var h http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
// should not happen
|
||||||
auth := api.GetAuth(r.Context())
|
auth := api.GetAuth(r.Context())
|
||||||
if auth == nil {
|
if auth == nil {
|
||||||
handleError(api.ErrPermission, w, r)
|
newResponse().WithError(api.ErrPermission).ServeHTTP(w, r)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// reject non granted requests
|
// reject non granted requests
|
||||||
if !auth.Granted() {
|
if !auth.Granted() {
|
||||||
handleError(api.ErrPermission, w, r)
|
newResponse().WithError(api.ErrPermission).ServeHTTP(w, r)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// use context defined in the request
|
// execute the service handler
|
||||||
s.handle(r.Context(), input, handler, service, w, r)
|
s.handle(r.Context(), input, handler, service, w, r)
|
||||||
})
|
})
|
||||||
|
|
||||||
// run middlewares the handler
|
// run contextual middlewares
|
||||||
for _, mw := range s.ctxMiddlewares {
|
for _, mw := range s.ctxMiddlewares {
|
||||||
h = mw(h)
|
h = mw(h)
|
||||||
}
|
}
|
||||||
|
|
||||||
// serve using the context with values
|
// serve using the pre-filled context
|
||||||
h.ServeHTTP(w, r.WithContext(c))
|
h.ServeHTTP(w, r.WithContext(c))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// handle the service request with the associated handler func and respond using
|
||||||
|
// the handler func output
|
||||||
func (s *Handler) handle(c context.Context, input *reqdata.T, handler *apiHandler, service *config.Service, w http.ResponseWriter, r *http.Request) {
|
func (s *Handler) handle(c context.Context, input *reqdata.T, handler *apiHandler, service *config.Service, w http.ResponseWriter, r *http.Request) {
|
||||||
// pass execution to the handler
|
// pass execution to the handler function
|
||||||
var outData, outErr = handler.dyn.Handle(c, input.Data)
|
var outData, outErr = handler.dyn.Handle(c, input.Data)
|
||||||
|
|
||||||
// build response from returned arguments
|
// build response from output arguments
|
||||||
var res = api.EmptyResponse().WithError(outErr)
|
var res = newResponse().WithError(outErr)
|
||||||
for key, value := range outData {
|
for key, value := range outData {
|
||||||
|
|
||||||
// find original name from 'rename' field
|
// find original name from 'rename' field
|
||||||
for name, param := range service.Output {
|
for name, param := range service.Output {
|
||||||
if param.Rename == key {
|
if param.Rename == key {
|
||||||
res.SetData(name, value)
|
res.WithValue(name, value)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 7. apply headers
|
// write response and close request
|
||||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||||
for key, values := range res.Headers {
|
|
||||||
for _, value := range values {
|
|
||||||
w.Header().Add(key, value)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
res.ServeHTTP(w, r)
|
res.ServeHTTP(w, r)
|
||||||
}
|
}
|
||||||
|
|
||||||
func handleError(err api.Err, w http.ResponseWriter, r *http.Request) {
|
|
||||||
var response = api.EmptyResponse().WithError(err)
|
|
||||||
response.ServeHTTP(w, r)
|
|
||||||
}
|
|
||||||
|
|
||||||
func extractInput(service *config.Service, req http.Request) (*reqdata.T, error) {
|
func extractInput(service *config.Service, req http.Request) (*reqdata.T, error) {
|
||||||
var dataset = reqdata.New(service)
|
var dataset = reqdata.New(service)
|
||||||
|
|
||||||
|
|
545
handler_test.go
545
handler_test.go
|
@ -15,7 +15,13 @@ import (
|
||||||
"github.com/xdrm-io/aicra/validator"
|
"github.com/xdrm-io/aicra/validator"
|
||||||
)
|
)
|
||||||
|
|
||||||
func addBuiltinTypes(b *aicra.Builder) error {
|
func printEscaped(raw string) string {
|
||||||
|
raw = strings.ReplaceAll(raw, "\n", "\\n")
|
||||||
|
raw = strings.ReplaceAll(raw, "\r", "\\r")
|
||||||
|
return raw
|
||||||
|
}
|
||||||
|
|
||||||
|
func addDefaultTypes(b *aicra.Builder) error {
|
||||||
if err := b.Validate(validator.AnyType{}); err != nil {
|
if err := b.Validate(validator.AnyType{}); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
@ -37,9 +43,9 @@ func addBuiltinTypes(b *aicra.Builder) error {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestWith(t *testing.T) {
|
func TestHandler_With(t *testing.T) {
|
||||||
builder := &aicra.Builder{}
|
builder := &aicra.Builder{}
|
||||||
if err := addBuiltinTypes(builder); err != nil {
|
if err := addDefaultTypes(builder); err != nil {
|
||||||
t.Fatalf("unexpected error <%v>", err)
|
t.Fatalf("unexpected error <%v>", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -51,13 +57,11 @@ func TestWith(t *testing.T) {
|
||||||
|
|
||||||
middleware := func(next http.Handler) http.Handler {
|
middleware := func(next http.Handler) http.Handler {
|
||||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
newr := r
|
|
||||||
|
|
||||||
// first time -> store 1
|
// first time -> store 1
|
||||||
value := r.Context().Value(key)
|
value := r.Context().Value(key)
|
||||||
if value == nil {
|
if value == nil {
|
||||||
newr = r.WithContext(context.WithValue(r.Context(), key, int(1)))
|
r = r.WithContext(context.WithValue(r.Context(), key, int(1)))
|
||||||
next.ServeHTTP(w, newr)
|
next.ServeHTTP(w, r)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -67,8 +71,8 @@ func TestWith(t *testing.T) {
|
||||||
t.Fatalf("value is not an int")
|
t.Fatalf("value is not an int")
|
||||||
}
|
}
|
||||||
cast++
|
cast++
|
||||||
newr = r.WithContext(context.WithValue(r.Context(), key, cast))
|
r = r.WithContext(context.WithValue(r.Context(), key, cast))
|
||||||
next.ServeHTTP(w, newr)
|
next.ServeHTTP(w, r)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -123,7 +127,7 @@ func TestWith(t *testing.T) {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestWithAuth(t *testing.T) {
|
func TestHandler_WithAuth(t *testing.T) {
|
||||||
|
|
||||||
tt := []struct {
|
tt := []struct {
|
||||||
name string
|
name string
|
||||||
|
@ -208,7 +212,7 @@ func TestWithAuth(t *testing.T) {
|
||||||
for _, tc := range tt {
|
for _, tc := range tt {
|
||||||
t.Run(tc.name, func(t *testing.T) {
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
builder := &aicra.Builder{}
|
builder := &aicra.Builder{}
|
||||||
if err := addBuiltinTypes(builder); err != nil {
|
if err := addDefaultTypes(builder); err != nil {
|
||||||
t.Fatalf("unexpected error <%v>", err)
|
t.Fatalf("unexpected error <%v>", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -276,7 +280,7 @@ func TestWithAuth(t *testing.T) {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestPermissionError(t *testing.T) {
|
func TestHandler_PermissionError(t *testing.T) {
|
||||||
|
|
||||||
tt := []struct {
|
tt := []struct {
|
||||||
name string
|
name string
|
||||||
|
@ -301,7 +305,7 @@ func TestPermissionError(t *testing.T) {
|
||||||
for _, tc := range tt {
|
for _, tc := range tt {
|
||||||
t.Run(tc.name, func(t *testing.T) {
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
builder := &aicra.Builder{}
|
builder := &aicra.Builder{}
|
||||||
if err := addBuiltinTypes(builder); err != nil {
|
if err := addDefaultTypes(builder); err != nil {
|
||||||
t.Fatalf("unexpected error <%v>", err)
|
t.Fatalf("unexpected error <%v>", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -367,7 +371,7 @@ func TestPermissionError(t *testing.T) {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestDynamicScope(t *testing.T) {
|
func TestHandler_DynamicScope(t *testing.T) {
|
||||||
tt := []struct {
|
tt := []struct {
|
||||||
name string
|
name string
|
||||||
manifest string
|
manifest string
|
||||||
|
@ -558,7 +562,7 @@ func TestDynamicScope(t *testing.T) {
|
||||||
for _, tc := range tt {
|
for _, tc := range tt {
|
||||||
t.Run(tc.name, func(t *testing.T) {
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
builder := &aicra.Builder{}
|
builder := &aicra.Builder{}
|
||||||
if err := addBuiltinTypes(builder); err != nil {
|
if err := addDefaultTypes(builder); err != nil {
|
||||||
t.Fatalf("unexpected error <%v>", err)
|
t.Fatalf("unexpected error <%v>", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -621,3 +625,514 @@ func TestDynamicScope(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestHandler_ServiceErrors(t *testing.T) {
|
||||||
|
tt := []struct {
|
||||||
|
name string
|
||||||
|
manifest string
|
||||||
|
// handler
|
||||||
|
hmethod, huri string
|
||||||
|
hfn interface{}
|
||||||
|
// request
|
||||||
|
method, url string
|
||||||
|
contentType string
|
||||||
|
body string
|
||||||
|
permissions []string
|
||||||
|
err api.Err
|
||||||
|
}{
|
||||||
|
// service match
|
||||||
|
{
|
||||||
|
name: "unknown service method",
|
||||||
|
manifest: `[
|
||||||
|
{
|
||||||
|
"method": "GET",
|
||||||
|
"path": "/",
|
||||||
|
"info": "info",
|
||||||
|
"scope": [],
|
||||||
|
"in": {},
|
||||||
|
"out": {}
|
||||||
|
}
|
||||||
|
]`,
|
||||||
|
hmethod: http.MethodGet,
|
||||||
|
huri: "/",
|
||||||
|
hfn: func(context.Context) api.Err {
|
||||||
|
return api.ErrSuccess
|
||||||
|
},
|
||||||
|
method: http.MethodPost,
|
||||||
|
url: "/",
|
||||||
|
body: ``,
|
||||||
|
permissions: []string{},
|
||||||
|
err: api.ErrUnknownService,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "unknown service path",
|
||||||
|
manifest: `[
|
||||||
|
{
|
||||||
|
"method": "GET",
|
||||||
|
"path": "/",
|
||||||
|
"info": "info",
|
||||||
|
"scope": [],
|
||||||
|
"in": {},
|
||||||
|
"out": {}
|
||||||
|
}
|
||||||
|
]`,
|
||||||
|
hmethod: http.MethodGet,
|
||||||
|
huri: "/",
|
||||||
|
hfn: func(context.Context) api.Err {
|
||||||
|
return api.ErrSuccess
|
||||||
|
},
|
||||||
|
method: http.MethodGet,
|
||||||
|
url: "/invalid",
|
||||||
|
body: ``,
|
||||||
|
permissions: []string{},
|
||||||
|
err: api.ErrUnknownService,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "valid empty service",
|
||||||
|
manifest: `[
|
||||||
|
{
|
||||||
|
"method": "GET",
|
||||||
|
"path": "/",
|
||||||
|
"info": "info",
|
||||||
|
"scope": [],
|
||||||
|
"in": {},
|
||||||
|
"out": {}
|
||||||
|
}
|
||||||
|
]`,
|
||||||
|
hmethod: http.MethodGet,
|
||||||
|
huri: "/",
|
||||||
|
hfn: func(context.Context) api.Err {
|
||||||
|
return api.ErrSuccess
|
||||||
|
},
|
||||||
|
method: http.MethodGet,
|
||||||
|
url: "/",
|
||||||
|
body: ``,
|
||||||
|
permissions: []string{},
|
||||||
|
err: api.ErrSuccess,
|
||||||
|
},
|
||||||
|
|
||||||
|
// invalid uri param -> unknown service
|
||||||
|
{
|
||||||
|
name: "invalid uri param",
|
||||||
|
manifest: `[
|
||||||
|
{
|
||||||
|
"method": "GET",
|
||||||
|
"path": "/a/{id}/b",
|
||||||
|
"info": "info",
|
||||||
|
"scope": [],
|
||||||
|
"in": {
|
||||||
|
"{id}": { "info": "info", "type": "int", "name": "ID" }
|
||||||
|
},
|
||||||
|
"out": {}
|
||||||
|
}
|
||||||
|
]`,
|
||||||
|
hmethod: http.MethodGet,
|
||||||
|
huri: "/a/{id}/b",
|
||||||
|
hfn: func(context.Context, struct{ ID int }) api.Err {
|
||||||
|
return api.ErrSuccess
|
||||||
|
},
|
||||||
|
method: http.MethodGet,
|
||||||
|
url: "/a/invalid/b",
|
||||||
|
body: ``,
|
||||||
|
permissions: []string{},
|
||||||
|
err: api.ErrUnknownService,
|
||||||
|
},
|
||||||
|
|
||||||
|
// query param
|
||||||
|
{
|
||||||
|
name: "missing query param",
|
||||||
|
manifest: `[
|
||||||
|
{
|
||||||
|
"method": "GET",
|
||||||
|
"path": "/",
|
||||||
|
"info": "info",
|
||||||
|
"scope": [],
|
||||||
|
"in": {
|
||||||
|
"GET@id": { "info": "info", "type": "int", "name": "ID" }
|
||||||
|
},
|
||||||
|
"out": {}
|
||||||
|
}
|
||||||
|
]`,
|
||||||
|
hmethod: http.MethodGet,
|
||||||
|
huri: "/",
|
||||||
|
hfn: func(context.Context, struct{ ID int }) api.Err {
|
||||||
|
return api.ErrSuccess
|
||||||
|
},
|
||||||
|
method: http.MethodGet,
|
||||||
|
url: "/",
|
||||||
|
body: ``,
|
||||||
|
permissions: []string{},
|
||||||
|
err: api.ErrMissingParam,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "invalid query param",
|
||||||
|
manifest: `[
|
||||||
|
{
|
||||||
|
"method": "GET",
|
||||||
|
"path": "/a",
|
||||||
|
"info": "info",
|
||||||
|
"scope": [],
|
||||||
|
"in": {
|
||||||
|
"GET@id": { "info": "info", "type": "int", "name": "ID" }
|
||||||
|
},
|
||||||
|
"out": {}
|
||||||
|
}
|
||||||
|
]`,
|
||||||
|
hmethod: http.MethodGet,
|
||||||
|
huri: "/a",
|
||||||
|
hfn: func(context.Context, struct{ ID int }) api.Err {
|
||||||
|
return api.ErrSuccess
|
||||||
|
},
|
||||||
|
method: http.MethodGet,
|
||||||
|
url: "/a?id=abc",
|
||||||
|
body: ``,
|
||||||
|
permissions: []string{},
|
||||||
|
err: api.ErrInvalidParam,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "invalid query multi param",
|
||||||
|
manifest: `[
|
||||||
|
{
|
||||||
|
"method": "GET",
|
||||||
|
"path": "/a",
|
||||||
|
"info": "info",
|
||||||
|
"scope": [],
|
||||||
|
"in": {
|
||||||
|
"GET@id": { "info": "info", "type": "int", "name": "ID" }
|
||||||
|
},
|
||||||
|
"out": {}
|
||||||
|
}
|
||||||
|
]`,
|
||||||
|
hmethod: http.MethodGet,
|
||||||
|
huri: "/a",
|
||||||
|
hfn: func(context.Context, struct{ ID int }) api.Err {
|
||||||
|
return api.ErrSuccess
|
||||||
|
},
|
||||||
|
method: http.MethodGet,
|
||||||
|
url: "/a?id=123&id=456",
|
||||||
|
body: ``,
|
||||||
|
permissions: []string{},
|
||||||
|
err: api.ErrInvalidParam,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "valid query param",
|
||||||
|
manifest: `[
|
||||||
|
{
|
||||||
|
"method": "GET",
|
||||||
|
"path": "/a",
|
||||||
|
"info": "info",
|
||||||
|
"scope": [],
|
||||||
|
"in": {
|
||||||
|
"GET@id": { "info": "info", "type": "int", "name": "ID" }
|
||||||
|
},
|
||||||
|
"out": {}
|
||||||
|
}
|
||||||
|
]`,
|
||||||
|
hmethod: http.MethodGet,
|
||||||
|
huri: "/a",
|
||||||
|
hfn: func(context.Context, struct{ ID int }) api.Err {
|
||||||
|
return api.ErrSuccess
|
||||||
|
},
|
||||||
|
method: http.MethodGet,
|
||||||
|
url: "/a?id=123",
|
||||||
|
body: ``,
|
||||||
|
permissions: []string{},
|
||||||
|
err: api.ErrSuccess,
|
||||||
|
},
|
||||||
|
|
||||||
|
// json param
|
||||||
|
{
|
||||||
|
name: "missing json param",
|
||||||
|
manifest: `[
|
||||||
|
{
|
||||||
|
"method": "POST",
|
||||||
|
"path": "/",
|
||||||
|
"info": "info",
|
||||||
|
"scope": [],
|
||||||
|
"in": {
|
||||||
|
"id": { "info": "info", "type": "int", "name": "ID" }
|
||||||
|
},
|
||||||
|
"out": {}
|
||||||
|
}
|
||||||
|
]`,
|
||||||
|
hmethod: http.MethodPost,
|
||||||
|
huri: "/",
|
||||||
|
hfn: func(context.Context, struct{ ID int }) api.Err {
|
||||||
|
return api.ErrSuccess
|
||||||
|
},
|
||||||
|
contentType: "application/json",
|
||||||
|
method: http.MethodPost,
|
||||||
|
url: "/",
|
||||||
|
body: ``,
|
||||||
|
permissions: []string{},
|
||||||
|
err: api.ErrMissingParam,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "invalid json param",
|
||||||
|
manifest: `[
|
||||||
|
{
|
||||||
|
"method": "POST",
|
||||||
|
"path": "/",
|
||||||
|
"info": "info",
|
||||||
|
"scope": [],
|
||||||
|
"in": {
|
||||||
|
"id": { "info": "info", "type": "int", "name": "ID" }
|
||||||
|
},
|
||||||
|
"out": {}
|
||||||
|
}
|
||||||
|
]`,
|
||||||
|
hmethod: http.MethodPost,
|
||||||
|
huri: "/",
|
||||||
|
hfn: func(context.Context, struct{ ID int }) api.Err {
|
||||||
|
return api.ErrSuccess
|
||||||
|
},
|
||||||
|
contentType: "application/json",
|
||||||
|
method: http.MethodPost,
|
||||||
|
url: "/",
|
||||||
|
body: `{ "id": "invalid type" }`,
|
||||||
|
permissions: []string{},
|
||||||
|
err: api.ErrInvalidParam,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "valid json param",
|
||||||
|
manifest: `[
|
||||||
|
{
|
||||||
|
"method": "POST",
|
||||||
|
"path": "/",
|
||||||
|
"info": "info",
|
||||||
|
"scope": [],
|
||||||
|
"in": {
|
||||||
|
"id": { "info": "info", "type": "int", "name": "ID" }
|
||||||
|
},
|
||||||
|
"out": {}
|
||||||
|
}
|
||||||
|
]`,
|
||||||
|
hmethod: http.MethodPost,
|
||||||
|
huri: "/",
|
||||||
|
hfn: func(context.Context, struct{ ID int }) api.Err {
|
||||||
|
return api.ErrSuccess
|
||||||
|
},
|
||||||
|
contentType: "application/json",
|
||||||
|
method: http.MethodPost,
|
||||||
|
url: "/",
|
||||||
|
body: `{ "id": 123 }`,
|
||||||
|
permissions: []string{},
|
||||||
|
err: api.ErrSuccess,
|
||||||
|
},
|
||||||
|
|
||||||
|
// urlencoded param
|
||||||
|
{
|
||||||
|
name: "missing urlencoded param",
|
||||||
|
manifest: `[
|
||||||
|
{
|
||||||
|
"method": "POST",
|
||||||
|
"path": "/",
|
||||||
|
"info": "info",
|
||||||
|
"scope": [],
|
||||||
|
"in": {
|
||||||
|
"id": { "info": "info", "type": "int", "name": "ID" }
|
||||||
|
},
|
||||||
|
"out": {}
|
||||||
|
}
|
||||||
|
]`,
|
||||||
|
hmethod: http.MethodPost,
|
||||||
|
huri: "/",
|
||||||
|
hfn: func(context.Context, struct{ ID int }) api.Err {
|
||||||
|
return api.ErrSuccess
|
||||||
|
},
|
||||||
|
contentType: "application/x-www-form-urlencoded",
|
||||||
|
method: http.MethodPost,
|
||||||
|
url: "/",
|
||||||
|
body: ``,
|
||||||
|
permissions: []string{},
|
||||||
|
err: api.ErrMissingParam,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "invalid urlencoded param",
|
||||||
|
manifest: `[
|
||||||
|
{
|
||||||
|
"method": "POST",
|
||||||
|
"path": "/",
|
||||||
|
"info": "info",
|
||||||
|
"scope": [],
|
||||||
|
"in": {
|
||||||
|
"id": { "info": "info", "type": "int", "name": "ID" }
|
||||||
|
},
|
||||||
|
"out": {}
|
||||||
|
}
|
||||||
|
]`,
|
||||||
|
hmethod: http.MethodPost,
|
||||||
|
huri: "/",
|
||||||
|
hfn: func(context.Context, struct{ ID int }) api.Err {
|
||||||
|
return api.ErrSuccess
|
||||||
|
},
|
||||||
|
contentType: "application/x-www-form-urlencoded",
|
||||||
|
method: http.MethodPost,
|
||||||
|
url: "/",
|
||||||
|
body: `id=abc`,
|
||||||
|
permissions: []string{},
|
||||||
|
err: api.ErrInvalidParam,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "valid urlencoded param",
|
||||||
|
manifest: `[
|
||||||
|
{
|
||||||
|
"method": "POST",
|
||||||
|
"path": "/",
|
||||||
|
"info": "info",
|
||||||
|
"scope": [],
|
||||||
|
"in": {
|
||||||
|
"id": { "info": "info", "type": "int", "name": "ID" }
|
||||||
|
},
|
||||||
|
"out": {}
|
||||||
|
}
|
||||||
|
]`,
|
||||||
|
hmethod: http.MethodPost,
|
||||||
|
huri: "/",
|
||||||
|
hfn: func(context.Context, struct{ ID int }) api.Err {
|
||||||
|
return api.ErrSuccess
|
||||||
|
},
|
||||||
|
contentType: "application/x-www-form-urlencoded",
|
||||||
|
method: http.MethodPost,
|
||||||
|
url: "/",
|
||||||
|
body: `id=123`,
|
||||||
|
permissions: []string{},
|
||||||
|
err: api.ErrSuccess,
|
||||||
|
},
|
||||||
|
|
||||||
|
// formdata param
|
||||||
|
{
|
||||||
|
name: "missing multipart param",
|
||||||
|
manifest: `[
|
||||||
|
{
|
||||||
|
"method": "POST",
|
||||||
|
"path": "/",
|
||||||
|
"info": "info",
|
||||||
|
"scope": [],
|
||||||
|
"in": {
|
||||||
|
"id": { "info": "info", "type": "int", "name": "ID" }
|
||||||
|
},
|
||||||
|
"out": {}
|
||||||
|
}
|
||||||
|
]`,
|
||||||
|
hmethod: http.MethodPost,
|
||||||
|
huri: "/",
|
||||||
|
hfn: func(context.Context, struct{ ID int }) api.Err {
|
||||||
|
return api.ErrSuccess
|
||||||
|
},
|
||||||
|
contentType: "multipart/form-data; boundary=xxx",
|
||||||
|
method: http.MethodPost,
|
||||||
|
url: "/",
|
||||||
|
body: ``,
|
||||||
|
permissions: []string{},
|
||||||
|
err: api.ErrMissingParam,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "invalid multipart param",
|
||||||
|
manifest: `[
|
||||||
|
{
|
||||||
|
"method": "POST",
|
||||||
|
"path": "/",
|
||||||
|
"info": "info",
|
||||||
|
"scope": [],
|
||||||
|
"in": {
|
||||||
|
"id": { "info": "info", "type": "int", "name": "ID" }
|
||||||
|
},
|
||||||
|
"out": {}
|
||||||
|
}
|
||||||
|
]`,
|
||||||
|
hmethod: http.MethodPost,
|
||||||
|
huri: "/",
|
||||||
|
hfn: func(context.Context, struct{ ID int }) api.Err {
|
||||||
|
return api.ErrSuccess
|
||||||
|
},
|
||||||
|
contentType: "multipart/form-data; boundary=xxx",
|
||||||
|
method: http.MethodPost,
|
||||||
|
url: "/",
|
||||||
|
body: `--xxx
|
||||||
|
Content-Disposition: form-data; name="id"
|
||||||
|
|
||||||
|
abc
|
||||||
|
--xxx--`,
|
||||||
|
permissions: []string{},
|
||||||
|
err: api.ErrInvalidParam,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "valid multipart param",
|
||||||
|
manifest: `[
|
||||||
|
{
|
||||||
|
"method": "POST",
|
||||||
|
"path": "/",
|
||||||
|
"info": "info",
|
||||||
|
"scope": [],
|
||||||
|
"in": {
|
||||||
|
"id": { "info": "info", "type": "int", "name": "ID" }
|
||||||
|
},
|
||||||
|
"out": {}
|
||||||
|
}
|
||||||
|
]`,
|
||||||
|
hmethod: http.MethodPost,
|
||||||
|
huri: "/",
|
||||||
|
hfn: func(context.Context, struct{ ID int }) api.Err {
|
||||||
|
return api.ErrSuccess
|
||||||
|
},
|
||||||
|
contentType: "multipart/form-data; boundary=xxx",
|
||||||
|
method: http.MethodPost,
|
||||||
|
url: "/",
|
||||||
|
body: `--xxx
|
||||||
|
Content-Disposition: form-data; name="id"
|
||||||
|
|
||||||
|
123
|
||||||
|
--xxx--`,
|
||||||
|
permissions: []string{},
|
||||||
|
err: api.ErrSuccess,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range tt {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
builder := &aicra.Builder{}
|
||||||
|
if err := addDefaultTypes(builder); err != nil {
|
||||||
|
t.Fatalf("unexpected error <%v>", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
err := builder.Setup(strings.NewReader(tc.manifest))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("setup: unexpected error <%v>", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := builder.Bind(tc.hmethod, tc.huri, tc.hfn); err != nil {
|
||||||
|
t.Fatalf("bind: unexpected error <%v>", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
handler, err := builder.Build()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("build: unexpected error <%v>", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
response = httptest.NewRecorder()
|
||||||
|
body = strings.NewReader(tc.body)
|
||||||
|
request = httptest.NewRequest(tc.method, tc.url, body)
|
||||||
|
)
|
||||||
|
if len(tc.contentType) > 0 {
|
||||||
|
request.Header.Add("Content-Type", tc.contentType)
|
||||||
|
}
|
||||||
|
|
||||||
|
// test request
|
||||||
|
handler.ServeHTTP(response, request)
|
||||||
|
if response.Body == nil {
|
||||||
|
t.Fatalf("response has no body")
|
||||||
|
}
|
||||||
|
|
||||||
|
jsonErr, err := json.Marshal(tc.err)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("cannot marshal expected error: %v", err)
|
||||||
|
}
|
||||||
|
jsonExpected := fmt.Sprintf(`{"error":%s}`, jsonErr)
|
||||||
|
if response.Body.String() != jsonExpected {
|
||||||
|
t.Fatalf("invalid response:\n- actual: %s\n- expect: %s\n", printEscaped(response.Body.String()), printEscaped(jsonExpected))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -18,37 +18,37 @@ type Server struct {
|
||||||
|
|
||||||
// Parse a configuration into a server. Server.Types must be set beforehand to
|
// Parse a configuration into a server. Server.Types must be set beforehand to
|
||||||
// make datatypes available when checking and formatting the read configuration.
|
// make datatypes available when checking and formatting the read configuration.
|
||||||
func (srv *Server) Parse(r io.Reader) error {
|
func (s *Server) Parse(r io.Reader) error {
|
||||||
err := json.NewDecoder(r).Decode(&srv.Services)
|
err := json.NewDecoder(r).Decode(&s.Services)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("%s: %w", errRead, err)
|
return fmt.Errorf("%s: %w", ErrRead, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
err = srv.validate()
|
err = s.validate()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("%s: %w", errFormat, err)
|
return fmt.Errorf("%s: %w", ErrFormat, err)
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// validate implements the validator interface
|
// validate implements the validator interface
|
||||||
func (server Server) validate(datatypes ...validator.Type) error {
|
func (s Server) validate(datatypes ...validator.Type) error {
|
||||||
for _, service := range server.Services {
|
for _, service := range s.Services {
|
||||||
err := service.validate(server.Validators...)
|
err := service.validate(s.Validators...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("%s '%s': %w", service.Method, service.Pattern, err)
|
return fmt.Errorf("%s '%s': %w", service.Method, service.Pattern, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := server.collide(); err != nil {
|
if err := s.collide(); err != nil {
|
||||||
return fmt.Errorf("%s: %w", errFormat, err)
|
return fmt.Errorf("%s: %w", ErrFormat, err)
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Find a service matching an incoming HTTP request
|
// Find a service matching an incoming HTTP request
|
||||||
func (server Server) Find(r *http.Request) *Service {
|
func (s Server) Find(r *http.Request) *Service {
|
||||||
for _, service := range server.Services {
|
for _, service := range s.Services {
|
||||||
if matches := service.Match(r); matches {
|
if matches := service.Match(r); matches {
|
||||||
return service
|
return service
|
||||||
}
|
}
|
||||||
|
@ -62,14 +62,14 @@ func (server Server) Find(r *http.Request) *Service {
|
||||||
// - example 1: `/user/{id}` and `/user/articles` will not collide as {id} is an int and "articles" is not
|
// - example 1: `/user/{id}` and `/user/articles` will not collide as {id} is an int and "articles" is not
|
||||||
// - example 2: `/user/{name}` and `/user/articles` will collide as {name} is a string so as "articles"
|
// - example 2: `/user/{name}` and `/user/articles` will collide as {name} is a string so as "articles"
|
||||||
// - example 3: `/user/{name}` and `/user/{id}` will collide as {name} and {id} cannot be checked against their potential values
|
// - example 3: `/user/{name}` and `/user/{id}` will collide as {name} and {id} cannot be checked against their potential values
|
||||||
func (server *Server) collide() error {
|
func (s *Server) collide() error {
|
||||||
length := len(server.Services)
|
length := len(s.Services)
|
||||||
|
|
||||||
// for each service combination
|
// for each service combination
|
||||||
for a := 0; a < length; a++ {
|
for a := 0; a < length; a++ {
|
||||||
for b := a + 1; b < length; b++ {
|
for b := a + 1; b < length; b++ {
|
||||||
aService := server.Services[a]
|
aService := s.Services[a]
|
||||||
bService := server.Services[b]
|
bService := s.Services[b]
|
||||||
|
|
||||||
if aService.Method != bService.Method {
|
if aService.Method != bService.Method {
|
||||||
continue
|
continue
|
||||||
|
@ -105,14 +105,14 @@ func checkURICollision(uriA, uriB []string, inputA, inputB map[string]*Parameter
|
||||||
|
|
||||||
// both captures -> as we cannot check, consider a collision
|
// both captures -> as we cannot check, consider a collision
|
||||||
if aIsCapture && bIsCapture {
|
if aIsCapture && bIsCapture {
|
||||||
errors = append(errors, fmt.Errorf("%w (path %s and %s)", errPatternCollision, aPart, bPart))
|
errors = append(errors, fmt.Errorf("%w (path %s and %s)", ErrPatternCollision, aPart, bPart))
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
// no capture -> check strict equality
|
// no capture -> check strict equality
|
||||||
if !aIsCapture && !bIsCapture {
|
if !aIsCapture && !bIsCapture {
|
||||||
if aPart == bPart {
|
if aPart == bPart {
|
||||||
errors = append(errors, fmt.Errorf("%w (same path '%s')", errPatternCollision, aPart))
|
errors = append(errors, fmt.Errorf("%w (same path '%s')", ErrPatternCollision, aPart))
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -123,13 +123,13 @@ func checkURICollision(uriA, uriB []string, inputA, inputB map[string]*Parameter
|
||||||
|
|
||||||
// fail if no type or no validator
|
// fail if no type or no validator
|
||||||
if !exists || input.Validator == nil {
|
if !exists || input.Validator == nil {
|
||||||
errors = append(errors, fmt.Errorf("%w (invalid type for %s)", errPatternCollision, aPart))
|
errors = append(errors, fmt.Errorf("%w (invalid type for %s)", ErrPatternCollision, aPart))
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
// fail if not valid
|
// fail if not valid
|
||||||
if _, valid := input.Validator(bPart); valid {
|
if _, valid := input.Validator(bPart); valid {
|
||||||
errors = append(errors, fmt.Errorf("%w (%s captures '%s')", errPatternCollision, aPart, bPart))
|
errors = append(errors, fmt.Errorf("%w (%s captures '%s')", ErrPatternCollision, aPart, bPart))
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -139,13 +139,13 @@ func checkURICollision(uriA, uriB []string, inputA, inputB map[string]*Parameter
|
||||||
|
|
||||||
// fail if no type or no validator
|
// fail if no type or no validator
|
||||||
if !exists || input.Validator == nil {
|
if !exists || input.Validator == nil {
|
||||||
errors = append(errors, fmt.Errorf("%w (invalid type for %s)", errPatternCollision, bPart))
|
errors = append(errors, fmt.Errorf("%w (invalid type for %s)", ErrPatternCollision, bPart))
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
// fail if not valid
|
// fail if not valid
|
||||||
if _, valid := input.Validator(aPart); valid {
|
if _, valid := input.Validator(aPart); valid {
|
||||||
errors = append(errors, fmt.Errorf("%w (%s captures '%s')", errPatternCollision, bPart, aPart))
|
errors = append(errors, fmt.Errorf("%w (%s captures '%s')", ErrPatternCollision, bPart, aPart))
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -21,15 +21,15 @@ func TestLegalServiceName(t *testing.T) {
|
||||||
// empty
|
// empty
|
||||||
{
|
{
|
||||||
`[ { "method": "GET", "info": "a", "path": "" } ]`,
|
`[ { "method": "GET", "info": "a", "path": "" } ]`,
|
||||||
errInvalidPattern,
|
ErrInvalidPattern,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
`[ { "method": "GET", "info": "a", "path": "no-starting-slash" } ]`,
|
`[ { "method": "GET", "info": "a", "path": "no-starting-slash" } ]`,
|
||||||
errInvalidPattern,
|
ErrInvalidPattern,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
`[ { "method": "GET", "info": "a", "path": "ending-slash/" } ]`,
|
`[ { "method": "GET", "info": "a", "path": "ending-slash/" } ]`,
|
||||||
errInvalidPattern,
|
ErrInvalidPattern,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
`[ { "method": "GET", "info": "a", "path": "/" } ]`,
|
`[ { "method": "GET", "info": "a", "path": "/" } ]`,
|
||||||
|
@ -45,35 +45,35 @@ func TestLegalServiceName(t *testing.T) {
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
`[ { "method": "GET", "info": "a", "path": "/invalid/s{braces}" } ]`,
|
`[ { "method": "GET", "info": "a", "path": "/invalid/s{braces}" } ]`,
|
||||||
errInvalidPatternBraceCapture,
|
ErrInvalidPatternBraceCapture,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
`[ { "method": "GET", "info": "a", "path": "/invalid/{braces}a" } ]`,
|
`[ { "method": "GET", "info": "a", "path": "/invalid/{braces}a" } ]`,
|
||||||
errInvalidPatternBraceCapture,
|
ErrInvalidPatternBraceCapture,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
`[ { "method": "GET", "info": "a", "path": "/invalid/{braces}" } ]`,
|
`[ { "method": "GET", "info": "a", "path": "/invalid/{braces}" } ]`,
|
||||||
errUndefinedBraceCapture,
|
ErrUndefinedBraceCapture,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
`[ { "method": "GET", "info": "a", "path": "/invalid/s{braces}/abc" } ]`,
|
`[ { "method": "GET", "info": "a", "path": "/invalid/s{braces}/abc" } ]`,
|
||||||
errInvalidPatternBraceCapture,
|
ErrInvalidPatternBraceCapture,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
`[ { "method": "GET", "info": "a", "path": "/invalid/{braces}s/abc" } ]`,
|
`[ { "method": "GET", "info": "a", "path": "/invalid/{braces}s/abc" } ]`,
|
||||||
errInvalidPatternBraceCapture,
|
ErrInvalidPatternBraceCapture,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
`[ { "method": "GET", "info": "a", "path": "/invalid/{braces}/abc" } ]`,
|
`[ { "method": "GET", "info": "a", "path": "/invalid/{braces}/abc" } ]`,
|
||||||
errUndefinedBraceCapture,
|
ErrUndefinedBraceCapture,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
`[ { "method": "GET", "info": "a", "path": "/invalid/{b{races}s/abc" } ]`,
|
`[ { "method": "GET", "info": "a", "path": "/invalid/{b{races}s/abc" } ]`,
|
||||||
errInvalidPatternBraceCapture,
|
ErrInvalidPatternBraceCapture,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
`[ { "method": "GET", "info": "a", "path": "/invalid/{braces}/}abc" } ]`,
|
`[ { "method": "GET", "info": "a", "path": "/invalid/{braces}/}abc" } ]`,
|
||||||
errInvalidPatternBraceCapture,
|
ErrInvalidPatternBraceCapture,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -143,8 +143,8 @@ func TestAvailableMethods(t *testing.T) {
|
||||||
t.FailNow()
|
t.FailNow()
|
||||||
}
|
}
|
||||||
|
|
||||||
if !test.ValidMethod && !errors.Is(err, errUnknownMethod) {
|
if !test.ValidMethod && !errors.Is(err, ErrUnknownMethod) {
|
||||||
t.Errorf("expected error <%s> got <%s>", errUnknownMethod, err)
|
t.Errorf("expected error <%s> got <%s>", ErrUnknownMethod, err)
|
||||||
t.FailNow()
|
t.FailNow()
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
@ -184,7 +184,7 @@ func TestParseMissingMethodDescription(t *testing.T) {
|
||||||
`[ { "method": "GET", "path": "/" }]`,
|
`[ { "method": "GET", "path": "/" }]`,
|
||||||
false,
|
false,
|
||||||
},
|
},
|
||||||
{ // missing description
|
{ // missing descriptiontype
|
||||||
`[ { "method": "GET", "path": "/subservice" }]`,
|
`[ { "method": "GET", "path": "/subservice" }]`,
|
||||||
false,
|
false,
|
||||||
},
|
},
|
||||||
|
@ -217,8 +217,8 @@ func TestParseMissingMethodDescription(t *testing.T) {
|
||||||
t.FailNow()
|
t.FailNow()
|
||||||
}
|
}
|
||||||
|
|
||||||
if !test.ValidDescription && !errors.Is(err, errMissingDescription) {
|
if !test.ValidDescription && !errors.Is(err, ErrMissingDescription) {
|
||||||
t.Errorf("expected error <%s> got <%s>", errMissingDescription, err)
|
t.Errorf("expected error <%s> got <%s>", ErrMissingDescription, err)
|
||||||
t.FailNow()
|
t.FailNow()
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
@ -321,7 +321,7 @@ func TestParseParameters(t *testing.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
]`,
|
]`,
|
||||||
errMissingParamDesc,
|
ErrMissingParamDesc,
|
||||||
},
|
},
|
||||||
{ // invalid param name suffix
|
{ // invalid param name suffix
|
||||||
`[
|
`[
|
||||||
|
@ -334,7 +334,7 @@ func TestParseParameters(t *testing.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
]`,
|
]`,
|
||||||
errMissingParamDesc,
|
ErrMissingParamDesc,
|
||||||
},
|
},
|
||||||
|
|
||||||
{ // missing param description
|
{ // missing param description
|
||||||
|
@ -348,7 +348,7 @@ func TestParseParameters(t *testing.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
]`,
|
]`,
|
||||||
errMissingParamDesc,
|
ErrMissingParamDesc,
|
||||||
},
|
},
|
||||||
{ // empty param description
|
{ // empty param description
|
||||||
`[
|
`[
|
||||||
|
@ -361,7 +361,7 @@ func TestParseParameters(t *testing.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
]`,
|
]`,
|
||||||
errMissingParamDesc,
|
ErrMissingParamDesc,
|
||||||
},
|
},
|
||||||
|
|
||||||
{ // missing param type
|
{ // missing param type
|
||||||
|
@ -375,7 +375,7 @@ func TestParseParameters(t *testing.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
]`,
|
]`,
|
||||||
errMissingParamType,
|
ErrMissingParamType,
|
||||||
},
|
},
|
||||||
{ // empty param type
|
{ // empty param type
|
||||||
`[
|
`[
|
||||||
|
@ -388,7 +388,7 @@ func TestParseParameters(t *testing.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
]`,
|
]`,
|
||||||
errMissingParamType,
|
ErrMissingParamType,
|
||||||
},
|
},
|
||||||
{ // invalid type (optional mark only)
|
{ // invalid type (optional mark only)
|
||||||
`[
|
`[
|
||||||
|
@ -402,7 +402,7 @@ func TestParseParameters(t *testing.T) {
|
||||||
}
|
}
|
||||||
]`,
|
]`,
|
||||||
|
|
||||||
errMissingParamType,
|
ErrMissingParamType,
|
||||||
},
|
},
|
||||||
{ // valid description + valid type
|
{ // valid description + valid type
|
||||||
`[
|
`[
|
||||||
|
@ -444,7 +444,7 @@ func TestParseParameters(t *testing.T) {
|
||||||
}
|
}
|
||||||
]`,
|
]`,
|
||||||
// 2 possible errors as map order is not deterministic
|
// 2 possible errors as map order is not deterministic
|
||||||
errParamNameConflict,
|
ErrParamNameConflict,
|
||||||
},
|
},
|
||||||
{ // rename conflict with name
|
{ // rename conflict with name
|
||||||
`[
|
`[
|
||||||
|
@ -459,7 +459,7 @@ func TestParseParameters(t *testing.T) {
|
||||||
}
|
}
|
||||||
]`,
|
]`,
|
||||||
// 2 possible errors as map order is not deterministic
|
// 2 possible errors as map order is not deterministic
|
||||||
errParamNameConflict,
|
ErrParamNameConflict,
|
||||||
},
|
},
|
||||||
{ // rename conflict with rename
|
{ // rename conflict with rename
|
||||||
`[
|
`[
|
||||||
|
@ -474,7 +474,7 @@ func TestParseParameters(t *testing.T) {
|
||||||
}
|
}
|
||||||
]`,
|
]`,
|
||||||
// 2 possible errors as map order is not deterministic
|
// 2 possible errors as map order is not deterministic
|
||||||
errParamNameConflict,
|
ErrParamNameConflict,
|
||||||
},
|
},
|
||||||
|
|
||||||
{ // both renamed with no conflict
|
{ // both renamed with no conflict
|
||||||
|
@ -503,7 +503,7 @@ func TestParseParameters(t *testing.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
]`,
|
]`,
|
||||||
errMandatoryRename,
|
ErrMandatoryRename,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
`[
|
`[
|
||||||
|
@ -516,7 +516,7 @@ func TestParseParameters(t *testing.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
]`,
|
]`,
|
||||||
errMandatoryRename,
|
ErrMandatoryRename,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
`[
|
`[
|
||||||
|
@ -556,7 +556,7 @@ func TestParseParameters(t *testing.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
]`,
|
]`,
|
||||||
errIllegalOptionalURIParam,
|
ErrIllegalOptionalURIParam,
|
||||||
},
|
},
|
||||||
{ // URI parameter not specified
|
{ // URI parameter not specified
|
||||||
`[
|
`[
|
||||||
|
@ -569,7 +569,7 @@ func TestParseParameters(t *testing.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
]`,
|
]`,
|
||||||
errUnspecifiedBraceCapture,
|
ErrUnspecifiedBraceCapture,
|
||||||
},
|
},
|
||||||
{ // URI parameter not defined
|
{ // URI parameter not defined
|
||||||
`[
|
`[
|
||||||
|
@ -580,7 +580,7 @@ func TestParseParameters(t *testing.T) {
|
||||||
"in": { }
|
"in": { }
|
||||||
}
|
}
|
||||||
]`,
|
]`,
|
||||||
errUndefinedBraceCapture,
|
ErrUndefinedBraceCapture,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -637,7 +637,7 @@ func TestServiceCollision(t *testing.T) {
|
||||||
"info": "info", "in": {}
|
"info": "info", "in": {}
|
||||||
}
|
}
|
||||||
]`,
|
]`,
|
||||||
errPatternCollision,
|
ErrPatternCollision,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
`[
|
`[
|
||||||
|
@ -672,7 +672,7 @@ func TestServiceCollision(t *testing.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
]`,
|
]`,
|
||||||
errPatternCollision,
|
ErrPatternCollision,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
`[
|
`[
|
||||||
|
@ -698,7 +698,7 @@ func TestServiceCollision(t *testing.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
]`,
|
]`,
|
||||||
errPatternCollision,
|
ErrPatternCollision,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
`[
|
`[
|
||||||
|
@ -711,7 +711,7 @@ func TestServiceCollision(t *testing.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
]`,
|
]`,
|
||||||
errPatternCollision,
|
ErrPatternCollision,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
`[
|
`[
|
||||||
|
@ -750,7 +750,7 @@ func TestServiceCollision(t *testing.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
]`,
|
]`,
|
||||||
errPatternCollision,
|
ErrPatternCollision,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
`[
|
`[
|
||||||
|
@ -789,7 +789,7 @@ func TestServiceCollision(t *testing.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
]`,
|
]`,
|
||||||
errPatternCollision,
|
ErrPatternCollision,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
`[
|
`[
|
||||||
|
@ -804,7 +804,7 @@ func TestServiceCollision(t *testing.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
]`,
|
]`,
|
||||||
errPatternCollision,
|
ErrPatternCollision,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
`[
|
`[
|
||||||
|
|
|
@ -1,59 +1,61 @@
|
||||||
package config
|
package config
|
||||||
|
|
||||||
// cerr allows you to create constant "const" error with type boxing.
|
// Err allows you to create constant "const" error with type boxing.
|
||||||
type cerr string
|
type Err string
|
||||||
|
|
||||||
func (err cerr) Error() string {
|
func (err Err) Error() string {
|
||||||
return string(err)
|
return string(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// errRead - read error
|
const (
|
||||||
const errRead = cerr("cannot read config")
|
// ErrRead - read error
|
||||||
|
ErrRead = Err("cannot read config")
|
||||||
|
|
||||||
// errUnknownMethod - unknown http method
|
// ErrUnknownMethod - unknown http method
|
||||||
const errUnknownMethod = cerr("unknown HTTP method")
|
ErrUnknownMethod = Err("unknown HTTP method")
|
||||||
|
|
||||||
// errFormat - invalid format
|
// ErrFormat - invalid format
|
||||||
const errFormat = cerr("invalid config format")
|
ErrFormat = Err("invalid config format")
|
||||||
|
|
||||||
// errPatternCollision - collision between 2 services' patterns
|
// ErrPatternCollision - collision between 2 services' patterns
|
||||||
const errPatternCollision = cerr("pattern collision")
|
ErrPatternCollision = Err("pattern collision")
|
||||||
|
|
||||||
// errInvalidPattern - malformed service pattern
|
// ErrInvalidPattern - malformed service pattern
|
||||||
const errInvalidPattern = cerr("malformed service path: must begin with a '/' and not end with")
|
ErrInvalidPattern = Err("malformed service path: must begin with a '/' and not end with")
|
||||||
|
|
||||||
// errInvalidPatternBraceCapture - invalid brace capture
|
// ErrInvalidPatternBraceCapture - invalid brace capture
|
||||||
const errInvalidPatternBraceCapture = cerr("invalid uri parameter")
|
ErrInvalidPatternBraceCapture = Err("invalid uri parameter")
|
||||||
|
|
||||||
// errUnspecifiedBraceCapture - missing path brace capture
|
// ErrUnspecifiedBraceCapture - missing path brace capture
|
||||||
const errUnspecifiedBraceCapture = cerr("missing uri parameter")
|
ErrUnspecifiedBraceCapture = Err("missing uri parameter")
|
||||||
|
|
||||||
// errUndefinedBraceCapture - missing capturing brace definition
|
// ErrUndefinedBraceCapture - missing capturing brace definition
|
||||||
const errUndefinedBraceCapture = cerr("missing uri parameter definition")
|
ErrUndefinedBraceCapture = Err("missing uri parameter definition")
|
||||||
|
|
||||||
// errMandatoryRename - capture/query parameters must be renamed
|
// ErrMandatoryRename - capture/query parameters must be renamed
|
||||||
const errMandatoryRename = cerr("uri and query parameters must be renamed")
|
ErrMandatoryRename = Err("uri and query parameters must be renamed")
|
||||||
|
|
||||||
// errMissingDescription - a service is missing its description
|
// ErrMissingDescription - a service is missing its description
|
||||||
const errMissingDescription = cerr("missing description")
|
ErrMissingDescription = Err("missing description")
|
||||||
|
|
||||||
// errIllegalOptionalURIParam - uri parameter cannot optional
|
// ErrIllegalOptionalURIParam - uri parameter cannot optional
|
||||||
const errIllegalOptionalURIParam = cerr("uri parameter cannot be optional")
|
ErrIllegalOptionalURIParam = Err("uri parameter cannot be optional")
|
||||||
|
|
||||||
// errOptionalOption - cannot have optional output
|
// ErrOptionalOption - cannot have optional output
|
||||||
const errOptionalOption = cerr("output cannot be optional")
|
ErrOptionalOption = Err("output cannot be optional")
|
||||||
|
|
||||||
// errMissingParamDesc - missing parameter description
|
// ErrMissingParamDesc - missing parameter description
|
||||||
const errMissingParamDesc = cerr("missing parameter description")
|
ErrMissingParamDesc = Err("missing parameter description")
|
||||||
|
|
||||||
// errUnknownDataType - unknown parameter datatype
|
// ErrUnknownParamType - unknown parameter type
|
||||||
const errUnknownDataType = cerr("unknown parameter datatype")
|
ErrUnknownParamType = Err("unknown parameter datatype")
|
||||||
|
|
||||||
// errIllegalParamName - illegal parameter name
|
// ErrIllegalParamName - illegal parameter name
|
||||||
const errIllegalParamName = cerr("illegal parameter name")
|
ErrIllegalParamName = Err("illegal parameter name")
|
||||||
|
|
||||||
// errMissingParamType - missing parameter type
|
// ErrMissingParamType - missing parameter type
|
||||||
const errMissingParamType = cerr("missing parameter type")
|
ErrMissingParamType = Err("missing parameter type")
|
||||||
|
|
||||||
// errParamNameConflict - name/rename conflict
|
// ErrParamNameConflict - name/rename conflict
|
||||||
const errParamNameConflict = cerr("parameter name conflict")
|
ErrParamNameConflict = Err("parameter name conflict")
|
||||||
|
)
|
||||||
|
|
|
@ -20,11 +20,11 @@ type Parameter struct {
|
||||||
|
|
||||||
func (param *Parameter) validate(datatypes ...validator.Type) error {
|
func (param *Parameter) validate(datatypes ...validator.Type) error {
|
||||||
if len(param.Description) < 1 {
|
if len(param.Description) < 1 {
|
||||||
return errMissingParamDesc
|
return ErrMissingParamDesc
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(param.Type) < 1 || param.Type == "?" {
|
if len(param.Type) < 1 || param.Type == "?" {
|
||||||
return errMissingParamType
|
return ErrMissingParamType
|
||||||
}
|
}
|
||||||
|
|
||||||
// optional type
|
// optional type
|
||||||
|
@ -42,7 +42,7 @@ func (param *Parameter) validate(datatypes ...validator.Type) error {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if param.Validator == nil {
|
if param.Validator == nil {
|
||||||
return errUnknownDataType
|
return ErrUnknownParamType
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
|
@ -9,9 +9,11 @@ import (
|
||||||
"github.com/xdrm-io/aicra/validator"
|
"github.com/xdrm-io/aicra/validator"
|
||||||
)
|
)
|
||||||
|
|
||||||
var braceRegex = regexp.MustCompile(`^{([a-z_-]+)}$`)
|
var (
|
||||||
var queryRegex = regexp.MustCompile(`^GET@([a-z_-]+)$`)
|
captureRegex = regexp.MustCompile(`^{([a-z_-]+)}$`)
|
||||||
var availableHTTPMethods = []string{http.MethodGet, http.MethodPost, http.MethodPut, http.MethodDelete}
|
queryRegex = regexp.MustCompile(`^GET@([a-z_-]+)$`)
|
||||||
|
availableHTTPMethods = []string{http.MethodGet, http.MethodPost, http.MethodPut, http.MethodDelete}
|
||||||
|
)
|
||||||
|
|
||||||
// Service definition
|
// Service definition
|
||||||
type Service struct {
|
type Service struct {
|
||||||
|
@ -43,19 +45,25 @@ type BraceCapture struct {
|
||||||
|
|
||||||
// Match returns if this service would handle this HTTP request
|
// Match returns if this service would handle this HTTP request
|
||||||
func (svc *Service) Match(req *http.Request) bool {
|
func (svc *Service) Match(req *http.Request) bool {
|
||||||
if req.Method != svc.Method {
|
var (
|
||||||
return false
|
uri = req.RequestURI
|
||||||
|
queryIndex = strings.IndexByte(uri, '?')
|
||||||
|
)
|
||||||
|
|
||||||
|
// remove query part for matching the pattern
|
||||||
|
if queryIndex > -1 {
|
||||||
|
uri = uri[:queryIndex]
|
||||||
}
|
}
|
||||||
if !svc.matchPattern(req.RequestURI) {
|
|
||||||
return false
|
return req.Method == svc.Method && svc.matchPattern(uri)
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// checks if an uri matches the service's pattern
|
// checks if an uri matches the service's pattern
|
||||||
func (svc *Service) matchPattern(uri string) bool {
|
func (svc *Service) matchPattern(uri string) bool {
|
||||||
uriparts := SplitURL(uri)
|
var (
|
||||||
parts := SplitURL(svc.Pattern)
|
uriparts = SplitURL(uri)
|
||||||
|
parts = SplitURL(svc.Pattern)
|
||||||
|
)
|
||||||
|
|
||||||
if len(uriparts) != len(parts) {
|
if len(uriparts) != len(parts) {
|
||||||
return false
|
return false
|
||||||
|
@ -98,39 +106,34 @@ func (svc *Service) matchPattern(uri string) bool {
|
||||||
|
|
||||||
// Validate implements the validator interface
|
// Validate implements the validator interface
|
||||||
func (svc *Service) validate(datatypes ...validator.Type) error {
|
func (svc *Service) validate(datatypes ...validator.Type) error {
|
||||||
// check method
|
err := svc.checkMethod()
|
||||||
err := svc.isMethodAvailable()
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("field 'method': %w", err)
|
return fmt.Errorf("field 'method': %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// check pattern
|
|
||||||
svc.Pattern = strings.Trim(svc.Pattern, " \t\r\n")
|
svc.Pattern = strings.Trim(svc.Pattern, " \t\r\n")
|
||||||
err = svc.isPatternValid()
|
err = svc.checkPattern()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("field 'path': %w", err)
|
return fmt.Errorf("field 'path': %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// check description
|
|
||||||
if len(strings.Trim(svc.Description, " \t\r\n")) < 1 {
|
if len(strings.Trim(svc.Description, " \t\r\n")) < 1 {
|
||||||
return fmt.Errorf("field 'description': %w", errMissingDescription)
|
return fmt.Errorf("field 'description': %w", ErrMissingDescription)
|
||||||
}
|
}
|
||||||
|
|
||||||
// check input parameters
|
err = svc.checkInput(datatypes)
|
||||||
err = svc.validateInput(datatypes)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("field 'in': %w", err)
|
return fmt.Errorf("field 'in': %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// fail if a brace capture remains undefined
|
// fail when a brace capture remains undefined
|
||||||
for _, capture := range svc.Captures {
|
for _, capture := range svc.Captures {
|
||||||
if capture.Ref == nil {
|
if capture.Ref == nil {
|
||||||
return fmt.Errorf("field 'in': %s: %w", capture.Name, errUndefinedBraceCapture)
|
return fmt.Errorf("field 'in': %s: %w", capture.Name, ErrUndefinedBraceCapture)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// check output
|
err = svc.checkOutput(datatypes)
|
||||||
err = svc.validateOutput(datatypes)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("field 'out': %w", err)
|
return fmt.Errorf("field 'out': %w", err)
|
||||||
}
|
}
|
||||||
|
@ -138,27 +141,34 @@ func (svc *Service) validate(datatypes ...validator.Type) error {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (svc *Service) isMethodAvailable() error {
|
func (svc *Service) checkMethod() error {
|
||||||
for _, available := range availableHTTPMethods {
|
for _, available := range availableHTTPMethods {
|
||||||
if svc.Method == available {
|
if svc.Method == available {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return errUnknownMethod
|
return ErrUnknownMethod
|
||||||
}
|
}
|
||||||
|
|
||||||
func (svc *Service) isPatternValid() error {
|
// checkPattern checks for the validity of the pattern definition (i.e. the uri)
|
||||||
|
//
|
||||||
|
// Note that the uri can contain capture params e.g. `/a/{b}/c/{d}`, in this
|
||||||
|
// example, input parameters with names `{b}` and `{d}` are expected.
|
||||||
|
//
|
||||||
|
// This methods sets up the service state with adding capture params that are
|
||||||
|
// expected; checkInputs() will be able to check params agains pattern captures.
|
||||||
|
func (svc *Service) checkPattern() error {
|
||||||
length := len(svc.Pattern)
|
length := len(svc.Pattern)
|
||||||
|
|
||||||
// empty pattern
|
// empty pattern
|
||||||
if length < 1 {
|
if length < 1 {
|
||||||
return errInvalidPattern
|
return ErrInvalidPattern
|
||||||
}
|
}
|
||||||
|
|
||||||
if length > 1 {
|
if length > 1 {
|
||||||
// pattern not starting with '/' or ending with '/'
|
// pattern not starting with '/' or ending with '/'
|
||||||
if svc.Pattern[0] != '/' || svc.Pattern[length-1] == '/' {
|
if svc.Pattern[0] != '/' || svc.Pattern[length-1] == '/' {
|
||||||
return errInvalidPattern
|
return ErrInvalidPattern
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -166,11 +176,11 @@ func (svc *Service) isPatternValid() error {
|
||||||
parts := SplitURL(svc.Pattern)
|
parts := SplitURL(svc.Pattern)
|
||||||
for i, part := range parts {
|
for i, part := range parts {
|
||||||
if len(part) < 1 {
|
if len(part) < 1 {
|
||||||
return errInvalidPattern
|
return ErrInvalidPattern
|
||||||
}
|
}
|
||||||
|
|
||||||
// if brace capture
|
// if brace capture
|
||||||
if matches := braceRegex.FindAllStringSubmatch(part, -1); len(matches) > 0 && len(matches[0]) > 1 {
|
if matches := captureRegex.FindAllStringSubmatch(part, -1); len(matches) > 0 && len(matches[0]) > 1 {
|
||||||
braceName := matches[0][1]
|
braceName := matches[0][1]
|
||||||
|
|
||||||
// append
|
// append
|
||||||
|
@ -187,149 +197,185 @@ func (svc *Service) isPatternValid() error {
|
||||||
|
|
||||||
// fail on invalid format
|
// fail on invalid format
|
||||||
if strings.ContainsAny(part, "{}") {
|
if strings.ContainsAny(part, "{}") {
|
||||||
return errInvalidPatternBraceCapture
|
return ErrInvalidPatternBraceCapture
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (svc *Service) validateInput(types []validator.Type) error {
|
func (svc *Service) checkInput(types []validator.Type) error {
|
||||||
|
// no parameter
|
||||||
// ignore no parameter
|
|
||||||
if svc.Input == nil || len(svc.Input) < 1 {
|
if svc.Input == nil || len(svc.Input) < 1 {
|
||||||
svc.Input = make(map[string]*Parameter, 0)
|
svc.Input = map[string]*Parameter{}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// for each parameter
|
// for each parameter
|
||||||
for paramName, param := range svc.Input {
|
for name, p := range svc.Input {
|
||||||
if len(paramName) < 1 {
|
if len(name) < 1 {
|
||||||
return fmt.Errorf("%s: %w", paramName, errIllegalParamName)
|
return fmt.Errorf("%s: %w", name, ErrIllegalParamName)
|
||||||
}
|
}
|
||||||
|
|
||||||
// fail if brace capture does not exists in pattern
|
// parse parameters: capture (uri), query or form and update the service
|
||||||
var iscapture, isquery bool
|
// attributes accordingly
|
||||||
if matches := braceRegex.FindAllStringSubmatch(paramName, -1); len(matches) > 0 && len(matches[0]) > 1 {
|
ptype, err := svc.parseParam(name, p)
|
||||||
braceName := matches[0][1]
|
|
||||||
|
|
||||||
found := false
|
|
||||||
for _, capture := range svc.Captures {
|
|
||||||
if capture.Name == braceName {
|
|
||||||
capture.Ref = param
|
|
||||||
found = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !found {
|
|
||||||
return fmt.Errorf("%s: %w", paramName, errUnspecifiedBraceCapture)
|
|
||||||
}
|
|
||||||
iscapture = true
|
|
||||||
|
|
||||||
} else if matches := queryRegex.FindAllStringSubmatch(paramName, -1); len(matches) > 0 && len(matches[0]) > 1 {
|
|
||||||
|
|
||||||
queryName := matches[0][1]
|
|
||||||
|
|
||||||
// init map
|
|
||||||
if svc.Query == nil {
|
|
||||||
svc.Query = make(map[string]*Parameter)
|
|
||||||
}
|
|
||||||
svc.Query[queryName] = param
|
|
||||||
isquery = true
|
|
||||||
} else {
|
|
||||||
if svc.Form == nil {
|
|
||||||
svc.Form = make(map[string]*Parameter)
|
|
||||||
}
|
|
||||||
svc.Form[paramName] = param
|
|
||||||
}
|
|
||||||
|
|
||||||
// fail if capture or query without rename
|
|
||||||
if len(param.Rename) < 1 && (iscapture || isquery) {
|
|
||||||
return fmt.Errorf("%s: %w", paramName, errMandatoryRename)
|
|
||||||
}
|
|
||||||
|
|
||||||
// use param name if no rename
|
|
||||||
if len(param.Rename) < 1 {
|
|
||||||
param.Rename = paramName
|
|
||||||
}
|
|
||||||
|
|
||||||
err := param.validate(types...)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("%s: %w", paramName, err)
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rename mandatory for capture and query
|
||||||
|
if len(p.Rename) < 1 && (ptype == captureParam || ptype == queryParam) {
|
||||||
|
return fmt.Errorf("%s: %w", name, ErrMandatoryRename)
|
||||||
|
}
|
||||||
|
|
||||||
|
// fallback to name when Rename is not provided
|
||||||
|
if len(p.Rename) < 1 {
|
||||||
|
p.Rename = name
|
||||||
|
}
|
||||||
|
|
||||||
|
err = p.validate(types...)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("%s: %w", name, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// capture parameter cannot be optional
|
// capture parameter cannot be optional
|
||||||
if iscapture && param.Optional {
|
if p.Optional && ptype == captureParam {
|
||||||
return fmt.Errorf("%s: %w", paramName, errIllegalOptionalURIParam)
|
return fmt.Errorf("%s: %w", name, ErrIllegalOptionalURIParam)
|
||||||
}
|
}
|
||||||
|
|
||||||
// fail on name/rename conflict
|
err = nameConflicts(name, p, svc.Input)
|
||||||
for paramName2, param2 := range svc.Input {
|
if err != nil {
|
||||||
// ignore self
|
return err
|
||||||
if paramName == paramName2 {
|
|
||||||
continue
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3.2.1. Same rename field
|
|
||||||
// 3.2.2. Not-renamed field matches a renamed field
|
|
||||||
// 3.2.3. Renamed field matches name
|
|
||||||
if param.Rename == param2.Rename || paramName == param2.Rename || paramName2 == param.Rename {
|
|
||||||
return fmt.Errorf("%s: %w", paramName, errParamNameConflict)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (svc *Service) validateOutput(types []validator.Type) error {
|
func (svc *Service) checkOutput(types []validator.Type) error {
|
||||||
|
// no parameter
|
||||||
// ignore no parameter
|
|
||||||
if svc.Output == nil || len(svc.Output) < 1 {
|
if svc.Output == nil || len(svc.Output) < 1 {
|
||||||
svc.Output = make(map[string]*Parameter, 0)
|
svc.Output = make(map[string]*Parameter, 0)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// for each parameter
|
for name, p := range svc.Output {
|
||||||
for paramName, param := range svc.Output {
|
if len(name) < 1 {
|
||||||
if len(paramName) < 1 {
|
return fmt.Errorf("%s: %w", name, ErrIllegalParamName)
|
||||||
return fmt.Errorf("%s: %w", paramName, errIllegalParamName)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// use param name if no rename
|
// fallback to name when Rename is not provided
|
||||||
if len(param.Rename) < 1 {
|
if len(p.Rename) < 1 {
|
||||||
param.Rename = paramName
|
p.Rename = name
|
||||||
}
|
}
|
||||||
|
|
||||||
err := param.validate(types...)
|
err := p.validate(types...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("%s: %w", paramName, err)
|
return fmt.Errorf("%s: %w", name, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if param.Optional {
|
if p.Optional {
|
||||||
return fmt.Errorf("%s: %w", paramName, errOptionalOption)
|
return fmt.Errorf("%s: %w", name, ErrOptionalOption)
|
||||||
}
|
}
|
||||||
|
|
||||||
// fail on name/rename conflict
|
err = nameConflicts(name, p, svc.Output)
|
||||||
for paramName2, param2 := range svc.Output {
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type paramType int
|
||||||
|
|
||||||
|
const (
|
||||||
|
captureParam paramType = iota
|
||||||
|
queryParam
|
||||||
|
formParam
|
||||||
|
)
|
||||||
|
|
||||||
|
// parseParam determines which param type it is from its name:
|
||||||
|
// - `{paramName}` is an capture; it captures a segment of the uri defined in
|
||||||
|
// the pattern definition, e.g. `/some/path/with/{paramName}/somewhere`
|
||||||
|
// - `GET@paramName` is an uri query that is received from the http query format
|
||||||
|
// in the uri, e.g. `http://domain.com/uri?paramName=paramValue¶m2=value2`
|
||||||
|
// - any other name that contains valid characters is considered a Form
|
||||||
|
// parameter; it is extracted from the http request's body as: json, multipart
|
||||||
|
// or using the x-www-form-urlencoded format.
|
||||||
|
//
|
||||||
|
// Special notes:
|
||||||
|
// - capture params MUST be found in the pattern definition.
|
||||||
|
// - capture params MUST NOT be optional as they are in the pattern anyways.
|
||||||
|
// - capture and query params MUST be renamed because the `{param}` or
|
||||||
|
// `GET@param` name formats cannot be translated to a valid go exported name.
|
||||||
|
// c.f. the `dynfunc` package that creates a handler func() signature from
|
||||||
|
// the service definitions (i.e. input and output parameters).
|
||||||
|
func (svc *Service) parseParam(name string, p *Parameter) (paramType, error) {
|
||||||
|
var (
|
||||||
|
captureMatches = captureRegex.FindAllStringSubmatch(name, -1)
|
||||||
|
isCapture = len(captureMatches) > 0 && len(captureMatches[0]) > 1
|
||||||
|
)
|
||||||
|
|
||||||
|
// Parameter is a capture (uri/{param})
|
||||||
|
if isCapture {
|
||||||
|
captureName := captureMatches[0][1]
|
||||||
|
|
||||||
|
// fail if brace capture does not exists in pattern
|
||||||
|
found := false
|
||||||
|
for _, capture := range svc.Captures {
|
||||||
|
if capture.Name == captureName {
|
||||||
|
capture.Ref = p
|
||||||
|
found = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !found {
|
||||||
|
return captureParam, fmt.Errorf("%s: %w", name, ErrUnspecifiedBraceCapture)
|
||||||
|
}
|
||||||
|
return captureParam, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
queryMatches = queryRegex.FindAllStringSubmatch(name, -1)
|
||||||
|
isQuery = len(queryMatches) > 0 && len(queryMatches[0]) > 1
|
||||||
|
)
|
||||||
|
|
||||||
|
// Parameter is a query (uri?param)
|
||||||
|
if isQuery {
|
||||||
|
queryName := queryMatches[0][1]
|
||||||
|
|
||||||
|
// init map
|
||||||
|
if svc.Query == nil {
|
||||||
|
svc.Query = make(map[string]*Parameter)
|
||||||
|
}
|
||||||
|
svc.Query[queryName] = p
|
||||||
|
|
||||||
|
return queryParam, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parameter is a form param
|
||||||
|
if svc.Form == nil {
|
||||||
|
svc.Form = make(map[string]*Parameter)
|
||||||
|
}
|
||||||
|
svc.Form[name] = p
|
||||||
|
return formParam, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// nameConflicts returns whether ar given parameter has its name or Rename field
|
||||||
|
// in conflict with an existing parameter
|
||||||
|
func nameConflicts(name string, param *Parameter, others map[string]*Parameter) error {
|
||||||
|
for otherName, other := range others {
|
||||||
// ignore self
|
// ignore self
|
||||||
if paramName == paramName2 {
|
if otherName == name {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3.2.1. Same rename field
|
// 1. same rename field
|
||||||
// 3.2.2. Not-renamed field matches a renamed field
|
// 2. original name matches a renamed field
|
||||||
// 3.2.3. Renamed field matches name
|
// 3. renamed field matches an original name
|
||||||
if param.Rename == param2.Rename || paramName == param2.Rename || paramName2 == param.Rename {
|
if param.Rename == other.Rename || name == other.Rename || otherName == param.Rename {
|
||||||
return fmt.Errorf("%s: %w", paramName, errParamNameConflict)
|
return fmt.Errorf("%s: %w", otherName, ErrParamNameConflict)
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,50 +1,52 @@
|
||||||
package dynfunc
|
package dynfunc
|
||||||
|
|
||||||
// cerr allows you to create constant "const" error with type boxing.
|
// Err allows you to create constant "const" error with type boxing.
|
||||||
type cerr string
|
type Err string
|
||||||
|
|
||||||
func (err cerr) Error() string {
|
func (err Err) Error() string {
|
||||||
return string(err)
|
return string(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// errHandlerNotFunc - handler is not a func
|
const (
|
||||||
const errHandlerNotFunc = cerr("handler must be a func")
|
// ErrHandlerNotFunc - handler is not a func
|
||||||
|
ErrHandlerNotFunc = Err("handler must be a func")
|
||||||
|
|
||||||
// errNoServiceForHandler - no service matching this handler
|
// ErrNoServiceForHandler - no service matching this handler
|
||||||
const errNoServiceForHandler = cerr("no service found for this handler")
|
ErrNoServiceForHandler = Err("no service found for this handler")
|
||||||
|
|
||||||
// errMissingHandlerArgumentParam - missing params arguments for handler
|
// errMissingHandlerArgumentParam - missing params arguments for handler
|
||||||
const errMissingHandlerContextArgument = cerr("missing handler first argument of type context.Context")
|
ErrMissingHandlerContextArgument = Err("missing handler first argument of type context.Context")
|
||||||
|
|
||||||
// errMissingHandlerInputArgument - missing params arguments for handler
|
// ErrInvalidHandlerContextArgument - missing handler output error
|
||||||
const errMissingHandlerInputArgument = cerr("missing handler argument: input struct")
|
ErrInvalidHandlerContextArgument = Err("first input argument should be of type context.Context")
|
||||||
|
|
||||||
// errUnexpectedInput - input argument is not expected
|
// ErrMissingHandlerInputArgument - missing params arguments for handler
|
||||||
const errUnexpectedInput = cerr("unexpected input struct")
|
ErrMissingHandlerInputArgument = Err("missing handler argument: input struct")
|
||||||
|
|
||||||
// errMissingHandlerOutputArgument - missing output for handler
|
// ErrUnexpectedInput - input argument is not expected
|
||||||
const errMissingHandlerOutputArgument = cerr("missing handler first output argument: output struct")
|
ErrUnexpectedInput = Err("unexpected input struct")
|
||||||
|
|
||||||
// errMissingHandlerOutputError - missing error output for handler
|
// ErrMissingHandlerOutputArgument - missing output for handler
|
||||||
const errMissingHandlerOutputError = cerr("missing handler last output argument of type api.Err")
|
ErrMissingHandlerOutputArgument = Err("missing handler first output argument: output struct")
|
||||||
|
|
||||||
// errMissingRequestArgument - missing request argument for handler
|
// ErrMissingHandlerErrorArgument - missing error output for handler
|
||||||
const errMissingRequestArgument = cerr("handler first argument must be of type api.Request")
|
ErrMissingHandlerErrorArgument = Err("missing handler last output argument of type api.Err")
|
||||||
|
|
||||||
// errMissingParamArgument - missing parameters argument for handler
|
// ErrInvalidHandlerErrorArgument - missing handler output error
|
||||||
const errMissingParamArgument = cerr("handler second argument must be a struct")
|
ErrInvalidHandlerErrorArgument = Err("last output must be of type api.Err")
|
||||||
|
|
||||||
// errUnexportedName - argument is unexported in struct
|
// ErrMissingParamArgument - missing parameters argument for handler
|
||||||
const errUnexportedName = cerr("unexported name")
|
ErrMissingParamArgument = Err("handler second argument must be a struct")
|
||||||
|
|
||||||
// errWrongOutputArgumentType - wrong type for output first argument
|
// ErrUnexportedName - argument is unexported in struct
|
||||||
const errWrongOutputArgumentType = cerr("handler first output argument must be a *struct")
|
ErrUnexportedName = Err("unexported name")
|
||||||
|
|
||||||
// errMissingConfigArgument - missing an input/output argument in handler struct
|
// ErrWrongOutputArgumentType - wrong type for output first argument
|
||||||
const errMissingConfigArgument = cerr("missing an argument from the configuration")
|
ErrWrongOutputArgumentType = Err("handler first output argument must be a *struct")
|
||||||
|
|
||||||
// errWrongParamTypeFromConfig - a configuration parameter type is invalid in the handler param struct
|
// ErrMissingConfigArgument - missing an input/output argument in handler struct
|
||||||
const errWrongParamTypeFromConfig = cerr("invalid struct field type")
|
ErrMissingConfigArgument = Err("missing an argument from the configuration")
|
||||||
|
|
||||||
// errMissingHandlerErrorArgument - missing handler output error
|
// ErrWrongParamTypeFromConfig - a configuration parameter type is invalid in the handler param struct
|
||||||
const errMissingHandlerErrorArgument = cerr("last output must be of type api.Err")
|
ErrWrongParamTypeFromConfig = Err("invalid struct field type")
|
||||||
|
)
|
||||||
|
|
|
@ -20,14 +20,14 @@ type Handler struct {
|
||||||
|
|
||||||
// Build a handler from a dynamic function and checks its signature against a
|
// Build a handler from a dynamic function and checks its signature against a
|
||||||
// service configuration
|
// service configuration
|
||||||
//e
|
//
|
||||||
// `fn` must have as a signature : `func(*api.Context, in) (*out, api.Err)`
|
// `fn` must have as a signature : `func(context.Context, in) (*out, api.Err)`
|
||||||
// - `in` is a struct{} containing a field for each service input (with valid reflect.Type)
|
// - `in` is a struct{} containing a field for each service input (with valid reflect.Type)
|
||||||
// - `out` is a struct{} containing a field for each service output (with valid reflect.Type)
|
// - `out` is a struct{} containing a field for each service output (with valid reflect.Type)
|
||||||
//
|
//
|
||||||
// Special cases:
|
// Special cases:
|
||||||
// - it there is no input, `in` MUST be omitted
|
// - it there is no input, `in` MUST be omitted
|
||||||
// - it there is no output, `out` MUST be omitted
|
// - it there is no output, `out` CAN be omitted
|
||||||
func Build(fn interface{}, service config.Service) (*Handler, error) {
|
func Build(fn interface{}, service config.Service) (*Handler, error) {
|
||||||
var (
|
var (
|
||||||
h = &Handler{
|
h = &Handler{
|
||||||
|
@ -38,7 +38,7 @@ func Build(fn interface{}, service config.Service) (*Handler, error) {
|
||||||
)
|
)
|
||||||
|
|
||||||
if fnType.Kind() != reflect.Func {
|
if fnType.Kind() != reflect.Func {
|
||||||
return nil, errHandlerNotFunc
|
return nil, ErrHandlerNotFunc
|
||||||
}
|
}
|
||||||
if err := h.signature.ValidateInput(fnType); err != nil {
|
if err := h.signature.ValidateInput(fnType); err != nil {
|
||||||
return nil, fmt.Errorf("input: %w", err)
|
return nil, fmt.Errorf("input: %w", err)
|
||||||
|
|
|
@ -53,47 +53,47 @@ func (s *Signature) ValidateInput(handlerType reflect.Type) error {
|
||||||
|
|
||||||
// missing or invalid first arg: context.Context
|
// missing or invalid first arg: context.Context
|
||||||
if handlerType.NumIn() < 1 {
|
if handlerType.NumIn() < 1 {
|
||||||
return errMissingHandlerContextArgument
|
return ErrMissingHandlerContextArgument
|
||||||
}
|
}
|
||||||
firstArgType := handlerType.In(0)
|
firstArgType := handlerType.In(0)
|
||||||
|
|
||||||
if !firstArgType.Implements(ctxType) {
|
if !firstArgType.Implements(ctxType) {
|
||||||
return fmt.Errorf("fock")
|
return ErrInvalidHandlerContextArgument
|
||||||
}
|
}
|
||||||
|
|
||||||
// no input required
|
// no input required
|
||||||
if len(s.Input) == 0 {
|
if len(s.Input) == 0 {
|
||||||
// input struct provided
|
// input struct provided
|
||||||
if handlerType.NumIn() > 1 {
|
if handlerType.NumIn() > 1 {
|
||||||
return errUnexpectedInput
|
return ErrUnexpectedInput
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// too much arguments
|
// too much arguments
|
||||||
if handlerType.NumIn() > 2 {
|
if handlerType.NumIn() != 2 {
|
||||||
return errMissingHandlerInputArgument
|
return ErrMissingHandlerInputArgument
|
||||||
}
|
}
|
||||||
|
|
||||||
// arg must be a struct
|
// arg must be a struct
|
||||||
inStruct := handlerType.In(1)
|
inStruct := handlerType.In(1)
|
||||||
if inStruct.Kind() != reflect.Struct {
|
if inStruct.Kind() != reflect.Struct {
|
||||||
return errMissingParamArgument
|
return ErrMissingParamArgument
|
||||||
}
|
}
|
||||||
|
|
||||||
// check for invalid param
|
// check for invalid param
|
||||||
for name, ptype := range s.Input {
|
for name, ptype := range s.Input {
|
||||||
if name[0] == strings.ToLower(name)[0] {
|
if name[0] == strings.ToLower(name)[0] {
|
||||||
return fmt.Errorf("%s: %w", name, errUnexportedName)
|
return fmt.Errorf("%s: %w", name, ErrUnexportedName)
|
||||||
}
|
}
|
||||||
|
|
||||||
field, exists := inStruct.FieldByName(name)
|
field, exists := inStruct.FieldByName(name)
|
||||||
if !exists {
|
if !exists {
|
||||||
return fmt.Errorf("%s: %w", name, errMissingConfigArgument)
|
return fmt.Errorf("%s: %w", name, ErrMissingConfigArgument)
|
||||||
}
|
}
|
||||||
|
|
||||||
if !ptype.AssignableTo(field.Type) {
|
if !ptype.AssignableTo(field.Type) {
|
||||||
return fmt.Errorf("%s: %w (%s instead of %s)", name, errWrongParamTypeFromConfig, field.Type, ptype)
|
return fmt.Errorf("%s: %w (%s instead of %s)", name, ErrWrongParamTypeFromConfig, field.Type, ptype)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -105,44 +105,44 @@ func (s Signature) ValidateOutput(handlerType reflect.Type) error {
|
||||||
errType := reflect.TypeOf(api.ErrUnknown)
|
errType := reflect.TypeOf(api.ErrUnknown)
|
||||||
|
|
||||||
if handlerType.NumOut() < 1 {
|
if handlerType.NumOut() < 1 {
|
||||||
return errMissingHandlerErrorArgument
|
return ErrMissingHandlerErrorArgument
|
||||||
}
|
}
|
||||||
|
|
||||||
// last output must be api.Err
|
// last output must be api.Err
|
||||||
lastArgType := handlerType.Out(handlerType.NumOut() - 1)
|
lastArgType := handlerType.Out(handlerType.NumOut() - 1)
|
||||||
if !lastArgType.AssignableTo(errType) {
|
if !lastArgType.AssignableTo(errType) {
|
||||||
return errMissingHandlerErrorArgument
|
return ErrInvalidHandlerErrorArgument
|
||||||
}
|
}
|
||||||
|
|
||||||
// no output -> ok
|
// no output required -> ok
|
||||||
if len(s.Output) == 0 {
|
if len(s.Output) == 0 {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
if handlerType.NumOut() < 2 {
|
if handlerType.NumOut() < 2 {
|
||||||
return errMissingHandlerOutputArgument
|
return ErrMissingHandlerOutputArgument
|
||||||
}
|
}
|
||||||
|
|
||||||
// fail if first output is not a pointer to struct
|
// fail if first output is not a pointer to struct
|
||||||
outStructPtr := handlerType.Out(0)
|
outStructPtr := handlerType.Out(0)
|
||||||
if outStructPtr.Kind() != reflect.Ptr {
|
if outStructPtr.Kind() != reflect.Ptr {
|
||||||
return errWrongOutputArgumentType
|
return ErrWrongOutputArgumentType
|
||||||
}
|
}
|
||||||
|
|
||||||
outStruct := outStructPtr.Elem()
|
outStruct := outStructPtr.Elem()
|
||||||
if outStruct.Kind() != reflect.Struct {
|
if outStruct.Kind() != reflect.Struct {
|
||||||
return errWrongOutputArgumentType
|
return ErrWrongOutputArgumentType
|
||||||
}
|
}
|
||||||
|
|
||||||
// fail on invalid output
|
// fail on invalid output
|
||||||
for name, ptype := range s.Output {
|
for name, ptype := range s.Output {
|
||||||
if name[0] == strings.ToLower(name)[0] {
|
if name[0] == strings.ToLower(name)[0] {
|
||||||
return fmt.Errorf("%s: %w", name, errUnexportedName)
|
return fmt.Errorf("%s: %w", name, ErrUnexportedName)
|
||||||
}
|
}
|
||||||
|
|
||||||
field, exists := outStruct.FieldByName(name)
|
field, exists := outStruct.FieldByName(name)
|
||||||
if !exists {
|
if !exists {
|
||||||
return fmt.Errorf("%s: %w", name, errMissingConfigArgument)
|
return fmt.Errorf("%s: %w", name, ErrMissingConfigArgument)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ignore types evalutating to nil
|
// ignore types evalutating to nil
|
||||||
|
@ -151,7 +151,7 @@ func (s Signature) ValidateOutput(handlerType reflect.Type) error {
|
||||||
}
|
}
|
||||||
|
|
||||||
if !field.Type.ConvertibleTo(ptype) {
|
if !field.Type.ConvertibleTo(ptype) {
|
||||||
return fmt.Errorf("%s: %w (%s instead of %s)", name, errWrongParamTypeFromConfig, field.Type, ptype)
|
return fmt.Errorf("%s: %w (%s instead of %s)", name, ErrWrongParamTypeFromConfig, field.Type, ptype)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -8,382 +8,562 @@ import (
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/xdrm-io/aicra/api"
|
"github.com/xdrm-io/aicra/api"
|
||||||
|
"github.com/xdrm-io/aicra/internal/config"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestInputCheck(t *testing.T) {
|
func TestInputValidation(t *testing.T) {
|
||||||
tcases := []struct {
|
tt := []struct {
|
||||||
Name string
|
name string
|
||||||
Input map[string]reflect.Type
|
input map[string]reflect.Type
|
||||||
Fn interface{}
|
fn interface{}
|
||||||
FnCtx interface{}
|
err error
|
||||||
Err error
|
|
||||||
}{
|
}{
|
||||||
{
|
{
|
||||||
Name: "no input 0 given",
|
name: "missing context",
|
||||||
Input: map[string]reflect.Type{},
|
input: map[string]reflect.Type{},
|
||||||
Fn: func(context.Context) {},
|
fn: func() {},
|
||||||
FnCtx: func(context.Context) {},
|
err: ErrMissingHandlerContextArgument,
|
||||||
Err: nil,
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Name: "no input 1 given",
|
name: "invalid context",
|
||||||
Input: map[string]reflect.Type{},
|
input: map[string]reflect.Type{},
|
||||||
Fn: func(context.Context, int) {},
|
fn: func(int) {},
|
||||||
FnCtx: func(context.Context, int) {},
|
err: ErrInvalidHandlerContextArgument,
|
||||||
Err: errUnexpectedInput,
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Name: "no input 2 given",
|
name: "no input 0 given",
|
||||||
Input: map[string]reflect.Type{},
|
input: map[string]reflect.Type{},
|
||||||
Fn: func(context.Context, int, string) {},
|
fn: func(context.Context) {},
|
||||||
FnCtx: func(context.Context, int, string) {},
|
err: nil,
|
||||||
Err: errUnexpectedInput,
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Name: "1 input 0 given",
|
name: "no input 1 given",
|
||||||
Input: map[string]reflect.Type{
|
input: map[string]reflect.Type{},
|
||||||
|
fn: func(context.Context, int) {},
|
||||||
|
err: ErrUnexpectedInput,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "no input 2 given",
|
||||||
|
input: map[string]reflect.Type{},
|
||||||
|
fn: func(context.Context, int, string) {},
|
||||||
|
err: ErrUnexpectedInput,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "1 input 0 given",
|
||||||
|
input: map[string]reflect.Type{
|
||||||
"Test1": reflect.TypeOf(int(0)),
|
"Test1": reflect.TypeOf(int(0)),
|
||||||
},
|
},
|
||||||
Fn: func(context.Context) {},
|
fn: func(context.Context) {},
|
||||||
FnCtx: func(context.Context) {},
|
err: ErrMissingHandlerInputArgument,
|
||||||
Err: errMissingHandlerInputArgument,
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Name: "1 input non-struct given",
|
name: "1 input non-struct given",
|
||||||
Input: map[string]reflect.Type{
|
input: map[string]reflect.Type{
|
||||||
"Test1": reflect.TypeOf(int(0)),
|
"Test1": reflect.TypeOf(int(0)),
|
||||||
},
|
},
|
||||||
Fn: func(context.Context, int) {},
|
fn: func(context.Context, int) {},
|
||||||
FnCtx: func(context.Context, int) {},
|
err: ErrMissingParamArgument,
|
||||||
Err: errMissingParamArgument,
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Name: "unexported input",
|
name: "unexported input",
|
||||||
Input: map[string]reflect.Type{
|
input: map[string]reflect.Type{
|
||||||
"test1": reflect.TypeOf(int(0)),
|
"test1": reflect.TypeOf(int(0)),
|
||||||
},
|
},
|
||||||
Fn: func(context.Context, struct{}) {},
|
fn: func(context.Context, struct{}) {},
|
||||||
FnCtx: func(context.Context, struct{}) {},
|
err: ErrUnexportedName,
|
||||||
Err: errUnexportedName,
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Name: "1 input empty struct given",
|
name: "1 input empty struct given",
|
||||||
Input: map[string]reflect.Type{
|
input: map[string]reflect.Type{
|
||||||
"Test1": reflect.TypeOf(int(0)),
|
"Test1": reflect.TypeOf(int(0)),
|
||||||
},
|
},
|
||||||
Fn: func(context.Context, struct{}) {},
|
fn: func(context.Context, struct{}) {},
|
||||||
FnCtx: func(context.Context, struct{}) {},
|
err: ErrMissingConfigArgument,
|
||||||
Err: errMissingConfigArgument,
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Name: "1 input invalid given",
|
name: "1 input invalid given",
|
||||||
Input: map[string]reflect.Type{
|
input: map[string]reflect.Type{
|
||||||
"Test1": reflect.TypeOf(int(0)),
|
"Test1": reflect.TypeOf(int(0)),
|
||||||
},
|
},
|
||||||
Fn: func(context.Context, struct{ Test1 string }) {},
|
fn: func(context.Context, struct{ Test1 string }) {},
|
||||||
FnCtx: func(context.Context, struct{ Test1 string }) {},
|
err: ErrWrongParamTypeFromConfig,
|
||||||
Err: errWrongParamTypeFromConfig,
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Name: "1 input valid given",
|
name: "1 input valid given",
|
||||||
Input: map[string]reflect.Type{
|
input: map[string]reflect.Type{
|
||||||
"Test1": reflect.TypeOf(int(0)),
|
"Test1": reflect.TypeOf(int(0)),
|
||||||
},
|
},
|
||||||
Fn: func(context.Context, struct{ Test1 int }) {},
|
fn: func(context.Context, struct{ Test1 int }) {},
|
||||||
FnCtx: func(context.Context, struct{ Test1 int }) {},
|
err: nil,
|
||||||
Err: nil,
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Name: "1 input ptr empty struct given",
|
name: "1 input ptr empty struct given",
|
||||||
Input: map[string]reflect.Type{
|
input: map[string]reflect.Type{
|
||||||
"Test1": reflect.TypeOf(new(int)),
|
"Test1": reflect.TypeOf(new(int)),
|
||||||
},
|
},
|
||||||
Fn: func(context.Context, struct{}) {},
|
fn: func(context.Context, struct{}) {},
|
||||||
FnCtx: func(context.Context, struct{}) {},
|
err: ErrMissingConfigArgument,
|
||||||
Err: errMissingConfigArgument,
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Name: "1 input ptr invalid given",
|
name: "1 input ptr invalid given",
|
||||||
Input: map[string]reflect.Type{
|
input: map[string]reflect.Type{
|
||||||
"Test1": reflect.TypeOf(new(int)),
|
"Test1": reflect.TypeOf(new(int)),
|
||||||
},
|
},
|
||||||
Fn: func(context.Context, struct{ Test1 string }) {},
|
fn: func(context.Context, struct{ Test1 string }) {},
|
||||||
FnCtx: func(context.Context, struct{ Test1 string }) {},
|
err: ErrWrongParamTypeFromConfig,
|
||||||
Err: errWrongParamTypeFromConfig,
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Name: "1 input ptr invalid ptr type given",
|
name: "1 input ptr invalid ptr type given",
|
||||||
Input: map[string]reflect.Type{
|
input: map[string]reflect.Type{
|
||||||
"Test1": reflect.TypeOf(new(int)),
|
"Test1": reflect.TypeOf(new(int)),
|
||||||
},
|
},
|
||||||
Fn: func(context.Context, struct{ Test1 *string }) {},
|
fn: func(context.Context, struct{ Test1 *string }) {},
|
||||||
FnCtx: func(context.Context, struct{ Test1 *string }) {},
|
err: ErrWrongParamTypeFromConfig,
|
||||||
Err: errWrongParamTypeFromConfig,
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Name: "1 input ptr valid given",
|
name: "1 input ptr valid given",
|
||||||
Input: map[string]reflect.Type{
|
input: map[string]reflect.Type{
|
||||||
"Test1": reflect.TypeOf(new(int)),
|
"Test1": reflect.TypeOf(new(int)),
|
||||||
},
|
},
|
||||||
Fn: func(context.Context, struct{ Test1 *int }) {},
|
fn: func(context.Context, struct{ Test1 *int }) {},
|
||||||
FnCtx: func(context.Context, struct{ Test1 *int }) {},
|
err: nil,
|
||||||
Err: nil,
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Name: "1 valid string",
|
name: "1 valid string",
|
||||||
Input: map[string]reflect.Type{
|
input: map[string]reflect.Type{
|
||||||
"Test1": reflect.TypeOf(string("")),
|
"Test1": reflect.TypeOf(string("")),
|
||||||
},
|
},
|
||||||
Fn: func(context.Context, struct{ Test1 string }) {},
|
fn: func(context.Context, struct{ Test1 string }) {},
|
||||||
FnCtx: func(context.Context, struct{ Test1 string }) {},
|
err: nil,
|
||||||
Err: nil,
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Name: "1 valid uint",
|
name: "1 valid uint",
|
||||||
Input: map[string]reflect.Type{
|
input: map[string]reflect.Type{
|
||||||
"Test1": reflect.TypeOf(uint(0)),
|
"Test1": reflect.TypeOf(uint(0)),
|
||||||
},
|
},
|
||||||
Fn: func(context.Context, struct{ Test1 uint }) {},
|
fn: func(context.Context, struct{ Test1 uint }) {},
|
||||||
FnCtx: func(context.Context, struct{ Test1 uint }) {},
|
err: nil,
|
||||||
Err: nil,
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Name: "1 valid float64",
|
name: "1 valid float64",
|
||||||
Input: map[string]reflect.Type{
|
input: map[string]reflect.Type{
|
||||||
"Test1": reflect.TypeOf(float64(0)),
|
"Test1": reflect.TypeOf(float64(0)),
|
||||||
},
|
},
|
||||||
Fn: func(context.Context, struct{ Test1 float64 }) {},
|
fn: func(context.Context, struct{ Test1 float64 }) {},
|
||||||
FnCtx: func(context.Context, struct{ Test1 float64 }) {},
|
err: nil,
|
||||||
Err: nil,
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Name: "1 valid []byte",
|
name: "1 valid []byte",
|
||||||
Input: map[string]reflect.Type{
|
input: map[string]reflect.Type{
|
||||||
"Test1": reflect.TypeOf([]byte("")),
|
"Test1": reflect.TypeOf([]byte("")),
|
||||||
},
|
},
|
||||||
Fn: func(context.Context, struct{ Test1 []byte }) {},
|
fn: func(context.Context, struct{ Test1 []byte }) {},
|
||||||
FnCtx: func(context.Context, struct{ Test1 []byte }) {},
|
err: nil,
|
||||||
Err: nil,
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Name: "1 valid []rune",
|
name: "1 valid []rune",
|
||||||
Input: map[string]reflect.Type{
|
input: map[string]reflect.Type{
|
||||||
"Test1": reflect.TypeOf([]rune("")),
|
"Test1": reflect.TypeOf([]rune("")),
|
||||||
},
|
},
|
||||||
Fn: func(context.Context, struct{ Test1 []rune }) {},
|
fn: func(context.Context, struct{ Test1 []rune }) {},
|
||||||
FnCtx: func(context.Context, struct{ Test1 []rune }) {},
|
err: nil,
|
||||||
Err: nil,
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Name: "1 valid *string",
|
name: "1 valid *string",
|
||||||
Input: map[string]reflect.Type{
|
input: map[string]reflect.Type{
|
||||||
"Test1": reflect.TypeOf(new(string)),
|
"Test1": reflect.TypeOf(new(string)),
|
||||||
},
|
},
|
||||||
Fn: func(context.Context, struct{ Test1 *string }) {},
|
fn: func(context.Context, struct{ Test1 *string }) {},
|
||||||
FnCtx: func(context.Context, struct{ Test1 *string }) {},
|
err: nil,
|
||||||
Err: nil,
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Name: "1 valid *uint",
|
name: "1 valid *uint",
|
||||||
Input: map[string]reflect.Type{
|
input: map[string]reflect.Type{
|
||||||
"Test1": reflect.TypeOf(new(uint)),
|
"Test1": reflect.TypeOf(new(uint)),
|
||||||
},
|
},
|
||||||
Fn: func(context.Context, struct{ Test1 *uint }) {},
|
fn: func(context.Context, struct{ Test1 *uint }) {},
|
||||||
FnCtx: func(context.Context, struct{ Test1 *uint }) {},
|
err: nil,
|
||||||
Err: nil,
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Name: "1 valid *float64",
|
name: "1 valid *float64",
|
||||||
Input: map[string]reflect.Type{
|
input: map[string]reflect.Type{
|
||||||
"Test1": reflect.TypeOf(new(float64)),
|
"Test1": reflect.TypeOf(new(float64)),
|
||||||
},
|
},
|
||||||
Fn: func(context.Context, struct{ Test1 *float64 }) {},
|
fn: func(context.Context, struct{ Test1 *float64 }) {},
|
||||||
FnCtx: func(context.Context, struct{ Test1 *float64 }) {},
|
err: nil,
|
||||||
Err: nil,
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Name: "1 valid *[]byte",
|
name: "1 valid *[]byte",
|
||||||
Input: map[string]reflect.Type{
|
input: map[string]reflect.Type{
|
||||||
"Test1": reflect.TypeOf(new([]byte)),
|
"Test1": reflect.TypeOf(new([]byte)),
|
||||||
},
|
},
|
||||||
Fn: func(context.Context, struct{ Test1 *[]byte }) {},
|
fn: func(context.Context, struct{ Test1 *[]byte }) {},
|
||||||
FnCtx: func(context.Context, struct{ Test1 *[]byte }) {},
|
err: nil,
|
||||||
Err: nil,
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Name: "1 valid *[]rune",
|
name: "1 valid *[]rune",
|
||||||
Input: map[string]reflect.Type{
|
input: map[string]reflect.Type{
|
||||||
"Test1": reflect.TypeOf(new([]rune)),
|
"Test1": reflect.TypeOf(new([]rune)),
|
||||||
},
|
},
|
||||||
Fn: func(context.Context, struct{ Test1 *[]rune }) {},
|
fn: func(context.Context, struct{ Test1 *[]rune }) {},
|
||||||
FnCtx: func(context.Context, struct{ Test1 *[]rune }) {},
|
err: nil,
|
||||||
Err: nil,
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, tcase := range tcases {
|
for _, tc := range tt {
|
||||||
t.Run(tcase.Name, func(t *testing.T) {
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
// mock spec
|
// mock spec
|
||||||
s := Signature{
|
s := Signature{
|
||||||
Input: tcase.Input,
|
Input: tc.input,
|
||||||
Output: nil,
|
Output: nil,
|
||||||
}
|
}
|
||||||
|
|
||||||
err := s.ValidateInput(reflect.TypeOf(tcase.FnCtx))
|
err := s.ValidateInput(reflect.TypeOf(tc.fn))
|
||||||
if err == nil && tcase.Err != nil {
|
if err == nil && tc.err != nil {
|
||||||
t.Errorf("expected an error: '%s'", tcase.Err.Error())
|
t.Fatalf("expected an error: '%s'", tc.err.Error())
|
||||||
t.FailNow()
|
|
||||||
}
|
}
|
||||||
if err != nil && tcase.Err == nil {
|
if err != nil && tc.err == nil {
|
||||||
t.Errorf("unexpected error: '%s'", err.Error())
|
t.Fatalf("unexpected error: '%s'", err.Error())
|
||||||
t.FailNow()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if err != nil && tcase.Err != nil {
|
if err != nil && tc.err != nil {
|
||||||
if !errors.Is(err, tcase.Err) {
|
if !errors.Is(err, tc.err) {
|
||||||
t.Errorf("expected the error <%s> got <%s>", tcase.Err, err)
|
t.Fatalf("expected the error <%s> got <%s>", tc.err, err)
|
||||||
t.FailNow()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestOutputCheck(t *testing.T) {
|
func TestOutputValidation(t *testing.T) {
|
||||||
tcases := []struct {
|
tt := []struct {
|
||||||
Output map[string]reflect.Type
|
name string
|
||||||
Fn interface{}
|
output map[string]reflect.Type
|
||||||
Err error
|
fn interface{}
|
||||||
|
err error
|
||||||
}{
|
}{
|
||||||
// no input -> missing api.Err
|
|
||||||
{
|
{
|
||||||
Output: map[string]reflect.Type{},
|
name: "no output missing err",
|
||||||
Fn: func(context.Context) {},
|
output: map[string]reflect.Type{},
|
||||||
Err: errMissingHandlerOutputArgument,
|
fn: func() {},
|
||||||
|
err: ErrMissingHandlerErrorArgument,
|
||||||
},
|
},
|
||||||
// no input -> with last type not api.Err
|
|
||||||
{
|
{
|
||||||
Output: map[string]reflect.Type{},
|
name: "no output invalid err",
|
||||||
Fn: func(context.Context) bool { return true },
|
output: map[string]reflect.Type{},
|
||||||
Err: errMissingHandlerErrorArgument,
|
fn: func() bool { return true },
|
||||||
|
err: ErrInvalidHandlerErrorArgument,
|
||||||
},
|
},
|
||||||
// no input -> with api.Err
|
|
||||||
{
|
{
|
||||||
Output: map[string]reflect.Type{},
|
name: "1 output none required",
|
||||||
Fn: func(context.Context) api.Err { return api.ErrSuccess },
|
output: map[string]reflect.Type{},
|
||||||
Err: nil,
|
fn: func(context.Context) (*struct{}, api.Err) { return nil, api.ErrSuccess },
|
||||||
|
err: nil,
|
||||||
},
|
},
|
||||||
// no input -> missing context.Context
|
|
||||||
{
|
{
|
||||||
Output: map[string]reflect.Type{},
|
name: "no output 1 required",
|
||||||
Fn: func(context.Context) api.Err { return api.ErrSuccess },
|
output: map[string]reflect.Type{
|
||||||
Err: errMissingHandlerContextArgument,
|
|
||||||
},
|
|
||||||
// no input -> invlaid context.Context type
|
|
||||||
{
|
|
||||||
Output: map[string]reflect.Type{},
|
|
||||||
Fn: func(context.Context, int) api.Err { return api.ErrSuccess },
|
|
||||||
Err: errMissingHandlerContextArgument,
|
|
||||||
},
|
|
||||||
// func can have output if not specified
|
|
||||||
{
|
|
||||||
Output: map[string]reflect.Type{},
|
|
||||||
Fn: func(context.Context) (*struct{}, api.Err) { return nil, api.ErrSuccess },
|
|
||||||
Err: nil,
|
|
||||||
},
|
|
||||||
// missing output struct in func
|
|
||||||
{
|
|
||||||
Output: map[string]reflect.Type{
|
|
||||||
"Test1": reflect.TypeOf(int(0)),
|
"Test1": reflect.TypeOf(int(0)),
|
||||||
},
|
},
|
||||||
Fn: func() api.Err { return api.ErrSuccess },
|
fn: func() api.Err { return api.ErrSuccess },
|
||||||
Err: errWrongOutputArgumentType,
|
err: ErrMissingHandlerOutputArgument,
|
||||||
},
|
},
|
||||||
// output not a pointer
|
|
||||||
{
|
{
|
||||||
Output: map[string]reflect.Type{
|
name: "invalid int output",
|
||||||
|
output: map[string]reflect.Type{
|
||||||
"Test1": reflect.TypeOf(int(0)),
|
"Test1": reflect.TypeOf(int(0)),
|
||||||
},
|
},
|
||||||
Fn: func() (int, api.Err) { return 0, api.ErrSuccess },
|
fn: func() (int, api.Err) { return 0, api.ErrSuccess },
|
||||||
Err: errWrongOutputArgumentType,
|
err: ErrWrongOutputArgumentType,
|
||||||
},
|
},
|
||||||
// output not a pointer to struct
|
|
||||||
{
|
{
|
||||||
Output: map[string]reflect.Type{
|
name: "invalid int ptr output",
|
||||||
|
output: map[string]reflect.Type{
|
||||||
"Test1": reflect.TypeOf(int(0)),
|
"Test1": reflect.TypeOf(int(0)),
|
||||||
},
|
},
|
||||||
Fn: func() (*int, api.Err) { return nil, api.ErrSuccess },
|
fn: func() (*int, api.Err) { return nil, api.ErrSuccess },
|
||||||
Err: errWrongOutputArgumentType,
|
err: ErrWrongOutputArgumentType,
|
||||||
},
|
},
|
||||||
// unexported param name
|
|
||||||
{
|
{
|
||||||
Output: map[string]reflect.Type{
|
name: "invalid struct output",
|
||||||
|
output: map[string]reflect.Type{
|
||||||
|
"Test1": reflect.TypeOf(int(0)),
|
||||||
|
},
|
||||||
|
fn: func() (struct{ Test1 int }, api.Err) { return struct{ Test1 int }{Test1: 1}, api.ErrSuccess },
|
||||||
|
err: ErrWrongOutputArgumentType,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "unexported param",
|
||||||
|
output: map[string]reflect.Type{
|
||||||
"test1": reflect.TypeOf(int(0)),
|
"test1": reflect.TypeOf(int(0)),
|
||||||
},
|
},
|
||||||
Fn: func() (*struct{}, api.Err) { return nil, api.ErrSuccess },
|
fn: func() (*struct{}, api.Err) { return nil, api.ErrSuccess },
|
||||||
Err: errUnexportedName,
|
err: ErrUnexportedName,
|
||||||
},
|
},
|
||||||
// output field missing
|
|
||||||
{
|
{
|
||||||
Output: map[string]reflect.Type{
|
name: "missing output param",
|
||||||
|
output: map[string]reflect.Type{
|
||||||
"Test1": reflect.TypeOf(int(0)),
|
"Test1": reflect.TypeOf(int(0)),
|
||||||
},
|
},
|
||||||
Fn: func() (*struct{}, api.Err) { return nil, api.ErrSuccess },
|
fn: func() (*struct{}, api.Err) { return nil, api.ErrSuccess },
|
||||||
Err: errMissingConfigArgument,
|
err: ErrMissingConfigArgument,
|
||||||
},
|
},
|
||||||
// output field invalid type
|
|
||||||
{
|
{
|
||||||
Output: map[string]reflect.Type{
|
name: "invalid output param",
|
||||||
|
output: map[string]reflect.Type{
|
||||||
"Test1": reflect.TypeOf(int(0)),
|
"Test1": reflect.TypeOf(int(0)),
|
||||||
},
|
},
|
||||||
Fn: func() (*struct{ Test1 string }, api.Err) { return nil, api.ErrSuccess },
|
fn: func() (*struct{ Test1 string }, api.Err) { return nil, api.ErrSuccess },
|
||||||
Err: errWrongParamTypeFromConfig,
|
err: ErrWrongParamTypeFromConfig,
|
||||||
},
|
},
|
||||||
// output field valid type
|
|
||||||
{
|
{
|
||||||
Output: map[string]reflect.Type{
|
name: "valid param",
|
||||||
|
output: map[string]reflect.Type{
|
||||||
"Test1": reflect.TypeOf(int(0)),
|
"Test1": reflect.TypeOf(int(0)),
|
||||||
},
|
},
|
||||||
Fn: func() (*struct{ Test1 int }, api.Err) { return nil, api.ErrSuccess },
|
fn: func() (*struct{ Test1 int }, api.Err) { return nil, api.ErrSuccess },
|
||||||
Err: nil,
|
err: nil,
|
||||||
},
|
},
|
||||||
// ignore type check on nil type
|
|
||||||
{
|
{
|
||||||
Output: map[string]reflect.Type{
|
name: "2 valid params",
|
||||||
|
output: map[string]reflect.Type{
|
||||||
|
"Test1": reflect.TypeOf(int(0)),
|
||||||
|
"Test2": reflect.TypeOf(string("")),
|
||||||
|
},
|
||||||
|
fn: func() (*struct {
|
||||||
|
Test1 int
|
||||||
|
Test2 string
|
||||||
|
}, api.Err) {
|
||||||
|
return nil, api.ErrSuccess
|
||||||
|
},
|
||||||
|
err: nil,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "nil type ignore typecheck",
|
||||||
|
output: map[string]reflect.Type{
|
||||||
"Test1": nil,
|
"Test1": nil,
|
||||||
},
|
},
|
||||||
Fn: func() (*struct{ Test1 int }, api.Err) { return nil, api.ErrSuccess },
|
fn: func() (*struct{ Test1 int }, api.Err) { return nil, api.ErrSuccess },
|
||||||
Err: nil,
|
err: nil,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
for i, tcase := range tcases {
|
for _, tc := range tt {
|
||||||
t.Run(fmt.Sprintf("case.%d", i), func(t *testing.T) {
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
// mock spec
|
// mock spec
|
||||||
s := Signature{
|
s := Signature{
|
||||||
Input: nil,
|
Input: nil,
|
||||||
Output: tcase.Output,
|
Output: tc.output,
|
||||||
}
|
}
|
||||||
|
|
||||||
err := s.ValidateOutput(reflect.TypeOf(tcase.Fn))
|
err := s.ValidateOutput(reflect.TypeOf(tc.fn))
|
||||||
if err == nil && tcase.Err != nil {
|
if !errors.Is(err, tc.err) {
|
||||||
t.Errorf("expected an error: '%s'", tcase.Err.Error())
|
t.Fatalf("expected the error <%s> got <%s>", tc.err, err)
|
||||||
t.FailNow()
|
}
|
||||||
}
|
})
|
||||||
if err != nil && tcase.Err == nil {
|
}
|
||||||
t.Errorf("unexpected error: '%s'", err.Error())
|
}
|
||||||
t.FailNow()
|
|
||||||
}
|
func TestServiceValidation(t *testing.T) {
|
||||||
|
|
||||||
if err != nil && tcase.Err != nil {
|
tt := []struct {
|
||||||
if !errors.Is(err, tcase.Err) {
|
name string
|
||||||
t.Errorf("expected the error <%s> got <%s>", tcase.Err, err)
|
in []*config.Parameter
|
||||||
t.FailNow()
|
out []*config.Parameter
|
||||||
}
|
fn interface{}
|
||||||
|
err error
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "missing context",
|
||||||
|
fn: func() {},
|
||||||
|
err: ErrMissingHandlerContextArgument,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "invalid context",
|
||||||
|
fn: func(int) {},
|
||||||
|
err: ErrInvalidHandlerContextArgument,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "missing error",
|
||||||
|
fn: func(context.Context) {},
|
||||||
|
err: ErrMissingHandlerErrorArgument,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "invalid error",
|
||||||
|
fn: func(context.Context) int { return 1 },
|
||||||
|
err: ErrInvalidHandlerErrorArgument,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "no in no out",
|
||||||
|
fn: func(context.Context) api.Err { return api.ErrSuccess },
|
||||||
|
err: nil,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "unamed in",
|
||||||
|
in: []*config.Parameter{
|
||||||
|
{
|
||||||
|
Rename: "", // should be ignored
|
||||||
|
GoType: reflect.TypeOf(int(0)),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
fn: func(context.Context) api.Err { return api.ErrSuccess },
|
||||||
|
err: nil,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "missing in",
|
||||||
|
in: []*config.Parameter{
|
||||||
|
{
|
||||||
|
Rename: "Test1",
|
||||||
|
GoType: reflect.TypeOf(int(0)),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
fn: func(context.Context) api.Err { return api.ErrSuccess },
|
||||||
|
err: ErrMissingHandlerInputArgument,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "valid in",
|
||||||
|
in: []*config.Parameter{
|
||||||
|
{
|
||||||
|
Rename: "Test1",
|
||||||
|
GoType: reflect.TypeOf(int(0)),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
fn: func(context.Context, struct{ Test1 int }) api.Err { return api.ErrSuccess },
|
||||||
|
err: nil,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "optional in not ptr",
|
||||||
|
in: []*config.Parameter{
|
||||||
|
{
|
||||||
|
Rename: "Test1",
|
||||||
|
GoType: reflect.TypeOf(int(0)),
|
||||||
|
Optional: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
fn: func(context.Context, struct{ Test1 int }) api.Err { return api.ErrSuccess },
|
||||||
|
err: ErrWrongParamTypeFromConfig,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "valid optional in",
|
||||||
|
in: []*config.Parameter{
|
||||||
|
{
|
||||||
|
Rename: "Test1",
|
||||||
|
GoType: reflect.TypeOf(int(0)),
|
||||||
|
Optional: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
fn: func(context.Context, struct{ Test1 *int }) api.Err { return api.ErrSuccess },
|
||||||
|
err: nil,
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
name: "unamed out",
|
||||||
|
out: []*config.Parameter{
|
||||||
|
{
|
||||||
|
Rename: "", // should be ignored
|
||||||
|
GoType: reflect.TypeOf(int(0)),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
fn: func(context.Context) api.Err { return api.ErrSuccess },
|
||||||
|
err: nil,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "missing out struct",
|
||||||
|
out: []*config.Parameter{
|
||||||
|
{
|
||||||
|
Rename: "Test1",
|
||||||
|
GoType: reflect.TypeOf(int(0)),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
fn: func(context.Context) api.Err { return api.ErrSuccess },
|
||||||
|
err: ErrMissingHandlerOutputArgument,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "invalid out struct type",
|
||||||
|
out: []*config.Parameter{
|
||||||
|
{
|
||||||
|
Rename: "Test1",
|
||||||
|
GoType: reflect.TypeOf(int(0)),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
fn: func(context.Context) (int, api.Err) { return 0, api.ErrSuccess },
|
||||||
|
err: ErrWrongOutputArgumentType,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "missing out",
|
||||||
|
out: []*config.Parameter{
|
||||||
|
{
|
||||||
|
Rename: "Test1",
|
||||||
|
GoType: reflect.TypeOf(int(0)),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
fn: func(context.Context) (*struct{}, api.Err) { return nil, api.ErrSuccess },
|
||||||
|
err: ErrMissingConfigArgument,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "valid out",
|
||||||
|
out: []*config.Parameter{
|
||||||
|
{
|
||||||
|
Rename: "Test1",
|
||||||
|
GoType: reflect.TypeOf(int(0)),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
fn: func(context.Context) (*struct{ Test1 int }, api.Err) { return nil, api.ErrSuccess },
|
||||||
|
err: nil,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "optional out not ptr",
|
||||||
|
out: []*config.Parameter{
|
||||||
|
{
|
||||||
|
Rename: "Test1",
|
||||||
|
GoType: reflect.TypeOf(int(0)),
|
||||||
|
Optional: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
fn: func(context.Context) (*struct{ Test1 *int }, api.Err) { return nil, api.ErrSuccess },
|
||||||
|
err: ErrWrongParamTypeFromConfig,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range tt {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
service := config.Service{
|
||||||
|
Input: make(map[string]*config.Parameter),
|
||||||
|
Output: make(map[string]*config.Parameter),
|
||||||
|
}
|
||||||
|
|
||||||
|
// fill service with arguments
|
||||||
|
if tc.in != nil && len(tc.in) > 0 {
|
||||||
|
for i, in := range tc.in {
|
||||||
|
service.Input[fmt.Sprintf("%d", i)] = in
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if tc.out != nil && len(tc.out) > 0 {
|
||||||
|
for i, out := range tc.out {
|
||||||
|
service.Output[fmt.Sprintf("%d", i)] = out
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
s := BuildSignature(service)
|
||||||
|
|
||||||
|
err := s.ValidateInput(reflect.TypeOf(tc.fn))
|
||||||
|
if err != nil {
|
||||||
|
if !errors.Is(err, tc.err) {
|
||||||
|
t.Fatalf("expected the error <%s> got <%s>", tc.err, err)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
err = s.ValidateOutput(reflect.TypeOf(tc.fn))
|
||||||
|
if err != nil {
|
||||||
|
if !errors.Is(err, tc.err) {
|
||||||
|
t.Fatalf("expected the error <%s> got <%s>", tc.err, err)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// no error encountered but expected 1
|
||||||
|
if tc.err != nil {
|
||||||
|
t.Fatalf("expected an error <%v>", tc.err)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
|
@ -66,17 +66,24 @@ func (i *T) GetQuery(req http.Request) error {
|
||||||
query := req.URL.Query()
|
query := req.URL.Query()
|
||||||
|
|
||||||
for name, param := range i.service.Query {
|
for name, param := range i.service.Query {
|
||||||
value, exist := query[name]
|
values, exist := query[name]
|
||||||
|
|
||||||
if !exist && !param.Optional {
|
|
||||||
return fmt.Errorf("%s: %w", name, ErrMissingRequiredParam)
|
|
||||||
}
|
|
||||||
|
|
||||||
if !exist {
|
if !exist {
|
||||||
|
if !param.Optional {
|
||||||
|
return fmt.Errorf("%s: %w", name, ErrMissingRequiredParam)
|
||||||
|
}
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
parsed := parseParameter(value)
|
var parsed interface{}
|
||||||
|
|
||||||
|
// consider element instead of slice or elements when only 1
|
||||||
|
if len(values) == 1 {
|
||||||
|
parsed = parseParameter(values[0])
|
||||||
|
} else { // consider slice
|
||||||
|
parsed = parseParameter(values)
|
||||||
|
}
|
||||||
|
|
||||||
cast, valid := param.Validator(parsed)
|
cast, valid := param.Validator(parsed)
|
||||||
if !valid {
|
if !valid {
|
||||||
return fmt.Errorf("%s: %w", name, ErrInvalidType)
|
return fmt.Errorf("%s: %w", name, ErrInvalidType)
|
||||||
|
@ -99,17 +106,32 @@ func (i *T) GetForm(req http.Request) error {
|
||||||
ct := req.Header.Get("Content-Type")
|
ct := req.Header.Get("Content-Type")
|
||||||
switch {
|
switch {
|
||||||
case strings.HasPrefix(ct, "application/json"):
|
case strings.HasPrefix(ct, "application/json"):
|
||||||
return i.parseJSON(req)
|
err := i.parseJSON(req)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
case strings.HasPrefix(ct, "application/x-www-form-urlencoded"):
|
case strings.HasPrefix(ct, "application/x-www-form-urlencoded"):
|
||||||
return i.parseUrlencoded(req)
|
err := i.parseUrlencoded(req)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
case strings.HasPrefix(ct, "multipart/form-data; boundary="):
|
case strings.HasPrefix(ct, "multipart/form-data; boundary="):
|
||||||
return i.parseMultipart(req)
|
err := i.parseMultipart(req)
|
||||||
|
if err != nil {
|
||||||
default:
|
return err
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// fail on at least 1 mandatory form param when there is no body
|
||||||
|
for name, param := range i.service.Form {
|
||||||
|
_, exists := i.Data[param.Rename]
|
||||||
|
if !exists && !param.Optional {
|
||||||
|
return fmt.Errorf("%s: %w", name, ErrMissingRequiredParam)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// parseJSON parses JSON from the request body inside 'Form'
|
// parseJSON parses JSON from the request body inside 'Form'
|
||||||
|
@ -129,10 +151,6 @@ func (i *T) parseJSON(req http.Request) error {
|
||||||
for name, param := range i.service.Form {
|
for name, param := range i.service.Form {
|
||||||
value, exist := parsed[name]
|
value, exist := parsed[name]
|
||||||
|
|
||||||
if !exist && !param.Optional {
|
|
||||||
return fmt.Errorf("%s: %w", name, ErrMissingRequiredParam)
|
|
||||||
}
|
|
||||||
|
|
||||||
if !exist {
|
if !exist {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
@ -155,17 +173,21 @@ func (i *T) parseUrlencoded(req http.Request) error {
|
||||||
}
|
}
|
||||||
|
|
||||||
for name, param := range i.service.Form {
|
for name, param := range i.service.Form {
|
||||||
value, exist := req.PostForm[name]
|
values, exist := req.PostForm[name]
|
||||||
|
|
||||||
if !exist && !param.Optional {
|
|
||||||
return fmt.Errorf("%s: %w", name, ErrMissingRequiredParam)
|
|
||||||
}
|
|
||||||
|
|
||||||
if !exist {
|
if !exist {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
parsed := parseParameter(value)
|
var parsed interface{}
|
||||||
|
|
||||||
|
// consider element instead of slice or elements when only 1
|
||||||
|
if len(values) == 1 {
|
||||||
|
parsed = parseParameter(values[0])
|
||||||
|
} else { // consider slice
|
||||||
|
parsed = parseParameter(values)
|
||||||
|
}
|
||||||
|
|
||||||
cast, valid := param.Validator(parsed)
|
cast, valid := param.Validator(parsed)
|
||||||
if !valid {
|
if !valid {
|
||||||
return fmt.Errorf("%s: %w", name, ErrInvalidType)
|
return fmt.Errorf("%s: %w", name, ErrInvalidType)
|
||||||
|
@ -185,7 +207,7 @@ func (i *T) parseMultipart(req http.Request) error {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return fmt.Errorf("%s: %w", err, ErrInvalidMultipart)
|
||||||
}
|
}
|
||||||
|
|
||||||
err = mpr.Parse()
|
err = mpr.Parse()
|
||||||
|
@ -196,10 +218,6 @@ func (i *T) parseMultipart(req http.Request) error {
|
||||||
for name, param := range i.service.Form {
|
for name, param := range i.service.Form {
|
||||||
component, exist := mpr.Data[name]
|
component, exist := mpr.Data[name]
|
||||||
|
|
||||||
if !exist && !param.Optional {
|
|
||||||
return fmt.Errorf("%s: %w", name, ErrMissingRequiredParam)
|
|
||||||
}
|
|
||||||
|
|
||||||
if !exist {
|
if !exist {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
|
@ -135,13 +135,11 @@ func TestStoreWithUri(t *testing.T) {
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if test.Err != nil {
|
if test.Err != nil {
|
||||||
if !errors.Is(err, test.Err) {
|
if !errors.Is(err, test.Err) {
|
||||||
t.Errorf("expected error <%s>, got <%s>", test.Err, err)
|
t.Fatalf("expected error <%s>, got <%s>", test.Err, err)
|
||||||
t.FailNow()
|
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
t.Errorf("unexpected error <%s>", err)
|
t.Fatalf("unexpected error <%s>", err)
|
||||||
t.FailNow()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(store.Data) != len(service.Input) {
|
if len(store.Data) != len(service.Input) {
|
||||||
|
@ -183,14 +181,14 @@ func TestExtractQuery(t *testing.T) {
|
||||||
Query: "a",
|
Query: "a",
|
||||||
Err: nil,
|
Err: nil,
|
||||||
ParamNames: []string{"a"},
|
ParamNames: []string{"a"},
|
||||||
ParamValues: [][]string{[]string{""}},
|
ParamValues: [][]string{{""}},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
ServiceParam: []string{"a"},
|
ServiceParam: []string{"a"},
|
||||||
Query: "a&b",
|
Query: "a&b",
|
||||||
Err: nil,
|
Err: nil,
|
||||||
ParamNames: []string{"a"},
|
ParamNames: []string{"a"},
|
||||||
ParamValues: [][]string{[]string{""}},
|
ParamValues: [][]string{{""}},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
ServiceParam: []string{"a", "missing"},
|
ServiceParam: []string{"a", "missing"},
|
||||||
|
@ -204,40 +202,40 @@ func TestExtractQuery(t *testing.T) {
|
||||||
Query: "a&b",
|
Query: "a&b",
|
||||||
Err: nil,
|
Err: nil,
|
||||||
ParamNames: []string{"a", "b"},
|
ParamNames: []string{"a", "b"},
|
||||||
ParamValues: [][]string{[]string{""}, []string{""}},
|
ParamValues: [][]string{{""}, {""}},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
ServiceParam: []string{"a"},
|
ServiceParam: []string{"a"},
|
||||||
Err: nil,
|
Err: nil,
|
||||||
Query: "a=",
|
Query: "a=",
|
||||||
ParamNames: []string{"a"},
|
ParamNames: []string{"a"},
|
||||||
ParamValues: [][]string{[]string{""}},
|
ParamValues: [][]string{{""}},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
ServiceParam: []string{"a", "b"},
|
ServiceParam: []string{"a", "b"},
|
||||||
Err: nil,
|
Err: nil,
|
||||||
Query: "a=&b=x",
|
Query: "a=&b=x",
|
||||||
ParamNames: []string{"a", "b"},
|
ParamNames: []string{"a", "b"},
|
||||||
ParamValues: [][]string{[]string{""}, []string{"x"}},
|
ParamValues: [][]string{{""}, {"x"}},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
ServiceParam: []string{"a", "c"},
|
ServiceParam: []string{"a", "c"},
|
||||||
Err: nil,
|
Err: nil,
|
||||||
Query: "a=b&c=d",
|
Query: "a=b&c=d",
|
||||||
ParamNames: []string{"a", "c"},
|
ParamNames: []string{"a", "c"},
|
||||||
ParamValues: [][]string{[]string{"b"}, []string{"d"}},
|
ParamValues: [][]string{{"b"}, {"d"}},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
ServiceParam: []string{"a", "c"},
|
ServiceParam: []string{"a", "c"},
|
||||||
Err: nil,
|
Err: nil,
|
||||||
Query: "a=b&c=d&a=x",
|
Query: "a=b&c=d&a=x",
|
||||||
ParamNames: []string{"a", "c"},
|
ParamNames: []string{"a", "c"},
|
||||||
ParamValues: [][]string{[]string{"b", "x"}, []string{"d"}},
|
ParamValues: [][]string{{"b", "x"}, {"d"}},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
for i, test := range tests {
|
for i, test := range tests {
|
||||||
t.Run(fmt.Sprintf("request.%d", i), func(t *testing.T) {
|
t.Run(fmt.Sprintf("request[%d]", i), func(t *testing.T) {
|
||||||
|
|
||||||
store := New(getServiceWithQuery(test.ServiceParam...))
|
store := New(getServiceWithQuery(test.ServiceParam...))
|
||||||
|
|
||||||
|
@ -246,19 +244,16 @@ func TestExtractQuery(t *testing.T) {
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if test.Err != nil {
|
if test.Err != nil {
|
||||||
if !errors.Is(err, test.Err) {
|
if !errors.Is(err, test.Err) {
|
||||||
t.Errorf("expected error <%s>, got <%s>", test.Err, err)
|
t.Fatalf("expected error <%s>, got <%s>", test.Err, err)
|
||||||
t.FailNow()
|
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
t.Errorf("unexpected error <%s>", err)
|
t.Fatalf("unexpected error <%s>", err)
|
||||||
t.FailNow()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if test.ParamNames == nil || test.ParamValues == nil {
|
if test.ParamNames == nil || test.ParamValues == nil {
|
||||||
if len(store.Data) != 0 {
|
if len(store.Data) != 0 {
|
||||||
t.Errorf("expected no GET parameters and got %d", len(store.Data))
|
t.Fatalf("expected no GET parameters and got %d", len(store.Data))
|
||||||
t.FailNow()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// no param to check
|
// no param to check
|
||||||
|
@ -266,8 +261,7 @@ func TestExtractQuery(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(test.ParamNames) != len(test.ParamValues) {
|
if len(test.ParamNames) != len(test.ParamValues) {
|
||||||
t.Errorf("invalid test: names and values differ in size (%d vs %d)", len(test.ParamNames), len(test.ParamValues))
|
t.Fatalf("invalid test: names and values differ in size (%d vs %d)", len(test.ParamNames), len(test.ParamValues))
|
||||||
t.FailNow()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
for pi, pName := range test.ParamNames {
|
for pi, pName := range test.ParamNames {
|
||||||
|
@ -276,29 +270,35 @@ func TestExtractQuery(t *testing.T) {
|
||||||
t.Run(pName, func(t *testing.T) {
|
t.Run(pName, func(t *testing.T) {
|
||||||
param, isset := store.Data[pName]
|
param, isset := store.Data[pName]
|
||||||
if !isset {
|
if !isset {
|
||||||
t.Errorf("param does not exist")
|
t.Fatalf("param does not exist")
|
||||||
t.FailNow()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// single value, should return a single element
|
||||||
|
if len(values) == 1 {
|
||||||
|
cast, canCast := param.(string)
|
||||||
|
if !canCast {
|
||||||
|
t.Fatalf("should return a string (got '%v')", cast)
|
||||||
|
}
|
||||||
|
if values[0] != cast {
|
||||||
|
t.Fatalf("should return '%s' (got '%s')", values[0], cast)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// multiple values, should return a slice
|
||||||
cast, canCast := param.([]interface{})
|
cast, canCast := param.([]interface{})
|
||||||
if !canCast {
|
if !canCast {
|
||||||
t.Errorf("should return a []string (got '%v')", cast)
|
t.Fatalf("should return a []string (got '%v')", cast)
|
||||||
t.FailNow()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(cast) != len(values) {
|
if len(cast) != len(values) {
|
||||||
t.Errorf("should return %d string(s) (got '%d')", len(values), len(cast))
|
t.Fatalf("should return %d string(s) (got '%d')", len(values), len(cast))
|
||||||
t.FailNow()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
for vi, value := range values {
|
for vi, value := range values {
|
||||||
|
|
||||||
t.Run(fmt.Sprintf("value.%d", vi), func(t *testing.T) {
|
|
||||||
if value != cast[vi] {
|
if value != cast[vi] {
|
||||||
t.Errorf("should return '%s' (got '%s')", value, cast[vi])
|
t.Fatalf("should return '%s' (got '%s')", value, cast[vi])
|
||||||
t.FailNow()
|
|
||||||
}
|
}
|
||||||
})
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
@ -326,9 +326,7 @@ func TestStoreWithUrlEncodedFormParseError(t *testing.T) {
|
||||||
store := New(nil)
|
store := New(nil)
|
||||||
err := store.GetForm(*req)
|
err := store.GetForm(*req)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
t.Errorf("expected malformed urlencoded to have FailNow being parsed (got %d elements)", len(store.Data))
|
t.Fatalf("expected malformed urlencoded to have FailNow being parsed (got %d elements)", len(store.Data))
|
||||||
t.FailNow()
|
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
func TestExtractFormUrlEncoded(t *testing.T) {
|
func TestExtractFormUrlEncoded(t *testing.T) {
|
||||||
|
@ -359,14 +357,14 @@ func TestExtractFormUrlEncoded(t *testing.T) {
|
||||||
URLEncoded: "a",
|
URLEncoded: "a",
|
||||||
Err: nil,
|
Err: nil,
|
||||||
ParamNames: []string{"a"},
|
ParamNames: []string{"a"},
|
||||||
ParamValues: [][]string{[]string{""}},
|
ParamValues: [][]string{{""}},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
ServiceParams: []string{"a"},
|
ServiceParams: []string{"a"},
|
||||||
URLEncoded: "a&b",
|
URLEncoded: "a&b",
|
||||||
Err: nil,
|
Err: nil,
|
||||||
ParamNames: []string{"a"},
|
ParamNames: []string{"a"},
|
||||||
ParamValues: [][]string{[]string{""}},
|
ParamValues: [][]string{{""}},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
ServiceParams: []string{"a", "missing"},
|
ServiceParams: []string{"a", "missing"},
|
||||||
|
@ -380,35 +378,35 @@ func TestExtractFormUrlEncoded(t *testing.T) {
|
||||||
URLEncoded: "a&b",
|
URLEncoded: "a&b",
|
||||||
Err: nil,
|
Err: nil,
|
||||||
ParamNames: []string{"a", "b"},
|
ParamNames: []string{"a", "b"},
|
||||||
ParamValues: [][]string{[]string{""}, []string{""}},
|
ParamValues: [][]string{{""}, {""}},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
ServiceParams: []string{"a"},
|
ServiceParams: []string{"a"},
|
||||||
Err: nil,
|
Err: nil,
|
||||||
URLEncoded: "a=",
|
URLEncoded: "a=",
|
||||||
ParamNames: []string{"a"},
|
ParamNames: []string{"a"},
|
||||||
ParamValues: [][]string{[]string{""}},
|
ParamValues: [][]string{{""}},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
ServiceParams: []string{"a", "b"},
|
ServiceParams: []string{"a", "b"},
|
||||||
Err: nil,
|
Err: nil,
|
||||||
URLEncoded: "a=&b=x",
|
URLEncoded: "a=&b=x",
|
||||||
ParamNames: []string{"a", "b"},
|
ParamNames: []string{"a", "b"},
|
||||||
ParamValues: [][]string{[]string{""}, []string{"x"}},
|
ParamValues: [][]string{{""}, {"x"}},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
ServiceParams: []string{"a", "c"},
|
ServiceParams: []string{"a", "c"},
|
||||||
Err: nil,
|
Err: nil,
|
||||||
URLEncoded: "a=b&c=d",
|
URLEncoded: "a=b&c=d",
|
||||||
ParamNames: []string{"a", "c"},
|
ParamNames: []string{"a", "c"},
|
||||||
ParamValues: [][]string{[]string{"b"}, []string{"d"}},
|
ParamValues: [][]string{{"b"}, {"d"}},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
ServiceParams: []string{"a", "c"},
|
ServiceParams: []string{"a", "c"},
|
||||||
Err: nil,
|
Err: nil,
|
||||||
URLEncoded: "a=b&c=d&a=x",
|
URLEncoded: "a=b&c=d&a=x",
|
||||||
ParamNames: []string{"a", "c"},
|
ParamNames: []string{"a", "c"},
|
||||||
ParamValues: [][]string{[]string{"b", "x"}, []string{"d"}},
|
ParamValues: [][]string{{"b", "x"}, {"d"}},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -424,19 +422,16 @@ func TestExtractFormUrlEncoded(t *testing.T) {
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if test.Err != nil {
|
if test.Err != nil {
|
||||||
if !errors.Is(err, test.Err) {
|
if !errors.Is(err, test.Err) {
|
||||||
t.Errorf("expected error <%s>, got <%s>", test.Err, err)
|
t.Fatalf("expected error <%s>, got <%s>", test.Err, err)
|
||||||
t.FailNow()
|
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
t.Errorf("unexpected error <%s>", err)
|
t.Fatalf("unexpected error <%s>", err)
|
||||||
t.FailNow()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if test.ParamNames == nil || test.ParamValues == nil {
|
if test.ParamNames == nil || test.ParamValues == nil {
|
||||||
if len(store.Data) != 0 {
|
if len(store.Data) != 0 {
|
||||||
t.Errorf("expected no GET parameters and got %d", len(store.Data))
|
t.Fatalf("expected no GET parameters and got %d", len(store.Data))
|
||||||
t.FailNow()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// no param to check
|
// no param to check
|
||||||
|
@ -444,8 +439,7 @@ func TestExtractFormUrlEncoded(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(test.ParamNames) != len(test.ParamValues) {
|
if len(test.ParamNames) != len(test.ParamValues) {
|
||||||
t.Errorf("invalid test: names and values differ in size (%d vs %d)", len(test.ParamNames), len(test.ParamValues))
|
t.Fatalf("invalid test: names and values differ in size (%d vs %d)", len(test.ParamNames), len(test.ParamValues))
|
||||||
t.FailNow()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
for pi, key := range test.ParamNames {
|
for pi, key := range test.ParamNames {
|
||||||
|
@ -454,29 +448,35 @@ func TestExtractFormUrlEncoded(t *testing.T) {
|
||||||
t.Run(key, func(t *testing.T) {
|
t.Run(key, func(t *testing.T) {
|
||||||
param, isset := store.Data[key]
|
param, isset := store.Data[key]
|
||||||
if !isset {
|
if !isset {
|
||||||
t.Errorf("param does not exist")
|
t.Fatalf("param does not exist")
|
||||||
t.FailNow()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// single value, should return a single element
|
||||||
|
if len(values) == 1 {
|
||||||
|
cast, canCast := param.(string)
|
||||||
|
if !canCast {
|
||||||
|
t.Fatalf("should return a string (got '%v')", cast)
|
||||||
|
}
|
||||||
|
if values[0] != cast {
|
||||||
|
t.Fatalf("should return '%s' (got '%s')", values[0], cast)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// multiple values, should return a slice
|
||||||
cast, canCast := param.([]interface{})
|
cast, canCast := param.([]interface{})
|
||||||
if !canCast {
|
if !canCast {
|
||||||
t.Errorf("should return a []interface{} (got '%v')", cast)
|
t.Fatalf("should return a []string (got '%v')", cast)
|
||||||
t.FailNow()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(cast) != len(values) {
|
if len(cast) != len(values) {
|
||||||
t.Errorf("should return %d string(s) (got '%d')", len(values), len(cast))
|
t.Fatalf("should return %d string(s) (got '%d')", len(values), len(cast))
|
||||||
t.FailNow()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
for vi, value := range values {
|
for vi, value := range values {
|
||||||
|
|
||||||
t.Run(fmt.Sprintf("value.%d", vi), func(t *testing.T) {
|
|
||||||
if value != cast[vi] {
|
if value != cast[vi] {
|
||||||
t.Errorf("should return '%s' (got '%s')", value, cast[vi])
|
t.Fatalf("should return '%s' (got '%s')", value, cast[vi])
|
||||||
t.FailNow()
|
|
||||||
}
|
}
|
||||||
})
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
@ -567,19 +567,16 @@ func TestJsonParameters(t *testing.T) {
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if test.Err != nil {
|
if test.Err != nil {
|
||||||
if !errors.Is(err, test.Err) {
|
if !errors.Is(err, test.Err) {
|
||||||
t.Errorf("expected error <%s>, got <%s>", test.Err, err)
|
t.Fatalf("expected error <%s>, got <%s>", test.Err, err)
|
||||||
t.FailNow()
|
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
t.Errorf("unexpected error <%s>", err)
|
t.Fatalf("unexpected error <%s>", err)
|
||||||
t.FailNow()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if test.ParamNames == nil || test.ParamValues == nil {
|
if test.ParamNames == nil || test.ParamValues == nil {
|
||||||
if len(store.Data) != 0 {
|
if len(store.Data) != 0 {
|
||||||
t.Errorf("expected no JSON parameters and got %d", len(store.Data))
|
t.Fatalf("expected no JSON parameters and got %d", len(store.Data))
|
||||||
t.FailNow()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// no param to check
|
// no param to check
|
||||||
|
@ -587,8 +584,7 @@ func TestJsonParameters(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(test.ParamNames) != len(test.ParamValues) {
|
if len(test.ParamNames) != len(test.ParamValues) {
|
||||||
t.Errorf("invalid test: names and values differ in size (%d vs %d)", len(test.ParamNames), len(test.ParamValues))
|
t.Fatalf("invalid test: names and values differ in size (%d vs %d)", len(test.ParamNames), len(test.ParamValues))
|
||||||
t.FailNow()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
for pi, pName := range test.ParamNames {
|
for pi, pName := range test.ParamNames {
|
||||||
|
@ -599,8 +595,7 @@ func TestJsonParameters(t *testing.T) {
|
||||||
|
|
||||||
param, isset := store.Data[key]
|
param, isset := store.Data[key]
|
||||||
if !isset {
|
if !isset {
|
||||||
t.Errorf("store should contain element with key '%s'", key)
|
t.Fatalf("store should contain element with key '%s'", key)
|
||||||
t.FailNow()
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -610,13 +605,11 @@ func TestJsonParameters(t *testing.T) {
|
||||||
paramValueType := reflect.TypeOf(param)
|
paramValueType := reflect.TypeOf(param)
|
||||||
|
|
||||||
if valueType != paramValueType {
|
if valueType != paramValueType {
|
||||||
t.Errorf("should be of type %v (got '%v')", valueType, paramValueType)
|
t.Fatalf("should be of type %v (got '%v')", valueType, paramValueType)
|
||||||
t.FailNow()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if paramValue != value {
|
if paramValue != value {
|
||||||
t.Errorf("should return %v (got '%v')", value, paramValue)
|
t.Fatalf("should return %v (got '%v')", value, paramValue)
|
||||||
t.FailNow()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
})
|
})
|
||||||
|
@ -724,19 +717,16 @@ x
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if test.Err != nil {
|
if test.Err != nil {
|
||||||
if !errors.Is(err, test.Err) {
|
if !errors.Is(err, test.Err) {
|
||||||
t.Errorf("expected error <%s>, got <%s>", test.Err, err)
|
t.Fatalf("expected error <%s>, got <%s>", test.Err, err)
|
||||||
t.FailNow()
|
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
t.Errorf("unexpected error <%s>", err)
|
t.Fatalf("unexpected error <%s>", err)
|
||||||
t.FailNow()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if test.ParamNames == nil || test.ParamValues == nil {
|
if test.ParamNames == nil || test.ParamValues == nil {
|
||||||
if len(store.Data) != 0 {
|
if len(store.Data) != 0 {
|
||||||
t.Errorf("expected no JSON parameters and got %d", len(store.Data))
|
t.Fatalf("expected no JSON parameters and got %d", len(store.Data))
|
||||||
t.FailNow()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// no param to check
|
// no param to check
|
||||||
|
@ -744,8 +734,7 @@ x
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(test.ParamNames) != len(test.ParamValues) {
|
if len(test.ParamNames) != len(test.ParamValues) {
|
||||||
t.Errorf("invalid test: names and values differ in size (%d vs %d)", len(test.ParamNames), len(test.ParamValues))
|
t.Fatalf("invalid test: names and values differ in size (%d vs %d)", len(test.ParamNames), len(test.ParamValues))
|
||||||
t.FailNow()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
for pi, key := range test.ParamNames {
|
for pi, key := range test.ParamNames {
|
||||||
|
@ -755,8 +744,7 @@ x
|
||||||
|
|
||||||
param, isset := store.Data[key]
|
param, isset := store.Data[key]
|
||||||
if !isset {
|
if !isset {
|
||||||
t.Errorf("store should contain element with key '%s'", key)
|
t.Fatalf("store should contain element with key '%s'", key)
|
||||||
t.FailNow()
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -766,13 +754,11 @@ x
|
||||||
paramValueType := reflect.TypeOf(param)
|
paramValueType := reflect.TypeOf(param)
|
||||||
|
|
||||||
if valueType != paramValueType {
|
if valueType != paramValueType {
|
||||||
t.Errorf("should be of type %v (got '%v')", valueType, paramValueType)
|
t.Fatalf("should be of type %v (got '%v')", valueType, paramValueType)
|
||||||
t.FailNow()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if paramValue != value {
|
if paramValue != value {
|
||||||
t.Errorf("should return %v (got '%v')", value, paramValue)
|
t.Fatalf("should return %v (got '%v')", value, paramValue)
|
||||||
t.FailNow()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
})
|
})
|
||||||
|
|
|
@ -0,0 +1,60 @@
|
||||||
|
package aicra
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/xdrm-io/aicra/api"
|
||||||
|
)
|
||||||
|
|
||||||
|
// response for an service call
|
||||||
|
type response struct {
|
||||||
|
Data map[string]interface{}
|
||||||
|
Status int
|
||||||
|
err api.Err
|
||||||
|
}
|
||||||
|
|
||||||
|
// newResponse creates an empty response.
|
||||||
|
func newResponse() *response {
|
||||||
|
return &response{
|
||||||
|
Status: http.StatusOK,
|
||||||
|
Data: make(map[string]interface{}),
|
||||||
|
err: api.ErrFailure,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithError sets the response error
|
||||||
|
func (r *response) WithError(err api.Err) *response {
|
||||||
|
r.err = err
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithValue sets a response value
|
||||||
|
func (r *response) WithValue(name string, value interface{}) *response {
|
||||||
|
r.Data[name] = value
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
// MarshalJSON generates the JSON representation of the response
|
||||||
|
//
|
||||||
|
// implements json.Marshaler
|
||||||
|
func (r *response) MarshalJSON() ([]byte, error) {
|
||||||
|
fmt := make(map[string]interface{})
|
||||||
|
for k, v := range r.Data {
|
||||||
|
fmt[k] = v
|
||||||
|
}
|
||||||
|
fmt["error"] = r.err
|
||||||
|
return json.Marshal(fmt)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ServeHTTP writes the response representation back to the http.ResponseWriter
|
||||||
|
//
|
||||||
|
// implements http.Handler
|
||||||
|
func (res *response) ServeHTTP(w http.ResponseWriter, r *http.Request) error {
|
||||||
|
w.WriteHeader(res.err.Status)
|
||||||
|
encoded, err := json.Marshal(res)
|
||||||
|
if err == nil {
|
||||||
|
w.Write(encoded)
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
|
@ -0,0 +1,95 @@
|
||||||
|
package aicra
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/xdrm-io/aicra/api"
|
||||||
|
)
|
||||||
|
|
||||||
|
func printEscaped(raw string) string {
|
||||||
|
raw = strings.ReplaceAll(raw, "\n", "\\n")
|
||||||
|
raw = strings.ReplaceAll(raw, "\r", "\\r")
|
||||||
|
return raw
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestResponseJSON(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
tt := []struct {
|
||||||
|
name string
|
||||||
|
err api.Err
|
||||||
|
data map[string]interface{}
|
||||||
|
json string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "empty success response",
|
||||||
|
err: api.ErrSuccess,
|
||||||
|
data: map[string]interface{}{},
|
||||||
|
json: `{"error":{"code":0,"reason":"all right"}}`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "empty failure response",
|
||||||
|
err: api.ErrFailure,
|
||||||
|
data: map[string]interface{}{},
|
||||||
|
json: `{"error":{"code":1,"reason":"it failed"}}`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "empty unknown error response",
|
||||||
|
err: api.ErrUnknown,
|
||||||
|
data: map[string]interface{}{},
|
||||||
|
json: `{"error":{"code":-1,"reason":"unknown error"}}`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "success with data before err",
|
||||||
|
err: api.ErrSuccess,
|
||||||
|
data: map[string]interface{}{"a": 12},
|
||||||
|
json: `{"a":12,"error":{"code":0,"reason":"all right"}}`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "success with data right before err",
|
||||||
|
err: api.ErrSuccess,
|
||||||
|
data: map[string]interface{}{"e": 12},
|
||||||
|
json: `{"e":12,"error":{"code":0,"reason":"all right"}}`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "success with data right after err",
|
||||||
|
err: api.ErrSuccess,
|
||||||
|
data: map[string]interface{}{"f": 12},
|
||||||
|
json: `{"error":{"code":0,"reason":"all right"},"f":12}`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "success with data after err",
|
||||||
|
err: api.ErrSuccess,
|
||||||
|
data: map[string]interface{}{"z": 12},
|
||||||
|
json: `{"error":{"code":0,"reason":"all right"},"z":12}`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "success with data around err",
|
||||||
|
err: api.ErrSuccess,
|
||||||
|
data: map[string]interface{}{"d": "before", "f": "after"},
|
||||||
|
json: `{"d":"before","error":{"code":0,"reason":"all right"},"f":"after"}`,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range tt {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
res := newResponse().WithError(tc.err)
|
||||||
|
for k, v := range tc.data {
|
||||||
|
res.WithValue(k, v)
|
||||||
|
}
|
||||||
|
|
||||||
|
raw, err := json.Marshal(res)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("cannot marshal to json: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if string(raw) != tc.json {
|
||||||
|
t.Fatalf("mismatching json:\nexpect: %v\nactual: %v", printEscaped(tc.json), printEscaped(string(raw)))
|
||||||
|
}
|
||||||
|
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -2,11 +2,24 @@ package validator_test
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"reflect"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/xdrm-io/aicra/validator"
|
"github.com/xdrm-io/aicra/validator"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func TestAny_ReflectType(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
var (
|
||||||
|
dt = validator.AnyType{}
|
||||||
|
expected = reflect.TypeOf(interface{}(nil))
|
||||||
|
)
|
||||||
|
if dt.GoType() != expected {
|
||||||
|
t.Fatalf("invalid GoType() %v ; expected %v", dt.GoType(), expected)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestAny_AvailableTypes(t *testing.T) {
|
func TestAny_AvailableTypes(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
|
|
|
@ -2,11 +2,24 @@ package validator_test
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"reflect"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/xdrm-io/aicra/validator"
|
"github.com/xdrm-io/aicra/validator"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func TestBool_ReflectType(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
var (
|
||||||
|
dt = validator.BoolType{}
|
||||||
|
expected = reflect.TypeOf(true)
|
||||||
|
)
|
||||||
|
if dt.GoType() != expected {
|
||||||
|
t.Fatalf("invalid GoType() %v ; expected %v", dt.GoType(), expected)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestBool_AvailableTypes(t *testing.T) {
|
func TestBool_AvailableTypes(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
|
|
|
@ -3,11 +3,24 @@ package validator_test
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"math"
|
"math"
|
||||||
|
"reflect"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/xdrm-io/aicra/validator"
|
"github.com/xdrm-io/aicra/validator"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func TestFloat64_ReflectType(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
var (
|
||||||
|
dt = validator.FloatType{}
|
||||||
|
expected = reflect.TypeOf(float64(0.0))
|
||||||
|
)
|
||||||
|
if dt.GoType() != expected {
|
||||||
|
t.Fatalf("invalid GoType() %v ; expected %v", dt.GoType(), expected)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestFloat64_AvailableTypes(t *testing.T) {
|
func TestFloat64_AvailableTypes(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
|
|
|
@ -3,11 +3,24 @@ package validator_test
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"math"
|
"math"
|
||||||
|
"reflect"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/xdrm-io/aicra/validator"
|
"github.com/xdrm-io/aicra/validator"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func TestInt_ReflectType(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
var (
|
||||||
|
dt = validator.IntType{}
|
||||||
|
expected = reflect.TypeOf(int(0))
|
||||||
|
)
|
||||||
|
if dt.GoType() != expected {
|
||||||
|
t.Fatalf("invalid GoType() %v ; expected %v", dt.GoType(), expected)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestInt_AvailableTypes(t *testing.T) {
|
func TestInt_AvailableTypes(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
|
@ -71,7 +84,7 @@ func TestInt_Values(t *testing.T) {
|
||||||
{uint(math.MaxInt64 + 1), false},
|
{uint(math.MaxInt64 + 1), false},
|
||||||
|
|
||||||
{float64(math.MinInt64), true},
|
{float64(math.MinInt64), true},
|
||||||
// we cannot just substract 1 because of how precision works
|
// we cannot just subtract 1 because of how precision works
|
||||||
{float64(math.MinInt64 - 1024 - 1), false},
|
{float64(math.MinInt64 - 1024 - 1), false},
|
||||||
|
|
||||||
// WARNING : this is due to how floats are compared
|
// WARNING : this is due to how floats are compared
|
||||||
|
|
|
@ -2,11 +2,24 @@ package validator_test
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"reflect"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/xdrm-io/aicra/validator"
|
"github.com/xdrm-io/aicra/validator"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func TestString_ReflectType(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
var (
|
||||||
|
dt = validator.StringType{}
|
||||||
|
expected = reflect.TypeOf(string("abc"))
|
||||||
|
)
|
||||||
|
if dt.GoType() != expected {
|
||||||
|
t.Fatalf("invalid GoType() %v ; expected %v", dt.GoType(), expected)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestString_AvailableTypes(t *testing.T) {
|
func TestString_AvailableTypes(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
|
|
|
@ -3,11 +3,24 @@ package validator_test
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"math"
|
"math"
|
||||||
|
"reflect"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/xdrm-io/aicra/validator"
|
"github.com/xdrm-io/aicra/validator"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func TestUint_ReflectType(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
var (
|
||||||
|
dt = validator.UintType{}
|
||||||
|
expected = reflect.TypeOf(uint(0))
|
||||||
|
)
|
||||||
|
if dt.GoType() != expected {
|
||||||
|
t.Fatalf("invalid GoType() %v ; expected %v", dt.GoType(), expected)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestUint_AvailableTypes(t *testing.T) {
|
func TestUint_AvailableTypes(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue