-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathextensions_test.go
More file actions
106 lines (100 loc) · 2.31 KB
/
extensions_test.go
File metadata and controls
106 lines (100 loc) · 2.31 KB
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
104
105
106
package openapi_test
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/require"
"go.yaml.in/yaml/v4"
"github.com/sv-tools/openapi"
)
type testExtendable struct {
A string `json:"a,omitempty" yaml:"a,omitempty"`
}
func TestExtendable_Marshal_Unmarshal(t *testing.T) {
for _, tt := range []struct {
name string
data string
expected string
emptyExtensions bool
}{
{
name: "spec only",
data: `{"a": "foo"}`,
emptyExtensions: true,
},
{
name: "spec with extra non extension field",
data: `{"a": "foo", "b": "bar"}`,
expected: `{"a": "foo"}`,
emptyExtensions: true,
},
{
name: "spec with extension field",
data: `{"a": "foo", "x-b": "bar"}`,
emptyExtensions: false,
},
} {
t.Run(tt.name, func(t *testing.T) {
t.Run("json", func(t *testing.T) {
var v *openapi.Extendable[testExtendable]
require.NoError(t, json.Unmarshal([]byte(tt.data), &v))
if tt.emptyExtensions {
require.Empty(t, v.Extensions)
} else {
require.NotEmpty(t, v.Extensions)
}
data, err := json.Marshal(&v)
require.NoError(t, err)
if tt.expected == "" {
tt.expected = tt.data
}
require.JSONEq(t, tt.expected, string(data))
})
t.Run("yaml", func(t *testing.T) {
var v *openapi.Extendable[testExtendable]
require.NoError(t, yaml.Unmarshal([]byte(tt.data), &v))
if tt.emptyExtensions {
require.Empty(t, v.Extensions)
} else {
require.NotEmpty(t, v.Extensions)
}
data, err := yaml.Marshal(&v)
require.NoError(t, err)
if tt.expected == "" {
tt.expected = tt.data
}
require.YAMLEq(t, tt.expected, string(data))
})
})
}
}
func TestExtendable_WithExt(t *testing.T) {
for _, tt := range []struct {
name string
key string
value any
expected map[string]any
}{
{
name: "without prefix",
key: "foo",
value: 42,
expected: map[string]any{
"x-foo": 42,
},
},
{
name: "with prefix",
key: "x-foo",
value: 43,
expected: map[string]any{
"x-foo": 43,
},
},
} {
t.Run(tt.name, func(t *testing.T) {
ext := openapi.NewExtendable(&testExtendable{})
ext.AddExt(tt.key, tt.value)
require.Equal(t, tt.expected, ext.Extensions)
})
}
}