Files
go-omni/config/errorParams_test.go

45 lines
1.7 KiB
Go

package config_test
import (
"encoding/json"
"os"
"path/filepath"
"testing"
"git.yuntuo.hk/k2safe/go-omni/config"
apierrors "git.yuntuo.hk/k2safe/go-omni/errors"
)
func TestTemplateConfigFiles(t *testing.T) {
for _, file := range []struct{ name, body string }{
{"config.json", `{"errors":{"defaultStatus":200,"definitions":{"LIMIT":{"code":"limit","message":"{label}:{max}","params":[{"name":"label","type":"string","example":"字段"},{"name":"max","type":"int64","example":9223372036854775807}]}}}}`},
{"config.yaml", "errors:\n defaultStatus: 200\n definitions:\n LIMIT:\n code: limit\n message: '{label}:{max}'\n params:\n - name: label\n type: string\n example: 字段\n - name: max\n type: int64\n example: 9223372036854775807\n"},
} {
t.Run(file.name, func(t *testing.T) {
path := filepath.Join(t.TempDir(), file.name)
if err := os.WriteFile(path, []byte(file.body), 0600); err != nil {
t.Fatal(err)
}
cfg, err := config.LoadFile(path)
if err != nil {
t.Fatal(err)
}
r := apierrors.MustRegistry(cfg.Errors)
if r.Example("LIMIT").Message != "字段:9223372036854775807" {
t.Fatal(r.Example("LIMIT"))
}
cfg.Errors.Definitions["LIMIT"].Params[0].Name = "mutated"
var supplied map[string]any
if err := apierrors.DecodeCatalogJSON([]byte(`{"label":"字段","max":9223372036854775807}`), &supplied); err != nil {
t.Fatal(err)
}
if _, ok := supplied["max"].(json.Number); !ok {
t.Fatal("number precision lost")
}
if r.Resolve(apierrors.ByCode("LIMIT").WithParams(supplied)).Message != "字段:9223372036854775807" {
t.Fatal("parameter decode or snapshot failure")
}
})
}
}