-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathextensions_test.go
103 lines (85 loc) · 2.4 KB
/
extensions_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package openapi
import (
"testing"
"github.com/go-json-experiment/json"
"github.com/go-json-experiment/json/jsontext"
)
type testStruct struct {
// A string field
StringField string `json:"stringField,omitempty" yaml:"stringField,omitempty"`
// An integer field
IntegerField int `json:"integerField,omitempty" yaml:"integerField,omitempty"`
// An Extensions field
Extensions Extensions `json:",inline" yaml:",inline"`
}
func TestExtensions_valid(t *testing.T) {
t.Parallel()
t.Run("nil", func(t *testing.T) {
ext := Extensions(nil)
if err := validateExtensions(ext); err != nil {
t.Fatal(err)
}
})
t.Run("empty", func(t *testing.T) {
ext := Extensions(jsontext.Value{})
if err := validateExtensions(ext); err != nil {
t.Fatal(err)
}
})
t.Run("empty JSON", func(t *testing.T) {
ext := Extensions(jsontext.Value{'{', '}'})
if err := validateExtensions(ext); err != nil {
t.Fatal(err)
}
})
}
func TestExtensions_invalid(t *testing.T) {
t.Parallel()
t.Run("does not start with x-", func(t *testing.T) {
ext := Extensions([]byte(`{"bar":true,"x-baz":42}`))
if err := validateExtensions(ext); err == nil {
t.Fatal("expected error")
} else if want := `bar: ` + ErrUnknownField.Error(); err.Error() != want {
t.Fatalf("got: %v, want: %v", err, want)
}
})
t.Run("invalid JSON", func(t *testing.T) {
ext := Extensions([]byte(`{"x-bar":true,"x-baz":42`))
synErr := errAs[jsontext.SyntacticError](t, validateExtensions(ext))
if synErr.JSONPointer != "" || synErr.ByteOffset != 24 ||
synErr.Err.Error() != "unexpected EOF" {
t.Fatalf("got: %#v", synErr.Err)
}
})
}
func TestExtensions_inline(t *testing.T) {
t.Parallel()
ts := &testStruct{
StringField: "foo",
IntegerField: 42,
Extensions: Extensions([]byte(
`{"x-bar":true,"x-baz":42,"x-string":"mystring","x-array":["foo","bar"]}`)),
}
if err := validateExtensions(ts.Extensions); err != nil {
t.Fatal(err)
}
b, err := json.Marshal(ts)
if err != nil {
t.Fatal(err)
}
const want = `{"stringField":"foo","integerField":42,"x-bar":true,"x-baz":42,"x-string":"mystring","x-array":["foo","bar"]}`
if string(b) != want {
t.Fatalf("got: %v, want: %v", string(b), want)
}
ts2 := &testStruct{}
if err := json.Unmarshal(b, ts2); err != nil {
t.Fatal(err)
}
b2, err := json.Marshal(ts2)
if err != nil {
t.Fatal(err)
}
if want != string(b2) {
t.Fatalf("got: %v, want: %v", string(b2), want)
}
}