Files
server-deploy/internal/wire/json_test.go

71 lines
1.9 KiB
Go

package wire
import (
"strings"
"testing"
)
type component struct {
Name string `json:"name"`
}
type document struct {
Components []component `json:"components"`
}
func TestStrictNestedArrays(t *testing.T) {
var doc document
if err := Decode(strings.NewReader(`{"components":[{"name":"server"}]}`), &doc, 1024); err != nil || doc.Components[0].Name != "server" {
t.Fatal(err)
}
for _, input := range []string{
`{"components":[{"name":"server","command":"secret"}]}`,
`{"components":[{}]}`,
`{"components":[{"Name":"server"}]}`,
`{"components":[null]}`,
`{"components":null}`,
`{"components":[{"name":null}]}`,
`{"components":[{"name":"one","name":"two"}]}`,
"{\"components\":[{\"name\":\"\xff\"}]}",
} {
if Decode(strings.NewReader(input), &doc, 1024) == nil {
t.Errorf("accepted malformed nested JSON: %q", input)
}
}
}
func TestDecodeBounds(t *testing.T) {
var doc document
for _, input := range []string{`{"components":[]} {}`, strings.Repeat(" ", 1025) + `{"components":[]}`} {
if Decode(strings.NewReader(input), &doc, 1024) == nil {
t.Fatal("accepted trailing or oversized input")
}
}
}
func TestInvalidDecoderArguments(t *testing.T) {
var doc document
for _, limit := range []int64{0, -1, 1<<63 - 1} {
if Decode(strings.NewReader(`{}`), &doc, limit) == nil {
t.Fatal("accepted invalid limit")
}
}
var nilDoc *document
for _, target := range []any{nil, doc, nilDoc} {
if Decode(strings.NewReader(`{}`), target, 1024) == nil {
t.Fatal("accepted invalid target")
}
}
}
func TestStrictTypedMaps(t *testing.T) {
var target map[string]component
for _, input := range []string{`{"api":{"name":"ok","extra":true}}`, `{"api":{"Name":"ok"}}`, `{"api":{}}`, `{"api":null}`} {
if Decode(strings.NewReader(input), &target, 1024) == nil {
t.Errorf("accepted malformed map entry: %s", input)
}
}
if err := Decode(strings.NewReader(`{"api":{"name":"ok"}}`), &target, 1024); err != nil {
t.Fatal(err)
}
}