File: yaml_test.go

package info (click to toggle)
golang-github-go-openapi-swag 1%3A0.25.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,200 kB
  • sloc: sh: 30; makefile: 3
file content (315 lines) | stat: -rw-r--r-- 8,273 bytes parent folder | download
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
// Copyright 2015 go-swagger maintainers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package yamlutils

import (
	"embed"
	"encoding/json"
	"fmt"
	"os"
	"path"
	"strings"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	yaml "go.yaml.in/yaml/v3"
)

// embedded test files

//go:embed fixtures/*.yaml
var embeddedFixtures embed.FS

var fixtureSpecTags, fixture2224, fixtureWithQuotedYKey, fixtureWithYKey []byte

func TestMain(m *testing.M) {
	fixtureSpecTags = mustLoadFixture("fixture_spec_tags.yaml")
	fixture2224 = mustLoadFixture("fixture_2224.yaml")
	fixtureWithQuotedYKey = mustLoadFixture("fixture_with_quoted.yaml")
	fixtureWithYKey = mustLoadFixture("fixture_with_ykey.yaml")

	os.Exit(m.Run())
}

func TestYAMLToJSON(t *testing.T) {
	const sd = `---
1: the int key value
name: a string value
'y': some value
`

	t.Run("with initial YAML doc", func(t *testing.T) {
		var data yaml.Node
		_ = yaml.Unmarshal([]byte(sd), &data)

		t.Run("should convert YAML doc to JSON", func(t *testing.T) {
			d, err := YAMLToJSON(data)
			require.NoError(t, err)
			require.NotNil(t, d)
			assert.JSONEq(t, `{"1":"the int key value","name":"a string value","y":"some value"}`, string(d))
		})

		t.Run("should NOT convert appended YAML doc to JSON", func(t *testing.T) {
			ns := []*yaml.Node{
				{
					Kind:  yaml.ScalarNode,
					Value: "true",
					Tag:   "!!bool",
				},
				{
					Kind:  yaml.ScalarNode,
					Value: "the bool value",
					Tag:   "!!str",
				},
			}
			data.Content[0].Content = append(data.Content[0].Content, ns...)

			d, err := YAMLToJSON(data)
			require.Error(t, err)
			require.Nil(t, d)
			require.ErrorContains(t, err, "is not supported as map key")
		})
	})

	t.Run("with initial YAML doc", func(t *testing.T) {
		var data yaml.Node
		_ = yaml.Unmarshal([]byte(sd), &data)

		tag := []*yaml.Node{
			{
				Kind:  yaml.ScalarNode,
				Value: "tag",
				Tag:   "!!str",
			},
			{
				Kind: yaml.MappingNode,
				Content: []*yaml.Node{
					{
						Kind:  yaml.ScalarNode,
						Value: "name",
						Tag:   "!!str",
					},
					{
						Kind:  yaml.ScalarNode,
						Value: "tag name",
						Tag:   "!!str",
					},
				},
			},
		}
		data.Content[0].Content = append(data.Content[0].Content, tag...)

		t.Run("should convert appended YAML doc to JSON", func(t *testing.T) {
			d, err := YAMLToJSON(data)
			require.NoError(t, err)
			assert.JSONEq(t, `{"1":"the int key value","name":"a string value","y":"some value","tag":{"name":"tag name"}}`, string(d))
		})

		t.Run("should NOT convert appended YAML doc to JSON: key cannot be a bool", func(t *testing.T) {
			tag[1].Content = []*yaml.Node{
				{
					Kind:  yaml.ScalarNode,
					Value: "true",
					Tag:   "!!bool",
				},
				{
					Kind:  yaml.ScalarNode,
					Value: "the bool tag name",
					Tag:   "!!str",
				},
			}

			d, err := YAMLToJSON(data)
			require.Error(t, err)
			require.Nil(t, d)
			require.ErrorContains(t, err, "is not supported as map key")
		})
	})

	t.Run("with initial YAML doc", func(t *testing.T) {
		var data yaml.Node
		_ = yaml.Unmarshal([]byte(sd), &data)

		t.Run("should convert any array to JSON", func(t *testing.T) {
			var lst []any
			lst = append(lst, "hello")

			d, err := YAMLToJSON(lst)
			require.NoError(t, err)
			require.NotNil(t, d)
			assert.JSONEq(t, `["hello"]`, string(d))

			t.Run("should convert object appended to array to JSON", func(t *testing.T) {
				lst = append(lst, data)

				d, err = YAMLToJSON(lst)
				require.NoError(t, err)
				require.NotEmpty(t, d)
				assert.JSONEq(t, `["hello",{"1":"the int key value","name":"a string value","y":"some value"}]`, string(d))
			})
		})
	})

	t.Run("from YAML bytes", func(t *testing.T) {
		t.Run("root document is an object. Should not convert", func(t *testing.T) {
			_, err := BytesToYAMLDoc([]byte("- name: hello\n"))
			require.Error(t, err)
		})

		t.Run("document is invalid YAML. Should not convert", func(t *testing.T) {
			_, err := BytesToYAMLDoc([]byte("name:\tgreetings: hello\n"))
			require.Error(t, err)
		})

		t.Run("root document is an object. Should convert", func(t *testing.T) {
			dd, err := BytesToYAMLDoc([]byte("description: 'object created'\n"))
			require.NoError(t, err)

			t.Run("should convert YAML object to JSON", func(t *testing.T) {
				d, err := YAMLToJSON(dd)
				require.NoError(t, err)
				assert.JSONEq(t, `{"description":"object created"}`, string(d))
			})
		})
	})
}

