summaryrefslogtreecommitdiffstats
path: root/toml_test.go
blob: fe2db9f664e60a4f016d24e759aaf9d9b74beede (plain)
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
//go:build go1.16
// +build go1.16

package toml_test

import (
	"bytes"
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"
	"regexp"
	"strings"
	"testing"

	"github.com/BurntSushi/toml"
	"github.com/BurntSushi/toml/internal/tag"
	tomltest "github.com/BurntSushi/toml/internal/toml-test"
)

// Test if the error message matches what we want for invalid tests. Every slice
// entry is tested with strings.Contains.
//
// Filepaths are glob'd
var errorTests = map[string][]string{
	"encoding/bad-utf8*":            {"invalid UTF-8 byte"},
	"encoding/utf16*":               {"files cannot contain NULL bytes; probably using UTF-16"},
	"string/multiline-escape-space": {`invalid escape: '\ '`},
}

// Test metadata; all keys listed as "keyname: type".
var metaTests = map[string]string{
	"implicit-and-explicit-after": `
		a.b.c:         Hash
		a.b.c.answer:  Integer
		a:             Hash
		a.better:      Integer
	`,
	"implicit-and-explicit-before": `
		a:             Hash
		a.better:      Integer
		a.b.c:         Hash
		a.b.c.answer:  Integer
	`,
	"key/case-sensitive": `
		sectioN:       String
		section:       Hash
		section.name:  String
		section.NAME:  String
		section.Name:  String
		Section:       Hash
		Section.name:  String
		Section."μ":   String
		Section."Μ":   String
		Section.M:     String
	`,
	"key/dotted": `
		name.first:                   String
		name.last:                    String
		many.dots.here.dot.dot.dot:   Integer
		count.a:                      Integer
		count.b:                      Integer
		count.c:                      Integer
		count.d:                      Integer
		count.e:                      Integer
		count.f:                      Integer
		count.g:                      Integer
		count.h:                      Integer
		count.i:                      Integer
		count.j:                      Integer
		count.k:                      Integer
		count.l:                      Integer
		tbl:                          Hash
		tbl.a.b.c:                    Float
		a.few.dots:                   Hash
		a.few.dots.polka.dot:         String
		a.few.dots.polka.dance-with:  String
		arr:                          ArrayHash
		arr.a.b.c:                    Integer
		arr.a.b.d:                    Integer
		arr:                          ArrayHash
		arr.a.b.c:                    Integer
		arr.a.b.d:                    Integer
	 `,
	"key/empty": `
		"": String
	`,
	"key/quoted-dots": `
		plain:                          Integer
		"with.dot":                     Integer
		plain_table:                    Hash
		plain_table.plain:              Integer
		plain_table."with.dot":         Integer
		table.withdot:                  Hash
		table.withdot.plain:            Integer
		table.withdot."key.with.dots":  Integer
	`,
	"key/space": `
		"a b": Integer
		" c d ": Integer
		" tbl ": Hash
		" tbl "."\ttab\ttab\t": String
	`,
	"key/special-chars": "\n" +
		"\"=~!@$^&*()_+-`1234567890[]|/?><.,;:'=\": Integer\n",

	// TODO: "(albums): Hash" is missing; the problem is that this is an
	// "implied key", which is recorded in the parser in implicits, rather than
	// in keys. This is to allow "redefining" tables, for example:
	//
	//    [a.b.c]
	//    answer = 42
	//    [a]
	//    better = 43
	//
	// However, we need to actually pass on this information to the MetaData so
	// we can use it.
	//
	// Keys are supposed to be in order, for the above right now that's:
	//
	//     (a).(b).(c):           Hash
	//     (a).(b).(c).(answer):  Integer
	//     (a):                   Hash
	//     (a).(better):          Integer
	//
	// So if we want to add "(a).(b): Hash", where should this be in the order?
	"table/array-implicit": `
		albums.songs:       ArrayHash
		albums.songs.name:  String
	`,

	// TODO: people and people.* listed many times; not entirely sure if that's
	// what we want?
	//
	// It certainly causes problems, because keys is a slice, and types a map.
	// So if array entry 1 differs in type from array entry 2 then that won't be
	// recorded right. This related to the problem in the above comment.
	//
	// people:                ArrayHash
	//
	// people[0]:             Hash
	// people[0].first_name:  String
	// people[0].last_name:   String
	//
	// people[1]:             Hash
	// people[1].first_name:  String
	// people[1].last_name:   String
	//
	// people[2]:             Hash
	// people[2].first_name:  String
	// people[2].last_name:   String
	"table/array-many": `
		people:             ArrayHash
		people.first_name:  String
		people.last_name:   String
		people:             ArrayHash
		people.first_name:  String
		people.last_name:   String
		people:             ArrayHash
		people.first_name:  String
		people.last_name:   String
	`,
	"table/array-nest": `
		albums:             ArrayHash
		albums.name:        String
		albums.songs:       ArrayHash
		albums.songs.name:  String
		albums.songs:       ArrayHash
		albums.songs.name:  String
		albums:             ArrayHash
		albums.name:        String
		albums.songs:       ArrayHash
		albums.songs.name:  String
		albums.songs:       ArrayHash
		albums.songs.name:  String
	`,
	"table/array-one": `
		people:             ArrayHash
		people.first_name:  String
		people.last_name:   String
	`,
	"table/array-table-array": `
		a:        ArrayHash
		a.b:      ArrayHash
		a.b.c:    Hash
		a.b.c.d:  String
		a.b:      ArrayHash
		a.b.c:    Hash
		a.b.c.d:  String
	`,
	"table/empty": `
		a: Hash
	`,
	"table/keyword": `
		true:   Hash
		false:  Hash
		inf:    Hash
		nan:    Hash
	`,
	"table/names": `
		a.b.c:    Hash
		a."b.c":  Hash
		a."d.e":  Hash
		a." x ":  Hash
		d.e.f:    Hash
		g.h.i:    Hash
		j."ʞ".l:  Hash
		x.1.2:    Hash
	`,
	"table/no-eol": `
		table: Hash
	`,
	"table/sub-empty": `
		a:    Hash
		a.b:  Hash
	`,
	"table/whitespace": `
		"valid key": Hash
	`,
	"table/with-literal-string": `
		a:                   Hash
		a."\"b\"":           Hash
		a."\"b\"".c:         Hash
		a."\"b\"".c.answer:  Integer
	`,
	"table/with-pound": `
		"key#group":         Hash
		"key#group".answer:  Integer
	`,
	"table/with-single-quotes": `
		a:             Hash
		a.b:           Hash
		a.b.c:         Hash
		a.b.c.answer:  Integer
	`,
	"table/without-super": `
		x.y.z.w:  Hash
		x:        Hash
	`,
}

