Files
go-omni/config/response_test.go

42 lines
1.5 KiB
Go

package config
import (
"strings"
"testing"
apierrors "git.yuntuo.hk/k2safe/go-omni/errors"
"git.yuntuo.hk/k2safe/go-omni/response"
)
func TestValidateEffectiveResponsePolicy(t *testing.T) {
catalog := apierrors.Catalog{DefaultStatus: 400, Definitions: map[string]apierrors.Definition{
"INVALID": {Code: 400002, Message: "invalid input"},
}}
other := catalog.Clone()
other.Definitions["INVALID"] = apierrors.Definition{Code: 400003, Message: "other input"}
formatter := response.MustNew(response.Config{CodeType: "int32", SuccessCode: 0, ErrorCode: 9999})
for _, tc := range []struct {
name string
encoder response.Encoder
wantError string
}{
{"incompatibleCode", response.RawJSON(response.MustNew(response.Config{CodeType: "int32", SuccessCode: 0, ErrorCode: 9999, Codes: map[string]any{"INVALID": 100}})), "conflicting"},
{"differentCatalog", response.MustWithErrors(other, formatter), "different error catalogs"},
{"matchingCatalog", response.MustWithErrors(catalog, formatter), ""},
{"rawJSON", response.RawJSON(response.MustNew(response.Config{CodeType: "int32", SuccessCode: 0, ErrorCode: 9999})), ""},
} {
t.Run(tc.name, func(t *testing.T) {
cfg := Default()
cfg.Errors, cfg.ResponseEncoder = catalog, tc.encoder
err := cfg.Validate()
if tc.wantError == "" {
if err != nil {
t.Fatal(err)
}
} else if err == nil || !strings.Contains(err.Error(), tc.wantError) {
t.Fatalf("want %q, got %v", tc.wantError, err)
}
})
}
}