Debian Codegraph @

td/td_json_test.go

raw
1 // Copyright (c) 2019-2023, Maxime Soulé
2 // All rights reserved.
3 //
4 // This source code is licensed under the BSD-style license found in the
5 // LICENSE file in the root directory of this source tree.
6
7 package td_test
8
9 import (
10 "encoding/json"
11 "errors"
12 "os"
13 "reflect"
14 "testing"
15 "time"
16
17 "github.com/maxatome/go-testdeep/internal/test"
18 "github.com/maxatome/go-testdeep/td"
19 )
20
21 type errReader struct{}
22
23 // Read implements io.Reader.
24 func (r errReader) Read(p []byte) (int, error) {
25 return 0, errors.New("an error occurred")
26 }
27
28 const (
29 insideOpJSON = " inside operator JSON at td_json_test.go:"
30 underOpJSON = "under operator JSON at td_json_test.go:"
31 )
32
33 func TestJSON(t *testing.T) {
34 type MyStruct struct {
35 Name string `json:"name"`
36 Age uint `json:"age"`
37 Gender string `json:"gender"`
38 }
39
40 //
41 // nil
42 checkOK(t, nil, td.JSON(`null`))
43 checkOK(t, (*int)(nil), td.JSON(`null`))
44
45 //
46 // Basic types
47 checkOK(t, 123, td.JSON(` 123 `))
48 checkOK(t, true, td.JSON(` true `))
49 checkOK(t, false, td.JSON(` false `))
50 checkOK(t, "foobar", td.JSON(` "foobar" `))
51
52 //
53 // struct
54 //
55 got := MyStruct{Name: "Bob", Age: 42, Gender: "male"}
56
57 // No placeholder
58 checkOK(t, got,
59 td.JSON(`{"name":"Bob","age":42,"gender":"male"}`))
60
61 checkOK(t, got, td.JSON(`$1`, got)) // json.Marshal() got for $1
62
63 // Numeric placeholders
64 checkOK(t, got,
65 td.JSON(`{"name":"$1","age":$2,"gender":$3}`,
66 "Bob", 42, "male")) // raw values
67
68 checkOK(t, got,
69 td.JSON(`{"name":"$1","age":$2,"gender":"$3"}`,
70 td.Re(`^Bob`),
71 td.Between(40, 45),
72 td.NotEmpty()))
73
74 // Same using Flatten
75 checkOK(t, got,
76 td.JSON(`{"name":"$1","age":$2,"gender":"$3"}`,
77 td.Re(`^Bob`),
78 td.Flatten([]td.TestDeep{td.Between(40, 45), td.NotEmpty()}),
79 ))
80
81 // Operators are not JSON marshalable
82 checkOK(t, got,
83 td.JSON(`$1`, map[string]any{
84 "name": td.Re(`^Bob`),
85 "age": 42,
86 "gender": td.NotEmpty(),
87 }))
88
89 // Placeholder + unmarshal before comparison
90 checkOK(t, json.RawMessage(`[1,2,3]`), td.JSON(`$1`, []int{1, 2, 3}))
91 checkOK(t, json.RawMessage(`{"foo":[1,2,3]}`),
92 td.JSON(`{"foo":$1}`, []int{1, 2, 3}))
93 checkOK(t, json.RawMessage(`[1,2,3]`),
94 td.JSON(`$1`, []any{1, td.Between(1, 3), 3}))
95
96 // Tag placeholders
97 checkOK(t, got,
98 td.JSON(`{"name":"$name","age":$age,"gender":$gender}`,
99 // raw values
100 td.Tag("name", "Bob"), td.Tag("age", 42), td.Tag("gender", "male")))
101
102 checkOK(t, got,
103 td.JSON(`{"name":"$name","age":$age,"gender":"$gender"}`,
104 td.Tag("name", td.Re(`^Bo`)),
105 td.Tag("age", td.Between(40, 45)),
106 td.Tag("gender", td.NotEmpty())))
107
108 // Tag placeholders + numeric placeholders
109 checkOK(t, []MyStruct{got, got},
110 td.JSON(`[
111 {"name":"$1","age":$age,"gender":"$3"},
112 {"name":"$1","age":$2,"gender":"$3"}
113 ]`,
114 td.Re(`^Bo`), // $1
115 td.Tag("age", td.Between(40, 45)), // $2
116 "male")) // $3
117
118 // Tag placeholders + operators are not JSON marshalable
119 checkOK(t, got,
120 td.JSON(`$all`, td.Tag("all", map[string]any{
121 "name": td.Re(`^Bob`),
122 "age": 42,
123 "gender": td.NotEmpty(),
124 })))
125
126 checkError(t, got,
127 td.JSON(`{"name":$1, "age":$1, "gender":$1}`,
128 td.Tag("!!", td.Ignore())),
129 expectedError{
130 Message: mustBe("bad usage of Tag operator"),
131 Summary: mustBe("invalid tag, should match (Letter|_)(Letter|_|Number)*"),
132 Under: mustContain("under operator Tag"),
133 })
134
135 // Tag placeholders + nil
136 checkOK(t, nil, td.JSON(`$all`, td.Tag("all", nil)))
137
138 // Mixed placeholders + operator
139 for _, op := range []string{
140 "NotEmpty",
141 "NotEmpty()",
142 "$^NotEmpty",
143 "$^NotEmpty()",
144 `"$^NotEmpty"`,
145 `"$^NotEmpty()"`,
146 `r<$^NotEmpty>`,
147 `r<$^NotEmpty()>`,
148 } {
149 checkOK(t, got,
150 td.JSON(`{"name":"$name","age":$1,"gender":`+op+`}`,
151 td.Tag("age", td.Between(40, 45)),
152 td.Tag("name", td.Re(`^Bob`))),
153 "using operator %s", op)
154 }
155
156 checkOK(t, got,
157 td.JSON(`{"name":Re("^Bo\\w"),"age":Between(40,45),"gender":NotEmpty()}`))
158 checkOK(t, got,
159 td.JSON(`
160 {
161 "name": All(Re("^Bo\\w"), HasPrefix("Bo"), HasSuffix("ob")),
162 "age": Between(40,45),
163 "gender": NotEmpty()
164 }`))
165 checkOK(t, got,
166 td.JSON(`
167 {
168 "name": All(Re("^Bo\\w"), HasPrefix("Bo"), HasSuffix("ob")),
169 "age": Between(40,45),
170 "gender": NotEmpty
171 }`))
172
173 // Same but operators in strings using "$^"
174 checkOK(t, got,
175 td.JSON(`{"name":Re("^Bo\\w"),"age":"$^Between(40,45)","gender":"$^NotEmpty()"}`))
176 checkOK(t, got, // using classic "" string, so each \ has to be escaped
177 td.JSON(`
178 {
179 "name": "$^All(Re(\"^Bo\\\\w\"), HasPrefix(\"Bo\"), HasSuffix(\"ob\"))",
180 "age": "$^Between(40,45)",
181 "gender": "$^NotEmpty()",
182 }`))
183 checkOK(t, got, // using raw strings, no escape needed
184 td.JSON(`
185 {
186 "name": "$^All(Re(r(^Bo\\w)), HasPrefix(r{Bo}), HasSuffix(r'ob'))",
187 "age": "$^Between(40,45)",
188 "gender": "$^NotEmpty()",
189 }`))
190
191 // …with comments…
192 checkOK(t, got,
193 td.JSON(`
194 // This should be the JSON representation of MyStruct struct
195 {
196 // A person:
197 "name": "$name", // The name of this person
198 "age": $1, /* The age of this person:
199 - placeholder unquoted, but could be without
200 any change
201 - to demonstrate a multi-lines comment */
202 "gender": $^NotEmpty // Operator NotEmpty
203 }`,
204 td.Tag("age", td.Between(40, 45)),
205 td.Tag("name", td.Re(`^Bob`))))
206
207 before := time.Now()
208 timeGot := map[string]time.Time{"created_at": time.Now()}
209 checkOK(t, timeGot,
210 td.JSON(`{"created_at": Between($1, $2)}`, before, time.Now()))
211
212 checkOK(t, timeGot,
213 td.JSON(`{"created_at": $1}`, td.Between(before, time.Now())))
214
215 // Len
216 checkOK(t, []int{1, 2, 3}, td.JSON(`Len(3)`))
217
218 //
219 // []byte
220 checkOK(t, got,
221 td.JSON([]byte(`{"name":"$name","age":$1,"gender":"male"}`),
222 td.Tag("age", td.Between(40, 45)),
223 td.Tag("name", td.Re(`^Bob`))))
224
225 //
226 // json.RawMessage
227 checkOK(t, got,
228 td.JSON(json.RawMessage(`{"name":"$name","age":$1,"gender":"male"}`),
229 td.Tag("age", td.Between(40, 45)),
230 td.Tag("name", td.Re(`^Bob`))))
231
232 //
233 // nil++
234 checkOK(t, nil, td.JSON(`$1`, nil))
235 checkOK(t, (*int)(nil), td.JSON(`$1`, td.Nil()))
236
237 checkOK(t, nil, td.JSON(`$x`, td.Tag("x", nil)))
238 checkOK(t, (*int)(nil), td.JSON(`$x`, td.Tag("x", nil)))
239
240 checkOK(t, json.RawMessage(`{"foo": null}`), td.JSON(`{"foo": null}`))
241
242 checkOK(t,
243 json.RawMessage(`{"foo": null}`),
244 td.JSON(`{"foo": $1}`, nil))
245
246 checkOK(t,
247 json.RawMessage(`{"foo": null}`),
248 td.JSON(`{"foo": $1}`, td.Nil()))
249
250 checkOK(t,
251 json.RawMessage(`{"foo": null}`),
252 td.JSON(`{"foo": $x}`, td.Tag("x", nil)))
253
254 checkOK(t,
255 json.RawMessage(`{"foo": null}`),
256 td.JSON(`{"foo": $x}`, td.Tag("x", td.Nil())))
257
258 //
259 // Loading a file
260 tmpDir := t.TempDir()
261
262 filename := tmpDir + "/test.json"
263 err := os.WriteFile(
264 filename, []byte(`{"name":$name,"age":$1,"gender":$^NotEmpty}`), 0644)
265 if err != nil {
266 t.Fatal(err)
267 }
268 checkOK(t, got,
269 td.JSON(filename,
270 td.Tag("age", td.Between(40, 45)),
271 td.Tag("name", td.Re(`^Bob`))))
272
273 //
274 // Reading (a file)
275 tmpfile, err := os.Open(filename)
276 if err != nil {
277 t.Fatal(err)
278 }
279 checkOK(t, got,
280 td.JSON(tmpfile,
281 td.Tag("age", td.Between(40, 45)),
282 td.Tag("name", td.Re(`^Bob`))))
283 tmpfile.Close() //nolint: errcheck
284
285 //
286 // Escaping $ in strings
287 checkOK(t, "$test", td.JSON(`"$$test"`))
288
289 //
290 // Errors
291 checkError(t, func() {}, td.JSON(`null`),
292 expectedError{
293 Message: mustBe("json.Marshal failed"),
294 Summary: mustContain("json: unsupported type"),
295 Under: mustContain(underOpJSON),
296 })
297
298 checkError(t, map[string]string{"zip": "pipo"},
299 td.All(td.JSON(`SuperMapOf({"zip":$1})`, "bingo")),
300 expectedError{
301 Path: mustBe(`DATA`),
302 Message: mustBe("compared (part 1 of 1)"),
303 Got: mustBe(`(map[string]string) (len=1) {
304 (string) (len=3) "zip": (string) (len=4) "pipo"
305 }`),
306 Expected: mustBe(`JSON(SuperMapOf(map[string]interface {}{
307 "zip": "bingo",
308 }))`,
309 ),
310 Under: mustContain("under operator All at "),
311 Origin: &expectedError{
312 Path: mustBe(`DATA<All#1/1>["zip"]`),
313 Message: mustBe(`values differ`),
314 Got: mustBe(`"pipo"`),
315 Expected: mustBe(`"bingo"`),
316 Under: mustContain("under operator SuperMapOf at line 1:0 (pos 0)" + insideOpJSON),
317 },
318 })
319
320 checkError(t, map[string]string{"zip": "pipo"},
321 td.JSON(`SuperMapOf({"zip":$1})`, "bingo"),
322 expectedError{
323 Path: mustBe(`DATA["zip"]`),
324 Message: mustBe("values differ"),
325 Got: mustBe(`"pipo"`),
326 Expected: mustBe(`"bingo"`),
327 Under: mustContain("under operator SuperMapOf at line 1:0 (pos 0)" + insideOpJSON),
328 })
329
330 checkError(t, json.RawMessage(`"pipo:bingo"`),
331 td.JSON(`Re(r;^pipo:(\w+);, ["bad"])`),
332 expectedError{
333 Path: mustBe(`(DATA =~ ^pipo:(\w+))[0]`),
334 Got: mustBe(`"bingo"`),
335 Expected: mustBe(`"bad"`),
336 Under: mustContain("under operator Re at line 1:0 (pos 0)" + insideOpJSON),
337 })
338
339 checkError(t, json.RawMessage(`"pipo:bingo"`),
340 td.JSON(`Re(r;^pipo:(\w+);, [$1])`, "bad"),
341 expectedError{
342 Path: mustBe(`(DATA =~ ^pipo:(\w+))[0]`),
343 Got: mustBe(`"bingo"`),
344 Expected: mustBe(`"bad"`),
345 Under: mustContain("under operator Re at line 1:0 (pos 0)" + insideOpJSON),
346 })
347
348 checkError(t, json.RawMessage(`"pipo:bingo"`),
349 td.JSON(`Re(r;^pipo:(\w+);, [$param])`, td.Tag("param", "bad")),
350 expectedError{
351 Path: mustBe(`(DATA =~ ^pipo:(\w+))[0]`),
352 Got: mustBe(`"bingo"`),
353 Expected: mustBe(`"bad"`),
354 Under: mustContain("under operator Re at line 1:0 (pos 0)" + insideOpJSON),
355 })
356
357 checkError(t, json.RawMessage(`"pipo:bingo"`),
358 td.JSON(`Re(r;^pipo:(\w+);, Bag($1))`, "bad"),
359 expectedError{
360 Path: mustBe(`(DATA =~ ^pipo:(\w+))`),
361 Summary: mustBe(`Missing item: ("bad")` + "\n" + ` Extra item: ("bingo")`),
362 Under: mustContain("under operator Bag at line 1:19 (pos 19)" + insideOpJSON),
363 })
364
365 checkError(t, json.RawMessage(`"pipo:bingo"`),
366 td.JSON(`Re(r;^pipo:(\w+);, Bag($param))`, td.Tag("param", "bad")),
367 expectedError{
368 Path: mustBe(`(DATA =~ ^pipo:(\w+))`),
369 Summary: mustBe(`Missing item: ("bad")` + "\n" + ` Extra item: ("bingo")`),
370 Under: mustContain("under operator Bag at line 1:19 (pos 19)" + insideOpJSON),
371 })
372
373 //
374 // Fatal errors
375 checkError(t, "never tested",
376 td.JSON("uNkNoWnFiLe.json"),
377 expectedError{
378 Message: mustBe("bad usage of JSON operator"),
379 Path: mustBe("DATA"),
380 Summary: mustContain("JSON file uNkNoWnFiLe.json cannot be read: "),
381 Under: mustContain(underOpJSON),
382 })
383
384 checkError(t, "never tested",
385 td.JSON(42),
386 expectedError{
387 Message: mustBe("bad usage of JSON operator"),
388 Path: mustBe("DATA"),
389 Summary: mustBe("usage: JSON(STRING_JSON|STRING_FILENAME|[]byte|json.RawMessage|io.Reader, ...), but received int as 1st parameter"),
390 Under: mustContain(underOpJSON),
391 })
392
393 checkError(t, "never tested",
394 td.JSON(errReader{}),
395 expectedError{
396 Message: mustBe("bad usage of JSON operator"),
397 Path: mustBe("DATA"),
398 Summary: mustBe("JSON read error: an error occurred"),
399 Under: mustContain(underOpJSON),
400 })
401
402 checkError(t, "never tested",
403 td.JSON(`pipo`),
404 expectedError{
405 Message: mustBe("bad usage of JSON operator"),
406 Path: mustBe("DATA"),
407 Summary: mustContain("JSON unmarshal error: "),
408 Under: mustContain(underOpJSON),
409 })
410
411 checkError(t, "never tested",
412 td.JSON(`[$foo]`,
413 td.Tag("foo", td.Ignore()),
414 td.Tag("foo", td.Ignore())),
415 expectedError{
416 Message: mustBe("bad usage of JSON operator"),
417 Path: mustBe("DATA"),
418 Summary: mustBe(`2 params have the same tag "foo"`),
419 Under: mustContain(underOpJSON),
420 })
421
422 checkError(t, []int{42},
423 td.JSON(`[$1]`, func() {}),
424 expectedError{
425 Message: mustBe("an error occurred while unmarshaling JSON into func()"),
426 Path: mustBe("DATA[0]"),
427 Summary: mustBe("json: cannot unmarshal number into Go value of type func()"),
428 Under: mustContain(underOpJSON),
429 })
430
431 checkError(t, []int{42},
432 td.JSON(`[$foo]`, td.Tag("foo", func() {})),
433 expectedError{
434 Message: mustBe("an error occurred while unmarshaling JSON into func()"),
435 Path: mustBe("DATA[0]"),
436 Summary: mustBe("json: cannot unmarshal number into Go value of type func()"),
437 Under: mustContain(underOpJSON),
438 })
439
440 // numeric placeholders
441 checkError(t, "never tested",
442 td.JSON(`[1, "$123bad"]`),
443 expectedError{
444 Message: mustBe("bad usage of JSON operator"),
445 Path: mustBe("DATA"),
446 Summary: mustBe(`JSON unmarshal error: invalid numeric placeholder at line 1:5 (pos 5)`),
447 Under: mustContain(underOpJSON),
448 })
449
450 checkError(t, "never tested",
451 td.JSON(`[1, $000]`),
452 expectedError{
453 Message: mustBe("bad usage of JSON operator"),
454 Path: mustBe("DATA"),
455 Summary: mustBe(`JSON unmarshal error: invalid numeric placeholder "$000", it should start at "$1" at line 1:4 (pos 4)`),
456 Under: mustContain(underOpJSON),
457 })
458
459 checkError(t, "never tested",
460 td.JSON(`[1, $1]`),
461 expectedError{
462 Message: mustBe("bad usage of JSON operator"),
463 Path: mustBe("DATA"),
464 Summary: mustBe(`JSON unmarshal error: numeric placeholder "$1", but no params given at line 1:4 (pos 4)`),
465 Under: mustContain(underOpJSON),
466 })
467
468 checkError(t, "never tested",
469 td.JSON(`[1, 2, $3]`, td.Ignore()),
470 expectedError{
471 Message: mustBe("bad usage of JSON operator"),
472 Path: mustBe("DATA"),
473 Summary: mustBe(`JSON unmarshal error: numeric placeholder "$3", but only one param given at line 1:7 (pos 7)`),
474 Under: mustContain(underOpJSON),
475 })
476
477 // $^Operator
478 checkError(t, "never tested",
479 td.JSON(`[1, $^bad%]`),
480 expectedError{
481 Message: mustBe("bad usage of JSON operator"),
482 Path: mustBe("DATA"),
483 Summary: mustBe(`JSON unmarshal error: $^ must be followed by an operator name at line 1:4 (pos 4)`),
484 Under: mustContain(underOpJSON),
485 })
486
487 checkError(t, "never tested",
488 td.JSON(`[1, "$^bad%"]`),
489 expectedError{
490 Message: mustBe("bad usage of JSON operator"),
491 Path: mustBe("DATA"),
492 Summary: mustBe(`JSON unmarshal error: $^ must be followed by an operator name at line 1:5 (pos 5)`),
493 Under: mustContain(underOpJSON),
494 })
495
496 // named placeholders
497 checkError(t, "never tested",
498 td.JSON(`[
499 1,
500 "$bad%"
501 ]`),
502 expectedError{
503 Message: mustBe("bad usage of JSON operator"),
504 Path: mustBe("DATA"),
505 Summary: mustBe(`JSON unmarshal error: bad placeholder "$bad%" at line 3:3 (pos 10)`),
506 Under: mustContain(underOpJSON),
507 })
508
509 checkError(t, "never tested",
510 td.JSON(`[1, $unknown]`),
511 expectedError{
512 Message: mustBe("bad usage of JSON operator"),
513 Path: mustBe("DATA"),
514 Summary: mustBe(`JSON unmarshal error: unknown placeholder "$unknown" at line 1:4 (pos 4)`),
515 Under: mustContain(underOpJSON),
516 })
517
518 //
519 // Stringification
520 test.EqualStr(t, td.JSON(`1`).String(),
521 `JSON(1)`)
522
523 test.EqualStr(t, td.JSON(`[ 1, 2, 3 ]`).String(),
524 `
525 JSON([
526 1,
527 2,
528 3
529 ])`[1:])
530
531 test.EqualStr(t, td.JSON(` null `).String(), `JSON(null)`)
532
533 test.EqualStr(t,
534 td.JSON(`[ $1, $name, $2, Nil(), $nil, 26, Between(5, 6), Len(34), Len(Between(5, 6)), 28 ]`,
535 td.Between(12, 20),
536 "test",
537 td.Tag("name", td.Code(func(s string) bool { return len(s) > 0 })),
538 td.Tag("nil", nil),
539 14,
540 ).String(),
541 `
542 JSON([
543 "$1" /* 12 ≤ got ≤ 20 */,
544 "$name" /* Code(func(string) bool) */,
545 "test",
546 nil,
547 null,
548 26,
549 5.0 ≤ got ≤ 6.0,
550 len=34,
551 len: 5.0 ≤ got ≤ 6.0,
552 28
553 ])`[1:])
554
555 test.EqualStr(t,
556 td.JSON(`[ $1, $name, $2, $^Nil, $nil ]`,
557 td.Between(12, 20),
558 "test",
559 td.Tag("name", td.Code(func(s string) bool { return len(s) > 0 })),
560 td.Tag("nil", nil),
561 ).String(),
562 `
563 JSON([
564 "$1" /* 12 ≤ got ≤ 20 */,
565 "$name" /* Code(func(string) bool) */,
566 "test",
567 nil,
568 null
569 ])`[1:])
570
571 test.EqualStr(t,
572 td.JSON(`{"label": $value, "zip": $^NotZero}`,
573 td.Tag("value", td.Bag(
574 td.JSON(`{"name": $1,"age":$2,"surname":$3}`,
575 td.HasPrefix("Bob"),
576 td.Between(12, 24),
577 "captain",
578 ),
579 td.JSON(`{"name": $1}`, td.HasPrefix("Alice")),
580 )),
581 ).String(),
582 `
583 JSON({
584 "label": "$value" /* Bag(JSON({
585 "age": "$2" /* 12 ≤ got ≤ 24 */,
586 "name": "$1" /* HasPrefix("Bob") */,
587 "surname": "captain"
588 }),
589 JSON({
590 "name": "$1" /* HasPrefix("Alice") */
591 })) */,
592 "zip": NotZero()
593 })`[1:])
594
595 test.EqualStr(t,
596 td.JSON(`
597 {
598 "label": {"name": HasPrefix("Bob"), "age": Between(12,24)},
599 "zip": NotZero()
600 }`).String(),
601 `
602 JSON({
603 "label": {
604 "age": 12.0 ≤ got ≤ 24.0,
605 "name": HasPrefix("Bob")
606 },
607 "zip": NotZero()
608 })`[1:])
609
610 // Erroneous op
611 test.EqualStr(t, td.JSON(`[`).String(), "JSON(<ERROR>)")
612 }
613
614 func TestJSONInside(t *testing.T) {
615 // Between
616 t.Run("Between", func(t *testing.T) {
617 got := map[string]int{"val1": 1, "val2": 2}
618
619 checkOK(t, got,
620 td.JSON(`{"val1": Between(0, 2), "val2": Between(2, 3, "[[")}`))
621 checkOK(t, got,
622 td.JSON(`{"val1": Between(0, 2), "val2": Between(2, 3, "BoundsInOut")}`))
623 for _, bounds := range []string{"[[", "BoundsInOut"} {
624 checkError(t, got,
625 td.JSON(`{"val1": Between(0, 2), "val2": Between(1, 2, $1)}`, bounds),
626 expectedError{
627 Message: mustBe("values differ"),
628 Path: mustBe(`DATA["val2"]`),
629 Got: mustBe("2.0"),
630 Expected: mustBe("1.0 ≤ got < 2.0"),
631 Under: mustContain("under operator Between at line 1:32 (pos 32)" + insideOpJSON),
632 })
633 }
634
635 checkError(t, json.RawMessage(`123`),
636 td.JSON(`Between(0, 2)`),
637 expectedError{
638 Message: mustBe("values differ"),
639 Path: mustBe(`DATA`),
640 Got: mustBe("123.0"),
641 Expected: mustBe("0.0 ≤ got ≤ 2.0"),
642 Under: mustContain("under operator Between at line 1:0 (pos 0)" + insideOpJSON),
643 })
644
645 checkOK(t, got,
646 td.JSON(`{"val1": Between(1, 1), "val2": Between(2, 2, "[]")}`))
647 checkOK(t, got,
648 td.JSON(`{"val1": Between(1, 1), "val2": Between(2, 2, "BoundsInIn")}`))
649
650 checkOK(t, got,
651 td.JSON(`{"val1": Between(0, 1, "]]"), "val2": Between(1, 3, "][")}`))
652 checkOK(t, got,
653 td.JSON(`{"val1": Between(0, 1, "BoundsOutIn"), "val2": Between(1, 3, "BoundsOutOut")}`))
654 for _, bounds := range []string{"]]", "BoundsOutIn"} {
655 checkError(t, got,
656 td.JSON(`{"val1": 1, "val2": Between(2, 3, $1)}`, bounds),
657 expectedError{
658 Message: mustBe("values differ"),
659 Path: mustBe(`DATA["val2"]`),
660 Got: mustBe("2.0"),
661 Expected: mustBe("2.0 < got ≤ 3.0"),
662 Under: mustContain("under operator Between at line 1:20 (pos 20)" + insideOpJSON),
663 })
664 }
665 for _, bounds := range []string{"][", "BoundsOutOut"} {
666 checkError(t, got,
667 td.JSON(`{"val1": 1, "val2": Between(2, 3, $1)}`, bounds),
668 expectedError{
669 Message: mustBe("values differ"),
670 Path: mustBe(`DATA["val2"]`),
671 Got: mustBe("2.0"),
672 Expected: mustBe("2.0 < got < 3.0"),
673 Under: mustContain("under operator Between at line 1:20 (pos 20)" + insideOpJSON),
674 },
675 "using bounds %q", bounds)
676 checkError(t, got,
677 td.JSON(`{"val1": 1, "val2": Between(1, 2, $1)}`, bounds),
678 expectedError{
679 Message: mustBe("values differ"),
680 Path: mustBe(`DATA["val2"]`),
681 Got: mustBe("2.0"),
682 Expected: mustBe("1.0 < got < 2.0"),
683 Under: mustContain("under operator Between at line 1:20 (pos 20)" + insideOpJSON),
684 },
685 "using bounds %q", bounds)
686 }
687
688 // Bad 3rd parameter
689 checkError(t, "never tested",
690 td.JSON(`{
691 "val2": Between(1, 2, "<>")
692 }`),
693 expectedError{
694 Message: mustBe("bad usage of JSON operator"),
695 Path: mustBe("DATA"),
696 Summary: mustBe(`JSON unmarshal error: Between() bad 3rd parameter, use "[]", "[[", "]]" or "][" at line 2:10 (pos 12)`),
697 Under: mustContain(underOpJSON),
698 })
699 checkError(t, "never tested",
700 td.JSON(`{
701 "val2": Between(1, 2, 125)
702 }`),
703 expectedError{
704 Message: mustBe("bad usage of JSON operator"),
705 Path: mustBe("DATA"),
706 Summary: mustBe(`JSON unmarshal error: Between() bad 3rd parameter, use "[]", "[[", "]]" or "][" at line 2:10 (pos 12)`),
707 Under: mustContain(underOpJSON),
708 })
709
710 checkError(t, "never tested",
711 td.JSON(`{"val2": Between(1)}`),
712 expectedError{
713 Message: mustBe("bad usage of JSON operator"),
714 Path: mustBe("DATA"),
715 Summary: mustBe(`JSON unmarshal error: Between() requires 2 or 3 parameters at line 1:9 (pos 9)`),
716 Under: mustContain(underOpJSON),
717 })
718
719 checkError(t, "never tested",
720 td.JSON(`{"val2": Between(1,2,3,4)}`),
721 expectedError{
722 Message: mustBe("bad usage of JSON operator"),
723 Path: mustBe("DATA"),
724 Summary: mustBe(`JSON unmarshal error: Between() requires 2 or 3 parameters at line 1:9 (pos 9)`),
725 Under: mustContain(underOpJSON),
726 })
727 })
728
729 // N
730 t.Run("N", func(t *testing.T) {
731 got := map[string]float32{"val": 2.1}
732
733 checkOK(t, got, td.JSON(`{"val": N(2.1)}`))
734 checkOK(t, got, td.JSON(`{"val": N(2, 0.1)}`))
735
736 checkError(t, "never tested",
737 td.JSON(`{"val2": N()}`),
738 expectedError{
739 Message: mustBe("bad usage of JSON operator"),
740 Path: mustBe("DATA"),
741 Summary: mustBe(`JSON unmarshal error: N() requires 1 or 2 parameters at line 1:9 (pos 9)`),
742 Under: mustContain(underOpJSON),
743 })
744
745 checkError(t, "never tested",
746 td.JSON(`{"val2": N(1,2,3)}`),
747 expectedError{
748 Message: mustBe("bad usage of JSON operator"),
749 Path: mustBe("DATA"),
750 Summary: mustBe(`JSON unmarshal error: N() requires 1 or 2 parameters at line 1:9 (pos 9)`),
751 Under: mustContain(underOpJSON),
752 })
753 })
754
755 // Re
756 t.Run("Re", func(t *testing.T) {
757 got := map[string]string{"val": "Foo bar"}
758
759 checkOK(t, got, td.JSON(`{"val": Re("^Foo")}`))
760 checkOK(t, got, td.JSON(`{"val": Re("^(\\w+)", ["Foo"])}`))
761 checkOK(t, got, td.JSON(`{"val": Re("^(\\w+)", Bag("Foo"))}`))
762
763 checkError(t, "never tested",
764 td.JSON(`{"val2": Re()}`),
765 expectedError{
766 Message: mustBe("bad usage of JSON operator"),
767 Path: mustBe("DATA"),
768 Summary: mustBe(`JSON unmarshal error: Re() requires 1 or 2 parameters at line 1:9 (pos 9)`),
769 Under: mustContain(underOpJSON),
770 })
771
772 checkError(t, "never tested",
773 td.JSON(`{"val2": Re(1,2,3)}`),
774 expectedError{
775 Message: mustBe("bad usage of JSON operator"),
776 Path: mustBe("DATA"),
777 Summary: mustBe(`JSON unmarshal error: Re() requires 1 or 2 parameters at line 1:9 (pos 9)`),
778 Under: mustContain(underOpJSON),
779 })
780 })
781
782 // SubMapOf
783 t.Run("SubMapOf", func(t *testing.T) {
784 got := []map[string]int{{"val1": 1, "val2": 2}}
785
786 checkOK(t, got, td.JSON(`[ SubMapOf({"val1":1, "val2":2, "xxx": "yyy"}) ]`))
787
788 checkError(t, "never tested",
789 td.JSON(`[ SubMapOf() ]`),
790 expectedError{
791 Message: mustBe("bad usage of JSON operator"),
792 Path: mustBe("DATA"),
793 Summary: mustBe(`JSON unmarshal error: SubMapOf() requires only one parameter at line 1:2 (pos 2)`),
794 Under: mustContain(underOpJSON),
795 })
796
797 checkError(t, "never tested",
798 td.JSON(`[ SubMapOf(1, 2) ]`),
799 expectedError{
800 Message: mustBe("bad usage of JSON operator"),
801 Path: mustBe("DATA"),
802 Summary: mustBe(`JSON unmarshal error: SubMapOf() requires only one parameter at line 1:2 (pos 2)`),
803 Under: mustContain(underOpJSON),
804 })
805 })
806
807 // SuperMapOf
808 t.Run("SuperMapOf", func(t *testing.T) {
809 got := []map[string]int{{"val1": 1, "val2": 2}}
810
811 checkOK(t, got, td.JSON(`[ SuperMapOf({"val1":1}) ]`))
812
813 checkError(t, "never tested",
814 td.JSON(`[ SuperMapOf() ]`),
815 expectedError{
816 Message: mustBe("bad usage of JSON operator"),
817 Path: mustBe("DATA"),
818 Summary: mustBe(`JSON unmarshal error: SuperMapOf() requires only one parameter at line 1:2 (pos 2)`),
819 Under: mustContain(underOpJSON),
820 })
821
822 checkError(t, "never tested",
823 td.JSON(`[ SuperMapOf(1, 2) ]`),
824 expectedError{
825 Message: mustBe("bad usage of JSON operator"),
826 Path: mustBe("DATA"),
827 Summary: mustBe(`JSON unmarshal error: SuperMapOf() requires only one parameter at line 1:2 (pos 2)`),
828 Under: mustContain(underOpJSON),
829 })
830 })
831
832 // errors
833 t.Run("Errors", func(t *testing.T) {
834 checkError(t, "never tested",
835 td.JSON(`[ UnknownOp() ]`),
836 expectedError{
837 Message: mustBe("bad usage of JSON operator"),
838 Path: mustBe("DATA"),
839 Summary: mustBe(`JSON unmarshal error: unknown operator UnknownOp() at line 1:2 (pos 2)`),
840 Under: mustContain(underOpJSON),
841 })
842
843 checkError(t, "never tested",
844 td.JSON(`[ Catch() ]`),
845 expectedError{
846 Message: mustBe("bad usage of JSON operator"),
847 Path: mustBe("DATA"),
848 Summary: mustBe(`JSON unmarshal error: Catch() is not usable in JSON() at line 1:2 (pos 2)`),
849 Under: mustContain(underOpJSON),
850 })
851
852 checkError(t, "never tested",
853 td.JSON(`[ JSON() ]`),
854 expectedError{
855 Message: mustBe("bad usage of JSON operator"),
856 Path: mustBe("DATA"),
857 Summary: mustBe(`JSON unmarshal error: JSON() is not usable in JSON(), use literal JSON instead at line 1:2 (pos 2)`),
858 Under: mustContain(underOpJSON),
859 })
860
861 checkError(t, "never tested",
862 td.JSON(`[ All() ]`),
863 expectedError{
864 Message: mustBe("bad usage of JSON operator"),
865 Path: mustBe("DATA"),
866 Summary: mustBe(`JSON unmarshal error: All() requires at least one parameter at line 1:2 (pos 2)`),
867 Under: mustContain(underOpJSON),
868 })
869
870 checkError(t, "never tested",
871 td.JSON(`[ Empty(12) ]`),
872 expectedError{
873 Message: mustBe("bad usage of JSON operator"),
874 Path: mustBe("DATA"),
875 Summary: mustBe(`JSON unmarshal error: Empty() requires no parameters at line 1:2 (pos 2)`),
876 Under: mustContain(underOpJSON),
877 })
878
879 checkError(t, "never tested",
880 td.JSON(`[ HasPrefix() ]`),
881 expectedError{
882 Message: mustBe("bad usage of JSON operator"),
883 Path: mustBe("DATA"),
884 Summary: mustBe(`JSON unmarshal error: HasPrefix() requires only one parameter at line 1:2 (pos 2)`),
885 Under: mustContain(underOpJSON),
886 })
887
888 checkError(t, "never tested",
889 td.JSON(`[ JSONPointer(1, 2, 3) ]`),
890 expectedError{
891 Message: mustBe("bad usage of JSON operator"),
892 Path: mustBe("DATA"),
893 Summary: mustBe(`JSON unmarshal error: JSONPointer() requires 2 parameters at line 1:2 (pos 2)`),
894 Under: mustContain(underOpJSON),
895 })
896
897 checkError(t, "never tested",
898 td.JSON(`[ JSONPointer(1, 2) ]`),
899 expectedError{
900 Message: mustBe("bad usage of JSON operator"),
901 Path: mustBe("DATA"),
902 Summary: mustBe(`JSON unmarshal error: JSONPointer() bad #1 parameter type: string required but float64 received at line 1:2 (pos 2)`),
903 Under: mustContain(underOpJSON),
904 })
905
906 // This one is not caught by JSON, but by Re itself, as the number
907 // of parameters is correct
908 checkError(t, json.RawMessage(`"never tested"`),
909 td.JSON(`Re(1)`),
910 expectedError{
911 Message: mustBe("bad usage of Re operator"),
912 Path: mustBe("DATA"),
913 Summary: mustBe(`usage: Re(STRING|*regexp.Regexp[, NON_NIL_CAPTURE]), but received float64 as 1st parameter`),
914 Under: mustContain("under operator Re at line 1:0 (pos 0)" + insideOpJSON),
915 })
916 })
917 }
918
919 func TestJSONTypeBehind(t *testing.T) {
920 equalTypes(t, td.JSON(`false`), true)
921 equalTypes(t, td.JSON(`"foo"`), "")
922 equalTypes(t, td.JSON(`42`), float64(0))
923 equalTypes(t, td.JSON(`[1,2,3]`), ([]any)(nil))
924 equalTypes(t, td.JSON(`{"a":12}`), (map[string]any)(nil))
925
926 // operator at the root → delegate it TypeBehind() call
927 equalTypes(t, td.JSON(`$1`, td.SuperMapOf(map[string]any{"x": 1}, nil)), (map[string]any)(nil))
928 equalTypes(t, td.JSON(`SuperMapOf({"x":1})`), (map[string]any)(nil))
929
930 equalTypes(t, td.JSON(`$1`, 123), 42)
931
932 nullType := td.JSON(`null`).TypeBehind()
933 if nullType != reflect.TypeOf((*any)(nil)).Elem() {
934 t.Errorf("Failed test: got %s intead of interface {}", nullType)
935 }
936
937 // Erroneous op
938 equalTypes(t, td.JSON(`[`), nil)
939 }
940
941 func TestSubJSONOf(t *testing.T) {
942 type MyStruct struct {
943 Name string `json:"name"`
944 Age uint `json:"age"`
945 Gender string `json:"gender"`
946 }
947
948 //
949 // struct
950 //
951 got := MyStruct{Name: "Bob", Age: 42, Gender: "male"}
952
953 // No placeholder
954 checkOK(t, got,
955 td.SubJSONOf(`
956 {
957 "name": "Bob",
958 "age": 42,
959 "gender": "male",
960 "details": { // ← we don't want to test this field
961 "city": "Test City",
962 "zip": 666
963 }
964 }`))
965
966 // Numeric placeholders
967 checkOK(t, got,
968 td.SubJSONOf(`{"name":"$1","age":$2,"gender":$3,"details":{}}`,
969 "Bob", 42, "male")) // raw values
970
971 checkOK(t, got,
972 td.SubJSONOf(`{"name":"$1","age":$2,"gender":$3,"details":{}}`,
973 td.Re(`^Bob`),
974 td.Between(40, 45),
975 td.NotEmpty()))
976
977 // Same using Flatten
978 checkOK(t, got,
979 td.SubJSONOf(`{"name":"$1","age":$2,"gender":$3,"details":{}}`,
980 td.Re(`^Bob`),
981 td.Flatten([]td.TestDeep{td.Between(40, 45), td.NotEmpty()}),
982 ))
983
984 // Tag placeholders
985 checkOK(t, got,
986 td.SubJSONOf(
987 `{"name":"$name","age":$age,"gender":"$gender","details":{}}`,
988 td.Tag("name", td.Re(`^Bob`)),
989 td.Tag("age", td.Between(40, 45)),
990 td.Tag("gender", td.NotEmpty())))
991
992 // Mixed placeholders + operator
993 for _, op := range []string{
994 "NotEmpty",
995 "NotEmpty()",
996 "$^NotEmpty",
997 "$^NotEmpty()",
998 `"$^NotEmpty"`,
999 `"$^NotEmpty()"`,
1000 `r<$^NotEmpty>`,
1001 `r<$^NotEmpty()>`,
1002 } {
1003 checkOK(t, got,
1004 td.SubJSONOf(
1005 `{"name":"$name","age":$1,"gender":`+op+`,"details":{}}`,
1006 td.Tag("age", td.Between(40, 45)),
1007 td.Tag("name", td.Re(`^Bob`))),
1008 "using operator %s", op)
1009 }
1010
1011 //
1012 // Errors
1013 checkError(t, func() {}, td.SubJSONOf(`{}`),
1014 expectedError{
1015 Message: mustBe("json.Marshal failed"),
1016 Summary: mustContain("json: unsupported type"),
1017 })
1018
1019 for i, n := range []any{
1020 nil,
1021 (map[string]any)(nil),
1022 (map[string]bool)(nil),
1023 ([]int)(nil),
1024 } {
1025 checkError(t, n, td.SubJSONOf(`{}`),
1026 expectedError{
1027 Message: mustBe("values differ"),
1028 Got: mustBe("null"),
1029 Expected: mustBe("non-null"),
1030 },
1031 "nil test #%d", i)
1032 }
1033
1034 //
1035 // Fatal errors
1036 checkError(t, "never tested",
1037 td.SubJSONOf(`[1, "$123bad"]`),
1038 expectedError{
1039 Message: mustBe("bad usage of SubJSONOf operator"),
1040 Path: mustBe("DATA"),
1041 Summary: mustBe(`JSON unmarshal error: invalid numeric placeholder at line 1:5 (pos 5)`),
1042 })
1043
1044 checkError(t, "never tested",
1045 td.SubJSONOf(`[1, $000]`),
1046 expectedError{
1047 Message: mustBe("bad usage of SubJSONOf operator"),
1048 Path: mustBe("DATA"),
1049 Summary: mustBe(`JSON unmarshal error: invalid numeric placeholder "$000", it should start at "$1" at line 1:4 (pos 4)`),
1050 })
1051
1052 checkError(t, "never tested",
1053 td.SubJSONOf(`[1, $1]`),
1054 expectedError{
1055 Message: mustBe("bad usage of SubJSONOf operator"),
1056 Path: mustBe("DATA"),
1057 Summary: mustBe(`JSON unmarshal error: numeric placeholder "$1", but no params given at line 1:4 (pos 4)`),
1058 })
1059
1060 checkError(t, "never tested",
1061 td.SubJSONOf(`[1, 2, $3]`, td.Ignore()),
1062 expectedError{
1063 Message: mustBe("bad usage of SubJSONOf operator"),
1064 Path: mustBe("DATA"),
1065 Summary: mustBe(`JSON unmarshal error: numeric placeholder "$3", but only one param given at line 1:7 (pos 7)`),
1066 })
1067
1068 // $^Operator
1069 checkError(t, "never tested",
1070 td.SubJSONOf(`[1, $^bad%]`),
1071 expectedError{
1072 Message: mustBe("bad usage of SubJSONOf operator"),
1073 Path: mustBe("DATA"),
1074 Summary: mustBe(`JSON unmarshal error: $^ must be followed by an operator name at line 1:4 (pos 4)`),
1075 })
1076
1077 checkError(t, "never tested",
1078 td.SubJSONOf(`[1, "$^bad%"]`),
1079 expectedError{
1080 Message: mustBe("bad usage of SubJSONOf operator"),
1081 Path: mustBe("DATA"),
1082 Summary: mustBe(`JSON unmarshal error: $^ must be followed by an operator name at line 1:5 (pos 5)`),
1083 })
1084
1085 // named placeholders
1086 checkError(t, "never tested",
1087 td.SubJSONOf(`[1, "$bad%"]`),
1088 expectedError{
1089 Message: mustBe("bad usage of SubJSONOf operator"),
1090 Path: mustBe("DATA"),
1091 Summary: mustBe(`JSON unmarshal error: bad placeholder "$bad%" at line 1:5 (pos 5)`),
1092 })
1093
1094 checkError(t, "never tested",
1095 td.SubJSONOf(`[1, $unknown]`),
1096 expectedError{
1097 Message: mustBe("bad usage of SubJSONOf operator"),
1098 Path: mustBe("DATA"),
1099 Summary: mustBe(`JSON unmarshal error: unknown placeholder "$unknown" at line 1:4 (pos 4)`),
1100 })
1101
1102 checkError(t, "never tested",
1103 td.SubJSONOf("null"),
1104 expectedError{
1105 Message: mustBe("bad usage of SubJSONOf operator"),
1106 Path: mustBe("DATA"),
1107 Summary: mustBe("SubJSONOf() only accepts JSON objects {…}"),
1108 })
1109
1110 //
1111 // Stringification
1112 test.EqualStr(t, td.SubJSONOf(`{}`).String(), `SubJSONOf({})`)
1113
1114 test.EqualStr(t, td.SubJSONOf(`{"foo":1, "bar":2}`).String(),
1115 `
1116 SubJSONOf({
1117 "bar": 2,
1118 "foo": 1
1119 })`[1:])
1120
1121 test.EqualStr(t,
1122 td.SubJSONOf(`{"label": $value, "zip": $^NotZero}`,
1123 td.Tag("value", td.Bag(
1124 td.SubJSONOf(`{"name": $1,"age":$2}`,
1125 td.HasPrefix("Bob"),
1126 td.Between(12, 24),
1127 ),
1128 td.SubJSONOf(`{"name": $1}`, td.HasPrefix("Alice")),
1129 )),
1130 ).String(),
1131 `
1132 SubJSONOf({
1133 "label": "$value" /* Bag(SubJSONOf({
1134 "age": "$2" /* 12 ≤ got ≤ 24 */,
1135 "name": "$1" /* HasPrefix("Bob") */
1136 }),
1137 SubJSONOf({
1138 "name": "$1" /* HasPrefix("Alice") */
1139 })) */,
1140 "zip": NotZero()
1141 })`[1:])
1142
1143 // Erroneous op
1144 test.EqualStr(t, td.SubJSONOf(`123`).String(), "SubJSONOf(<ERROR>)")
1145 }
1146
1147 func TestSubJSONOfTypeBehind(t *testing.T) {
1148 equalTypes(t, td.SubJSONOf(`{"a":12}`), (map[string]any)(nil))
1149
1150 // Erroneous op
1151 equalTypes(t, td.SubJSONOf(`123`), nil)
1152 }
1153
1154 func TestSuperJSONOf(t *testing.T) {
1155 type MyStruct struct {
1156 Name string `json:"name"`
1157 Age uint `json:"age"`
1158 Gender string `json:"gender"`
1159 Details string `json:"details"`
1160 }
1161
1162 //
1163 // struct
1164 //
1165 got := MyStruct{Name: "Bob", Age: 42, Gender: "male", Details: "Nice"}
1166
1167 // No placeholder
1168 checkOK(t, got, td.SuperJSONOf(`{"name": "Bob"}`))
1169
1170 // Numeric placeholders
1171 checkOK(t, got,
1172 td.SuperJSONOf(`{"name":"$1","age":$2}`,
1173 "Bob", 42)) // raw values
1174
1175 checkOK(t, got,
1176 td.SuperJSONOf(`{"name":"$1","age":$2}`,
1177 td.Re(`^Bob`),
1178 td.Between(40, 45)))
1179
1180 // Same using Flatten
1181 checkOK(t, got,
1182 td.SuperJSONOf(`{"name":"$1","age":$2}`,
1183 td.Flatten([]td.TestDeep{td.Re(`^Bob`), td.Between(40, 45)}),
1184 ))
1185
1186 // Tag placeholders
1187 checkOK(t, got,
1188 td.SuperJSONOf(`{"name":"$name","gender":"$gender"}`,
1189 td.Tag("name", td.Re(`^Bob`)),
1190 td.Tag("gender", td.NotEmpty())))
1191
1192 // Mixed placeholders + operator
1193 for _, op := range []string{
1194 "NotEmpty",
1195 "NotEmpty()",
1196 "$^NotEmpty",
1197 "$^NotEmpty()",
1198 `"$^NotEmpty"`,
1199 `"$^NotEmpty()"`,
1200 `r<$^NotEmpty>`,
1201 `r<$^NotEmpty()>`,
1202 } {
1203 checkOK(t, got,
1204 td.SuperJSONOf(
1205 `{"name":"$name","age":$1,"gender":`+op+`}`,
1206 td.Tag("age", td.Between(40, 45)),
1207 td.Tag("name", td.Re(`^Bob`))),
1208 "using operator %s", op)
1209 }
1210
1211 // …with comments…
1212 checkOK(t, got,
1213 td.SuperJSONOf(`
1214 // This should be the JSON representation of MyStruct struct
1215 {
1216 // A person:
1217 "name": "$name", // The name of this person
1218 "age": $1, /* The age of this person:
1219 - placeholder unquoted, but could be without
1220 any change
1221 - to demonstrate a multi-lines comment */
1222 "gender": $^NotEmpty // Shortcut to operator NotEmpty
1223 }`,
1224 td.Tag("age", td.Between(40, 45)),
1225 td.Tag("name", td.Re(`^Bob`))))
1226
1227 //
1228 // Errors
1229 checkError(t, func() {}, td.SuperJSONOf(`{}`),
1230 expectedError{
1231 Message: mustBe("json.Marshal failed"),
1232 Summary: mustContain("json: unsupported type"),
1233 })
1234
1235 for i, n := range []any{
1236 nil,
1237 (map[string]any)(nil),
1238 (map[string]bool)(nil),
1239 ([]int)(nil),
1240 } {
1241 checkError(t, n, td.SuperJSONOf(`{}`),
1242 expectedError{
1243 Message: mustBe("values differ"),
1244 Got: mustBe("null"),
1245 Expected: mustBe("non-null"),
1246 },
1247 "nil test #%d", i)
1248 }
1249
1250 //
1251 // Fatal errors
1252 checkError(t, "never tested",
1253 td.SuperJSONOf(`[1, "$123bad"]`),
1254 expectedError{
1255 Message: mustBe("bad usage of SuperJSONOf operator"),
1256 Path: mustBe("DATA"),
1257 Summary: mustBe(`JSON unmarshal error: invalid numeric placeholder at line 1:5 (pos 5)`),
1258 })
1259
1260 checkError(t, "never tested",
1261 td.SuperJSONOf(`[1, $000]`),
1262 expectedError{
1263 Message: mustBe("bad usage of SuperJSONOf operator"),
1264 Path: mustBe("DATA"),
1265 Summary: mustBe(`JSON unmarshal error: invalid numeric placeholder "$000", it should start at "$1" at line 1:4 (pos 4)`),
1266 })
1267
1268 checkError(t, "never tested",
1269 td.SuperJSONOf(`[1, $1]`),
1270 expectedError{
1271 Message: mustBe("bad usage of SuperJSONOf operator"),
1272 Path: mustBe("DATA"),
1273 Summary: mustBe(`JSON unmarshal error: numeric placeholder "$1", but no params given at line 1:4 (pos 4)`),
1274 })
1275
1276 checkError(t, "never tested",
1277 td.SuperJSONOf(`[1, 2, $3]`, td.Ignore()),
1278 expectedError{
1279 Message: mustBe("bad usage of SuperJSONOf operator"),
1280 Path: mustBe("DATA"),
1281 Summary: mustBe(`JSON unmarshal error: numeric placeholder "$3", but only one param given at line 1:7 (pos 7)`),
1282 })
1283
1284 // $^Operator
1285 checkError(t, "never tested",
1286 td.SuperJSONOf(`[1, $^bad%]`),
1287 expectedError{
1288 Message: mustBe("bad usage of SuperJSONOf operator"),
1289 Path: mustBe("DATA"),
1290 Summary: mustBe(`JSON unmarshal error: $^ must be followed by an operator name at line 1:4 (pos 4)`),
1291 })
1292
1293 checkError(t, "never tested",
1294 td.SuperJSONOf(`[1, "$^bad%"]`),
1295 expectedError{
1296 Message: mustBe("bad usage of SuperJSONOf operator"),
1297 Path: mustBe("DATA"),
1298 Summary: mustBe(`JSON unmarshal error: $^ must be followed by an operator name at line 1:5 (pos 5)`),
1299 })
1300
1301 // named placeholders
1302 checkError(t, "never tested",
1303 td.SuperJSONOf(`[1, "$bad%"]`),
1304 expectedError{
1305 Message: mustBe("bad usage of SuperJSONOf operator"),
1306 Path: mustBe("DATA"),
1307 Summary: mustBe(`JSON unmarshal error: bad placeholder "$bad%" at line 1:5 (pos 5)`),
1308 })
1309
1310 checkError(t, "never tested",
1311 td.SuperJSONOf(`[1, $unknown]`),
1312 expectedError{
1313 Message: mustBe("bad usage of SuperJSONOf operator"),
1314 Path: mustBe("DATA"),
1315 Summary: mustBe(`JSON unmarshal error: unknown placeholder "$unknown" at line 1:4 (pos 4)`),
1316 })
1317
1318 checkError(t, "never tested",
1319 td.SuperJSONOf("null"),
1320 expectedError{
1321 Message: mustBe("bad usage of SuperJSONOf operator"),
1322 Path: mustBe("DATA"),
1323 Summary: mustBe("SuperJSONOf() only accepts JSON objects {…}"),
1324 })
1325
1326 //
1327 // Stringification
1328 test.EqualStr(t, td.SuperJSONOf(`{}`).String(), `SuperJSONOf({})`)
1329
1330 test.EqualStr(t, td.SuperJSONOf(`{"foo":1, "bar":2}`).String(),
1331 `
1332 SuperJSONOf({
1333 "bar": 2,
1334 "foo": 1
1335 })`[1:])
1336
1337 test.EqualStr(t,
1338 td.SuperJSONOf(`{"label": $value, "zip": $^NotZero}`,
1339 td.Tag("value", td.Bag(
1340 td.SuperJSONOf(`{"name": $1,"age":$2}`,
1341 td.HasPrefix("Bob"),
1342 td.Between(12, 24),
1343 ),
1344 td.SuperJSONOf(`{"name": $1}`, td.HasPrefix("Alice")),
1345 )),
1346 ).String(),
1347 `
1348 SuperJSONOf({
1349 "label": "$value" /* Bag(SuperJSONOf({
1350 "age": "$2" /* 12 ≤ got ≤ 24 */,
1351 "name": "$1" /* HasPrefix("Bob") */
1352 }),
1353 SuperJSONOf({
1354 "name": "$1" /* HasPrefix("Alice") */
1355 })) */,
1356 "zip": NotZero()
1357 })`[1:])
1358
1359 // Erroneous op
1360 test.EqualStr(t, td.SuperJSONOf(`123`).String(), "SuperJSONOf(<ERROR>)")
1361 }
1362
1363 func TestSuperJSONOfTypeBehind(t *testing.T) {
1364 equalTypes(t, td.SuperJSONOf(`{"a":12}`), (map[string]any)(nil))
1365
1366 // Erroneous op
1367 equalTypes(t, td.SuperJSONOf(`123`), nil)
1368 }