// TOML 1.0
func TestToml(t *testing.T) {
	runTomlTest(t, false)
}

// TOML 1.1
func TestTomlNext(t *testing.T) {
	toml.WithTomlNext(func() {
		runTomlTest(t, true)
	})
}

// Make sure TOML 1.1 fails by default for now.
func TestTomlNextFails(t *testing.T) {
	runTomlTest(t, true,
		"valid/string/escape-esc",
		"valid/datetime/no-seconds",
		"valid/string/hex-escape",
		"valid/inline-table/newline",
		"valid/key/unicode")
}

func runTomlTest(t *testing.T, includeNext bool, wantFail ...string) {
	for k := range errorTests { // Make sure patterns are valid.
		_, err := filepath.Match(k, "")
		if err != nil {
			t.Fatal(err)
		}
	}

	// TODO: bit of a hack to make sure not all test run; without this "-run=.."
	// will still run alll tests, but just report the errors for the -run value.
	// This is annoying in cases where you have some debug printf.
	//
	// Need to update toml-test a bit to make this easier, but this good enough
	// for now.
	var runTests []string
	for _, a := range os.Args {
		if strings.HasPrefix(a, "-test.run=TestToml/") {
			a = strings.TrimPrefix(a, "-test.run=TestToml/encode/")
			a = strings.TrimPrefix(a, "-test.run=TestToml/decode/")
			runTests = []string{a, a + "/*"}
			break
		}
	}

	// Make sure the keys in metaTests and errorTests actually exist; easy to
	// make a typo and nothing will get tested.
	var (
		shouldExistValid   = make(map[string]struct{})
		shouldExistInvalid = make(map[string]struct{})
	)
	if len(runTests) == 0 {
		for k := range metaTests {
			shouldExistValid["valid/"+k] = struct{}{}
		}
		for k := range errorTests {
			shouldExistInvalid["invalid/"+k] = struct{}{}
		}
	}

	run := func(t *testing.T, enc bool) {
		r := tomltest.Runner{
			Files:    tomltest.EmbeddedTests(),
			Encoder:  enc,
			Parser:   parser{},
			RunTests: runTests,
			SkipTests: []string{
				// "15" in time.Parse() accepts both "1" and "01". The TOML
				// specification says that times *must* start with a leading
				// zero, but this requires writing out own datetime parser.
				// I think it's actually okay to just accept both really.
				// https://github.com/BurntSushi/toml/issues/320
				"invalid/datetime/time-no-leads",

				// These tests are fine, just doesn't deal well with empty output.
				"valid/comment/noeol",
				"valid/comment/nonascii",

				// TODO: fix this; we allow appending to tables, but shouldn't.
				"invalid/table/append-with-dotted*",
				"invalid/inline-table/add",
				"invalid/table/duplicate-key-dotted-table",
				"invalid/table/duplicate-key-dotted-table2",
				"invalid/spec/inline-table-2-0",
				"invalid/spec/table-9-1",
				"invalid/inline-table/nested_key_conflict",
				"invalid/table/append-to-array-with-dotted-keys",
			},
		}
		if includeNext {
			r.Version = "next"
		}

		tests, err := r.Run()
		if err != nil {
			t.Fatal(err)
		}

		failed := make(map[string]struct{})
		for _, test := range tests.Tests {
			t.Run(test.Path, func(t *testing.T) {
				if test.Failed() {
					for _, f := range wantFail {
						if f == test.Path {
							failed[test.Path] = struct{}{}
							return
						}
					}

					t.Fatalf("\nError:\n%s\n\nInput:\n%s\nOutput:\n%s\nWant:\n%s\n",
						test.Failure, test.Input, test.Output, test.Want)
					return
				}

				// Test error message.
				if test.Type() == tomltest.TypeInvalid {
					testError(t, test, shouldExistInvalid)
				}
				// Test metadata
				if !enc && test.Type() == tomltest.TypeValid {
					delete(shouldExistValid, test.Path)
					testMeta(t, test, includeNext)
				}
			})
		}
		for _, f := range wantFail {
			if _, ok := failed[f]; !ok {
				t.Errorf("expected test %q to fail but it didn't", f)
			}
		}

		t.Logf("passed: %d; failed: %d; skipped: %d", tests.Passed, tests.Failed, tests.Skipped)
	}

	t.Run("decode", func(t *testing.T) { run(t, false) })
	t.Run("encode", func(t *testing.T) { run(t, true) })

	if len(shouldExistValid) > 0 {
		var s []string
		for k := range shouldExistValid {
			s = append(s, k)
		}
		t.Errorf("the following meta tests didn't match any files: %s", strings.Join(s, ", "))
	}
	if len(shouldExistInvalid) > 0 {
		var s []string
		for k := range shouldExistInvalid {
			s = append(s, k)
		}
		t.Errorf("the following meta tests didn't match any files: %s", strings.Join(s, ", "))
	}
}

