Files

53 lines
1.6 KiB
Go

package strictjson
import (
"errors"
"testing"
)
type input struct {
// Name contains the only accepted field in these fixed-schema tests.
Name string `json:"name"`
}
// TestDecodeObject checks each fixed-schema rule with a fresh destination.
func TestDecodeObject(t *testing.T) {
cases := []struct {
name string
body string
want string
wantErr error
}{
{"Positive: Unicode preserved", `{"name":"Алиса 👋"}`, "Алиса 👋", nil},
{"Negative: missing field", `{}`, "", ErrInvalid},
{"Negative: unknown field", `{"name":"alice","extra":true}`, "", ErrInvalid},
{"Negative: duplicate field", `{"name":"alice","name":"bob"}`, "", ErrInvalid},
{"Negative: case mismatch", `{"Name":"alice"}`, "", ErrInvalid},
{"Negative: null field", `{"name":null}`, "", ErrInvalid},
{"Negative: wrong value type", `{"name":12}`, "", ErrInvalid},
{"Negative: invalid UTF-8", "{\"name\":\"\xff\"}", "", ErrInvalid},
{"Negative: array root", `[]`, "", ErrInvalid},
{"Negative: unclosed object", `{"name":"alice"`, "", ErrInvalid},
{"Negative: invalid value", `{"name":}`, "", ErrInvalid},
{"Negative: invalid key", `{name:"alice"}`, "", ErrInvalid},
{"Negative: trailing value", `{"name":"alice"} {}`, "", ErrInvalid},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
// Arrange.
var destination input
// Act.
err := DecodeObject([]byte(tc.body), &destination, "name")
// Assert.
if !errors.Is(err, tc.wantErr) {
t.Fatalf("error=%v, want=%v", err, tc.wantErr)
}
if destination.Name != tc.want {
t.Fatalf("decoded name=%q, want=%q", destination.Name, tc.want)
}
})
}
}