func TestWithYKey(t *testing.T) {
	doc, err := BytesToYAMLDoc(fixtureWithYKey)
	require.NoError(t, err)

	_, err = YAMLToJSON(doc)
	require.NoError(t, err)

	doc, err = BytesToYAMLDoc(fixtureWithQuotedYKey)
	require.NoError(t, err)
	jsond, err := YAMLToJSON(doc)
	require.NoError(t, err)

	var yt struct {
		Definitions struct {
			Viewbox struct {
				Properties struct {
					Y struct {
						Type string `json:"type"`
					} `json:"y"`
				} `json:"properties"`
			} `json:"viewbox"`
		} `json:"definitions"`
	}
	require.NoError(t, json.Unmarshal(jsond, &yt))
	assert.Equal(t, "integer", yt.Definitions.Viewbox.Properties.Y.Type)
}

func TestMapKeyTypes(t *testing.T) {
	dm := map[any]any{
		"12345":             "string",
		12345:               "int",
		int8(1):             "int8",
		int16(12345):        "int16",
		int32(12345678):     "int32",
		int64(12345678910):  "int64",
		uint(12345):         "uint",
		uint8(1):            "uint8",
		uint16(12345):       "uint16",
		uint32(12345678):    "uint32",
		uint64(12345678910): "uint64",
	}
	_, err := YAMLToJSON(dm)
	require.NoError(t, err)
}

func TestYAMLTags(t *testing.T) {
	t.Run("should marshal as a YAML doc", func(t *testing.T) {
		doc, err := BytesToYAMLDoc(fixtureSpecTags)
		require.NoError(t, err)

		t.Run("doc should marshal as the original doc", func(t *testing.T) {
			text, err := yaml.Marshal(doc)
			require.NoError(t, err)
			assert.YAMLEq(t, string(fixtureSpecTags), string(text))
		})

		t.Run("doc should marshal to JSON", func(t *testing.T) {
			jazon, err := YAMLToJSON(doc)
			require.NoError(t, err)

			t.Run("json should unmarshal to YAMLMapSlice", func(t *testing.T) {
				var data YAMLMapSlice
				require.NoError(t, json.Unmarshal(jazon, &data))

				t.Run("YAMLMapSlice should marshal to YAML bytes", func(t *testing.T) {
					text, err := data.MarshalYAML()
					require.NoError(t, err)

					buf, ok := text.([]byte)
					require.True(t, ok)

					// standard YAML used by [assert.YAMLEq] interprets YAML timestamp as [time.Time],
					// but in our context, we use string
					neutralizeTimestamp := strings.ReplaceAll(string(fixtureSpecTags), "default:", "default: !!str ")
					assert.YAMLEq(t, neutralizeTimestamp, string(buf))
				})
			})
		})
	})
}

func TestYAMLEdgeCases(t *testing.T) {
	t.Run("should never happen because never called in the context of arrays", func(t *testing.T) {
		_, err := yamlDocument(&yaml.Node{
			Content: []*yaml.Node{
				{},
				{},
			},
		})
		require.Error(t, err)
	})

	t.Run("should never happen unless the document representation is corrupted", func(t *testing.T) {
		_, err := yamlSequence(&yaml.Node{
			Content: []*yaml.Node{
				{
					Kind: yaml.Kind(99), // illegal kind
				},
			},
		})
		require.Error(t, err)
	})

	t.Run("should never happen unless the document cannot be marshaled", func(t *testing.T) {
		invalidType := func() {}
		_, err := format(invalidType)
		require.Error(t, err)

		_, err = transformData([]any{
			map[any]any{
				complex128(0): struct{}{},
			},
		})
		require.Error(t, err)
	})
}

func mustLoadFixture(name string) []byte {
	const msg = "wrong embedded FS configuration: %w"
	data, err := embeddedFixtures.ReadFile(path.Join("fixtures", name)) // "/" even on windows
	if err != nil {
		panic(fmt.Errorf(msg, err))
	}

	return data
}