var reCollapseSpace = regexp.MustCompile(` +`)

func testMeta(t *testing.T, test tomltest.Test, includeNext bool) {
	want, ok := metaTests[strings.TrimPrefix(test.Path, "valid/")]
	if !ok {
		return
	}

	// Output is slightly different due to different quoting; just skip for now.
	if includeNext && (test.Path == "valid/table/names" || test.Path == "valid/key/case-sensitive") {
		return
	}

	var s interface{}
	meta, err := toml.Decode(test.Input, &s)
	if err != nil {
		t.Fatal(err)
	}

	b := new(strings.Builder)
	for i, k := range meta.Keys() {
		if i > 0 {
			b.WriteByte('\n')
		}
		fmt.Fprintf(b, "%s: %s", k, meta.Type(k...))
	}
	have := b.String()

	want = reCollapseSpace.ReplaceAllString(strings.ReplaceAll(strings.TrimSpace(want), "\t", ""), " ")
	if have != want {
		t.Errorf("MetaData wrong\nhave:\n%s\nwant:\n%s", have, want)
	}
}

func testError(t *testing.T, test tomltest.Test, shouldExist map[string]struct{}) {
	path := strings.TrimPrefix(test.Path, "invalid/")

	errs, ok := errorTests[path]
	if ok {
		delete(shouldExist, "invalid/"+path)
	}
	if !ok {
		for k := range errorTests {
			ok, _ = filepath.Match(k, path)
			if ok {
				delete(shouldExist, "invalid/"+k)
				errs = errorTests[k]
				break
			}
		}
	}
	if !ok {
		return
	}

	for _, e := range errs {
		if !strings.Contains(test.Output, e) {
			t.Errorf("\nwrong error message\nhave: %s\nwant: %s", test.Output, e)
		}
	}
}

type parser struct{}

func (p parser) Encode(input string) (output string, outputIsError bool, retErr error) {
	defer func() {
		if r := recover(); r != nil {
			switch rr := r.(type) {
			case error:
				retErr = rr
			default:
				retErr = fmt.Errorf("%s", rr)
			}
		}
	}()

	var tmp interface{}
	err := json.Unmarshal([]byte(input), &tmp)
	if err != nil {
		return "", false, err
	}

	rm, err := tag.Remove(tmp)
	if err != nil {
		return err.Error(), true, retErr
	}

	buf := new(bytes.Buffer)
	err = toml.NewEncoder(buf).Encode(rm)
	if err != nil {
		return err.Error(), true, retErr
	}

	return buf.String(), false, retErr
}

func (p parser) Decode(input string) (output string, outputIsError bool, retErr error) {
	defer func() {
		if r := recover(); r != nil {
			switch rr := r.(type) {
			case error:
				retErr = rr
			default:
				retErr = fmt.Errorf("%s", rr)
			}
		}
	}()

	var d interface{}
	if _, err := toml.Decode(input, &d); err != nil {
		return err.Error(), true, retErr
	}

	j, err := json.MarshalIndent(tag.Add("", d), "", "  ")
	if err != nil {
		return "", false, err
	}
	return string(j), false, retErr
}