87 lines
2.7 KiB
Go
87 lines
2.7 KiB
Go
package apigen
|
|
|
|
import (
|
|
"path/filepath"
|
|
"strings"
|
|
"testing"
|
|
)
|
|
|
|
func TestErrorParamsConsumer(t *testing.T) { testCatalogConsumer(t, "errorParams.api", "errorParams") }
|
|
|
|
func TestErrorParamsDocumentAndValidation(t *testing.T) {
|
|
path := filepath.Join(frameworkRoot(t), "examples/contracts/errorParams.api")
|
|
source := readFile(t, path)
|
|
spec, err := Parse(path)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
compiled, err := Compile(spec)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
doc := document(t, compiled)
|
|
definitions := doc["x-omni-errors"].([]any)
|
|
found := false
|
|
for _, value := range definitions {
|
|
e := value.(map[string]any)
|
|
if e["name"] == "TextTooLong" {
|
|
found = true
|
|
params := e["params"].([]any)
|
|
if len(params) != 2 || params[0].(map[string]any)["name"] != "label" || params[1].(map[string]any)["type"] != "int" || e["message"] != "{label}不能超过{max}个字符" {
|
|
t.Fatal(e)
|
|
}
|
|
}
|
|
}
|
|
if !found {
|
|
t.Fatal("missing template definition")
|
|
}
|
|
for _, path := range []string{"/token", "/raw"} {
|
|
method := "post"
|
|
if path == "/raw" {
|
|
method = "get"
|
|
}
|
|
response := operation(t, doc, path, method)["responses"].(map[string]any)["200"].(map[string]any)
|
|
media := response["content"].(map[string]any)["application/json"].(map[string]any)
|
|
value := media["examples"].(map[string]any)["TextTooLong"].(map[string]any)["value"].(map[string]any)
|
|
if value["msg"] != "企业名称不能超过100个字符" || value["code"] != float64(400002) {
|
|
t.Fatal(value)
|
|
}
|
|
if _, ok := value["data"]; !ok {
|
|
t.Fatal("data null omitted", value)
|
|
}
|
|
if len(media["schema"].(map[string]any)["anyOf"].([]any)) != 2 {
|
|
t.Fatal("success schema lost")
|
|
}
|
|
}
|
|
for _, change := range [][2]string{
|
|
{`"{label}不能超过{max}个字符"`, `"{label}不能超过{missing}个字符"`},
|
|
{`"type": "int"`, `"type": "unknown"`},
|
|
{`"example": 100`, `"example": "100"`},
|
|
{`"name": "max"`, `"name": "label"`},
|
|
{`"name": "max"`, `"name": "type"`},
|
|
{`successCode: 0`, `successCode: 0\n messages: {"TEXT_TOO_LONG":"{label}不能超过{max}个字符"}`},
|
|
} {
|
|
changed := strings.Replace(source, change[0], strings.ReplaceAll(change[1], `\n`, "\n"), 1)
|
|
s, err := parseText(t, changed)
|
|
if err == nil {
|
|
_, err = Compile(s)
|
|
}
|
|
if err == nil {
|
|
t.Fatal("accepted", change)
|
|
}
|
|
}
|
|
// Removing examples still produces a concrete, deterministic example.
|
|
noExamples := strings.ReplaceAll(strings.ReplaceAll(source, `, "example": "企业名称"`, ""), `, "example": 100`, "")
|
|
s, err := parseText(t, noExamples)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
c, err := Compile(s)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if !strings.Contains(string(c.Document), "label不能超过1个字符") {
|
|
t.Fatal("missing generated example")
|
|
}
|
|
}
|