Debian Codegraph @

td/td_json.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
8
9 import (
10 "bytes"
11 ejson "encoding/json"
12 "errors"
13 "fmt"
14 "io"
15 "os"
16 "reflect"
17 "strings"
18
19 "github.com/maxatome/go-testdeep/internal/ctxerr"
20 "github.com/maxatome/go-testdeep/internal/dark"
21 "github.com/maxatome/go-testdeep/internal/flat"
22 "github.com/maxatome/go-testdeep/internal/json"
23 "github.com/maxatome/go-testdeep/internal/location"
24 "github.com/maxatome/go-testdeep/internal/types"
25 "github.com/maxatome/go-testdeep/internal/util"
26 )
27
28 // forbiddenOpsInJSON contains operators forbidden inside JSON,
29 // SubJSONOf or SuperJSONOf, optionally with an alternative to help
30 // the user.
31 var forbiddenOpsInJSON = map[string]string{
32 "Array": "literal []",
33 "Cap": "",
34 "Catch": "",
35 "Code": "",
36 "Delay": "",
37 "ErrorIs": "",
38 "Isa": "",
39 "JSON": "literal JSON",
40 "Lax": "",
41 "List": "literal []",
42 "Map": "literal {}",
43 "PPtr": "",
44 "Ptr": "",
45 "Recv": "",
46 "SStruct": "",
47 "Shallow": "",
48 "Slice": "literal []",
49 "Smuggle": "",
50 "String": `literal ""`,
51 "SubJSONOf": "SubMapOf operator",
52 "SuperJSONOf": "SuperMapOf operator",
53 "SuperSliceOf": "All and JSONPointer operators",
54 "Struct": "",
55 "Tag": "",
56 "TruncTime": "",
57 }
58
59 // tdJSONUnmarshaler handles the JSON unmarshaling of JSON, SubJSONOf
60 // and SuperJSONOf first parameter.
61 type tdJSONUnmarshaler struct {
62 location.Location // position of the operator
63 options jsonv2Options
64 }
65
66 // newJSONUnmarshaler returns a new instance of tdJSONUnmarshaler.
67 func newJSONUnmarshaler(pos location.Location) *tdJSONUnmarshaler {
68 return &tdJSONUnmarshaler{
69 Location: pos,
70 }
71 }
72
73 // replaceLocation replaces the location of tdOp by the
74 // JSON/SubJSONOf/SuperJSONOf one then add the position of the
75 // operator inside the JSON string.
76 func (u tdJSONUnmarshaler) replaceLocation(tdOp TestDeep, posInJSON json.Position) {
77 // The goal, instead of:
78 // [under operator Len at value.go:476]
79 // having:
80 // [under operator Len at line 12:7 (pos 123) inside operator JSON at file.go:23]
81 // so add ^------------------------------------------^
82
83 newPos := u.Location
84 newPos.Inside = fmt.Sprintf("%s inside operator %s ", posInJSON, u.Func)
85 newPos.Func = tdOp.GetLocation().Func
86 tdOp.replaceLocation(newPos)
87 }
88
89 // unmarshal unmarshals expectedJSON using placeholder parameters params.
90 func (u *tdJSONUnmarshaler) unmarshal(expectedJSON any, params []any) (any, *ctxerr.Error) {
91 var (
92 err error
93 b []byte
94 )
95
96 switch data := expectedJSON.(type) {
97 case string:
98 // Try to load this file (if it seems it can be a filename and not
99 // a JSON content)
100 if strings.HasSuffix(data, ".json") {
101 // It could be a file name, try to read from it
102 b, err = os.ReadFile(data)
103 if err != nil {
104 return nil, ctxerr.OpBad(u.Func, "JSON file %s cannot be read: %s", data, err)
105 }
106 break
107 }
108 b = []byte(data)
109
110 case []byte:
111 b = data
112
113 case ejson.RawMessage:
114 b = data
115
116 case io.Reader:
117 b, err = io.ReadAll(data)
118 if err != nil {
119 return nil, ctxerr.OpBad(u.Func, "JSON read error: %s", err)
120 }
121
122 default:
123 return nil, ctxerr.OpBadUsage(
124 u.Func, "(STRING_JSON|STRING_FILENAME|[]byte|json.RawMessage|io.Reader, ...)",
125 expectedJSON, 1, false)
126 }
127
128 // Join all json/v2 options
129 for _, p := range params {
130 if opts, ok := p.(jsonv2Options); ok {
131 u.options = joinOptions(u.options, opts)
132 }
133 }
134
135 params = flat.Interfaces(params...)
136 var byTag map[string]any
137
138 for i, p := range params {
139 if op, ok := p.(*tdTag); ok && op.err == nil {
140 if byTag[op.tag] != nil {
141 return nil, ctxerr.OpBad(u.Func, `2 params have the same tag "%s"`, op.tag)
142 }
143 if byTag == nil {
144 byTag = map[string]any{}
145 }
146 // Don't keep the tag layer
147 p = nil
148 if op.expectedValue.IsValid() {
149 p = op.expectedValue.Interface()
150 }
151 byTag[op.tag] = newJSONNamedPlaceholder(op.tag, p, u.options)
152 }
153 params[i] = newJSONNumPlaceholder(uint64(i+1), p, u.options)
154 }
155
156 final, err := json.Parse(b, json.ParseOpts{
157 Placeholders: params,
158 PlaceholdersByName: byTag,
159 OpFn: u.resolveOp(),
160 })
161 if err != nil {
162 return nil, ctxerr.OpBad(u.Func, "JSON unmarshal error: %s", err)
163 }
164
165 return final, nil
166 }
167
168 // resolveOp returns a closure usable as json.ParseOpts.OpFn.
169 func (u *tdJSONUnmarshaler) resolveOp() func(json.Operator, json.Position) (any, error) {
170 return func(jop json.Operator, posInJSON json.Position) (any, error) {
171 op, exists := allOperators[jop.Name]
172 if !exists {
173 return nil, fmt.Errorf("unknown operator %s()", jop.Name)
174 }
175
176 if hint, exists := forbiddenOpsInJSON[jop.Name]; exists {
177 if hint == "" {
178 return nil, fmt.Errorf("%s() is not usable in JSON()", jop.Name)
179 }
180 return nil, fmt.Errorf("%s() is not usable in JSON(), use %s instead",
181 jop.Name, hint)
182 }
183
184 vfn := reflect.ValueOf(op)
185 tfn := vfn.Type()
186
187 // If some parameters contain a placeholder, dereference it
188 for i, p := range jop.Params {
189 if ph, ok := p.(*tdJSONPlaceholder); ok {
190 jop.Params[i] = ph.expectedValue.Interface()
191 }
192 }
193
194 // Special cases
195 var min, max int
196 jsonPointer := false
197 switch jop.Name {
198 case "Between":
199 min, max = 2, 3
200 if len(jop.Params) == 3 {
201 bad := false
202 switch tp := jop.Params[2].(type) {
203 case BoundsKind:
204 // Special case, accept numeric values of Bounds*
205 // constants, for the case:
206 // td.JSON(`Between(40, 42, $1)`, td.BoundsInOut)
207 case string:
208 switch tp {
209 case "[]", "BoundsInIn":
210 jop.Params[2] = BoundsInIn
211 case "[[", "BoundsInOut":
212 jop.Params[2] = BoundsInOut
213 case "]]", "BoundsOutIn":
214 jop.Params[2] = BoundsOutIn
215 case "][", "BoundsOutOut":
216 jop.Params[2] = BoundsOutOut
217 default:
218 bad = true
219 }
220 default:
221 bad = true
222 }
223 if bad {
224 return nil, errors.New(`Between() bad 3rd parameter, use "[]", "[[", "]]" or "]["`)
225 }
226 }
227 case "JSONPointer":
228 jsonPointer, min, max = true, 2, 2
229 case "N", "Re":
230 min, max = 1, 2
231 case "Sorted":
232 min, max = 0, -1
233 case "SubMapOf", "SuperMapOf":
234 min, max = 1, 1
235 default:
236 min = tfn.NumIn()
237 if tfn.IsVariadic() {
238 // for All(expected ...any) → min == 1, as All() is a non-sense
239 max = -1
240 } else {
241 max = min
242 }
243 }
244 if len(jop.Params) < min || (max >= 0 && len(jop.Params) > max) {
245 switch {
246 case max < 0:
247 return nil, fmt.Errorf("%s() requires at least one parameter", jop.Name)
248 case max == 0:
249 return nil, fmt.Errorf("%s() requires no parameters", jop.Name)
250 case min == max:
251 if min == 1 {
252 return nil, fmt.Errorf("%s() requires only one parameter", jop.Name)
253 }
254 return nil, fmt.Errorf("%s() requires %d parameters", jop.Name, min)
255 default:
256 return nil, fmt.Errorf("%s() requires %d or %d parameters", jop.Name, min, max)
257 }
258 }
259
260 var in []reflect.Value
261 if len(jop.Params) > 0 {
262 in = make([]reflect.Value, len(jop.Params))
263 for i, p := range jop.Params {
264 in[i] = reflect.ValueOf(p)
265 }
266 // For JSONPointer use the same json/v2 options as the JSON operator one
267 if jsonPointer && u.options != nil {
268 in = append(in, reflect.ValueOf(u.options))
269 }
270
271 // If the function is variadic, no need to check each param as all
272 // variadic operators have always a ...any
273 numCheck := len(in)
274 if tfn.IsVariadic() {
275 numCheck = tfn.NumIn() - 1
276 }
277 for i, p := range in[:numCheck] {
278 fpt := tfn.In(i)
279 if fpt.Kind() != reflect.Interface && p.Type() != fpt {
280 return nil, fmt.Errorf(
281 "%s() bad #%d parameter type: %s required but %s received",
282 jop.Name, i+1,
283 fpt, p.Type(),
284 )
285 }
286 }
287 }
288
289 tdOp := vfn.Call(in)[0].Interface().(TestDeep)
290
291 // let erroneous operators (tdOp.err != nil) pass
292
293 // replace the location by the JSON/SubJSONOf/SuperJSONOf one
294 u.replaceLocation(tdOp, posInJSON)
295 return newJSONEmbedded(tdOp, u.options), nil
296 }
297 }
298
299 // tdJSONSmuggler is the base type for tdJSONPlaceholder & tdJSONEmbedded.
300 type tdJSONSmuggler struct {
301 tdSmugglerBase // ignored by tools/gen_funcs.pl
302 options jsonv2Options
303 }
304
305 func (s *tdJSONSmuggler) Match(ctx ctxerr.Context, got reflect.Value) *ctxerr.Error {
306 vgot, _ := jsonify(ctx, got, s.options) // Cannot fail
307
308 // Here, vgot type is either a bool, float64, string,
309 // []any, a map[string]any or simply nil
310
311 return s.jsonValueEqual(ctx, vgot, s.options)
312 }
313
314 func (s *tdJSONSmuggler) String() string {
315 return util.ToString(s.expectedValue.Interface())
316 }
317
318 func (s *tdJSONSmuggler) HandleInvalid() bool {
319 return true
320 }
321
322 func (s *tdJSONSmuggler) TypeBehind() reflect.Type {
323 return s.internalTypeBehind()
324 }
325
326 // tdJSONPlaceholder is an internal smuggler operator. It represents a
327 // JSON placeholder in an unmarshaled JSON expected data structure. As $1 in:
328 //
329 // td.JSON(`{"foo": $1}`, td.Between(12, 34))
330 //
331 // It takes the JSON representation of data and compares it to
332 // expectedValue.
333 //
334 // It does its best to convert back the JSON pointed data to the type
335 // of expectedValue or to the type behind the expectedValue.
336 type tdJSONPlaceholder struct {
337 tdJSONSmuggler
338 name string
339 num uint64
340 }
341
342 func newJSONNamedPlaceholder(name string, expectedValue any, opts jsonv2Options) TestDeep {
343 p := tdJSONPlaceholder{
344 tdJSONSmuggler: tdJSONSmuggler{
345 tdSmugglerBase: newSmugglerBase(expectedValue, -100), // without location
346 options: opts,
347 },
348 name: name,
349 }
350
351 if !p.isTestDeeper {
352 p.expectedValue = reflect.ValueOf(expectedValue)
353 }
354 return &p
355 }
356
357 func newJSONNumPlaceholder(num uint64, expectedValue any, opts jsonv2Options) TestDeep {
358 p := tdJSONPlaceholder{
359 tdJSONSmuggler: tdJSONSmuggler{
360 tdSmugglerBase: newSmugglerBase(expectedValue, -100), // without location
361 options: opts,
362 },
363 num: num,
364 }
365
366 if !p.isTestDeeper {
367 p.expectedValue = reflect.ValueOf(expectedValue)
368 }
369 return &p
370 }
371
372 func (p *tdJSONPlaceholder) MarshalJSON() ([]byte, error) {
373 if !p.isTestDeeper {
374 var expected any
375 if p.expectedValue.IsValid() {
376 expected = p.expectedValue.Interface()
377 }
378 return jsonMarshal(expected, p.options)
379 }
380
381 var b bytes.Buffer
382
383 if p.num == 0 {
384 fmt.Fprintf(&b, `"$%s"`, p.name)
385 } else {
386 fmt.Fprintf(&b, `"$%d"`, p.num)
387 }
388
389 b.WriteString(` /* `)
390
391 indent := "\n" + strings.Repeat(" ", b.Len())
392 b.WriteString(strings.ReplaceAll(p.String(), "\n", indent))
393
394 b.WriteString(` */`)
395
396 return b.Bytes(), nil
397 }
398
399 // tdJSONEmbedded represents a MarshalJSON'able operator. As Between() in:
400 //
401 // td.JSON(`{"foo": Between(12, 34)}`)
402 //
403 // tdSmugglerBase always contains a TestDeep operator, newJSONEmbedded()
404 // ensures that.
405 //
406 // It does its best to convert back the JSON pointed data to the type
407 // of the type behind the expectedValue (which is always a TestDeep
408 // operator).
409 type tdJSONEmbedded struct {
410 tdJSONSmuggler
411 }
412
413 func newJSONEmbedded(tdOp TestDeep, opts jsonv2Options) TestDeep {
414 e := tdJSONEmbedded{
415 tdJSONSmuggler: tdJSONSmuggler{
416 tdSmugglerBase: newSmugglerBase(tdOp, -100), // without location
417 options: opts,
418 },
419 }
420 return &e
421 }
422
423 func (e *tdJSONEmbedded) MarshalJSON() ([]byte, error) {
424 return []byte(e.String()), nil
425 }
426
427 // tdJSON is the JSON operator.
428 type tdJSON struct {
429 baseOKNil
430 expected reflect.Value
431 options jsonv2Options
432 }
433
434 var _ TestDeep = &tdJSON{}
435
436 func gotViaJSON(ctx ctxerr.Context, pGot *reflect.Value, opts jsonv2Options) *ctxerr.Error {
437 got, err := jsonify(ctx, *pGot, opts)
438 if err != nil {
439 return err
440 }
441 *pGot = reflect.ValueOf(got)
442 return nil
443 }
444
445 func jsonify(ctx ctxerr.Context, got reflect.Value, opts jsonv2Options) (any, *ctxerr.Error) {
446 gotIf, ok := dark.GetInterface(got, true)
447 if !ok {
448 return nil, ctx.CannotCompareError()
449 }
450
451 b, err := jsonMarshal(gotIf, opts)
452 if err != nil {
453 if ctx.BooleanError {
454 return nil, ctxerr.BooleanError
455 }
456 return nil, &ctxerr.Error{
457 Message: "json.Marshal failed",
458 Summary: ctxerr.NewSummary(err.Error()),
459 }
460 }
461
462 var vgot any
463 if err = jsonUnmarshal(b, &vgot, opts); err != nil {
464 if ctx.BooleanError {
465 return nil, ctxerr.BooleanError
466 }
467 return nil, &ctxerr.Error{
468 Message: "json.Unmarshal failed",
469 Summary: ctxerr.NewSummary(err.Error()),
470 }
471 }
472 return vgot, nil
473 }
474
475 // summary(JSON): compares against JSON representation
476 // input(JSON): nil,bool,str,int,float,array,slice,map,struct,ptr
477
478 // JSON operator allows to compare the JSON representation of data
479 // against expectedJSON. expectedJSON can be a:
480 //
481 // - string containing JSON data like `{"fullname":"Bob","age":42}`
482 // - string containing a JSON filename, ending with ".json" (its
483 // content is [os.ReadFile] before unmarshaling)
484 // - []byte containing JSON data
485 // - [encoding/json.RawMessage] containing JSON data
486 // - [io.Reader] stream containing JSON data (is [io.ReadAll]
487 // before unmarshaling)
488 //
489 // expectedJSON JSON value can contain placeholders. The params are
490 // for any placeholder parameters in expectedJSON. params can contain
491 // [TestDeep] operators as well as raw values. A placeholder can be
492 // numeric like $2 or named like $name and always references an item
493 // in params. params can also contains [encoding/json/v2.Options] when
494 // [encoding/json/v2] must be used, see jsonv2 example.
495 //
496 // Numeric placeholders reference the n'th "operators" item (starting
497 // at 1). Named placeholders are used with [Tag] operator as follows:
498 //
499 // td.Cmp(t, gotValue,
500 // td.JSON(`{"fullname": $name, "age": $2, "gender": $3}`,
501 // td.Tag("name", td.HasPrefix("Foo")), // matches $1 and $name
502 // td.Between(41, 43), // matches only $2
503 // "male")) // matches only $3
504 //
505 // Note that placeholders can be double-quoted as in:
506 //
507 // td.Cmp(t, gotValue,
508 // td.JSON(`{"fullname": "$name", "age": "$2", "gender": "$3"}`,
509 // td.Tag("name", td.HasPrefix("Foo")), // matches $1 and $name
510 // td.Between(41, 43), // matches only $2
511 // "male")) // matches only $3
512 //
513 // It makes no difference whatever the underlying type of the replaced
514 // item is (= double quoting a placeholder matching a number is not a
515 // problem). It is just a matter of taste, double-quoting placeholders
516 // can be preferred when the JSON data has to conform to the JSON
517 // specification, like when used in a ".json" file.
518 //
519 // JSON does its best to convert back the JSON corresponding to a
520 // placeholder to the type of the placeholder or, if the placeholder
521 // is an operator, to the type behind the operator. Allowing to do
522 // things like:
523 //
524 // td.Cmp(t, gotValue, td.JSON(`{"foo":$1}`, []int{1, 2, 3, 4}))
525 // td.Cmp(t, gotValue,
526 // td.JSON(`{"foo":$1}`, []any{1, 2, td.Between(2, 4), 4}))
527 // td.Cmp(t, gotValue, td.JSON(`{"foo":$1}`, td.Between(27, 32)))
528 //
529 // Of course, it does this conversion only if the expected type can be
530 // guessed. In the case the conversion cannot occur, data is compared
531 // as is, in its freshly unmarshaled JSON form (so as bool, float64,
532 // string, []any, map[string]any or simply nil).
533 //
534 // Note expectedJSON can be a []byte, an [encoding/json.RawMessage], a
535 // JSON filename or a [io.Reader]:
536 //
537 // td.Cmp(t, gotValue, td.JSON("file.json", td.Between(12, 34)))
538 // td.Cmp(t, gotValue, td.JSON([]byte(`[1, $1, 3]`), td.Between(12, 34)))
539 // td.Cmp(t, gotValue, td.JSON(osFile, td.Between(12, 34)))
540 //
541 // A JSON filename ends with ".json".
542 //
543 // To avoid a legit "$" string prefix causes a bad placeholder error,
544 // just double it to escape it. Note it is only needed when the "$" is
545 // the first character of a string:
546 //
547 // td.Cmp(t, gotValue,
548 // td.JSON(`{"fullname": "$name", "details": "$$info", "age": $2}`,
549 // td.Tag("name", td.HasPrefix("Foo")), // matches $1 and $name
550 // td.Between(41, 43))) // matches only $2
551 //
552 // For the "details" key, the raw value "$info" is expected, no
553 // placeholders are involved here.
554 //
555 // Note that [Lax] mode is automatically enabled by JSON operator to
556 // simplify numeric tests.
557 //
558 // Comments can be embedded in JSON data:
559 //
560 // td.Cmp(t, gotValue,
561 // td.JSON(`
562 // {
563 // // A guy properties:
564 // "fullname": "$name", // The full name of the guy
565 // "details": "$$info", // Literally "$info", thanks to "$" escape
566 // "age": $2 /* The age of the guy:
567 // - placeholder unquoted, but could be without
568 // any change
569 // - to demonstrate a multi-lines comment */
570 // }`,
571 // td.Tag("name", td.HasPrefix("Foo")), // matches $1 and $name
572 // td.Between(41, 43))) // matches only $2
573 //
574 // Comments, like in go, have 2 forms. To quote the Go language specification:
575 // - line comments start with the character sequence // and stop at the
576 // end of the line.
577 // - multi-lines comments start with the character sequence /* and stop
578 // with the first subsequent character sequence */.
579 //
580 // Other JSON divergences:
581 // - ',' can precede a '}' or a ']' (as in go);
582 // - strings can contain non-escaped \n, \r and \t;
583 // - raw strings are accepted (r{raw}, r!raw!, …), see below;
584 // - int_lit & float_lit numbers as defined in go spec are accepted;
585 // - numbers can be prefixed by '+'.
586 //
587 // Most operators can be directly embedded in JSON without requiring
588 // any placeholder. If an operators does not take any parameter, the
589 // parenthesis can be omitted.
590 //
591 // td.Cmp(t, gotValue,
592 // td.JSON(`
593 // {
594 // "fullname": HasPrefix("Foo"),
595 // "age": Between(41, 43),
596 // "details": SuperMapOf({
597 // "address": NotEmpty, // () are optional when no parameters
598 // "car": Any("Peugeot", "Tesla", "Jeep") // any of these
599 // })
600 // }`))
601 //
602 // Placeholders can be used anywhere, even in operators parameters as in:
603 //
604 // td.Cmp(t, gotValue, td.JSON(`{"fullname": HasPrefix($1)}`, "Zip"))
605 //
606 // A few notes about operators embedding:
607 // - [SubMapOf] and [SuperMapOf] take only one parameter, a JSON object;
608 // - the optional 3rd parameter of [Between] has to be specified as a string
609 // and can be: "[]" or "BoundsInIn" (default), "[[" or "BoundsInOut",
610 // "]]" or "BoundsOutIn", "][" or "BoundsOutOut";
611 // - the optional 3rd parameter of [JSONPointer] (opts) is filled by all
612 // [encoding/json/v2.Options] values found in params, so it uses the
613 // same marshal/unmarshal semantics as JSON itself. If that's not
614 // desirable, do not embed [JSONPointer] and use a placeholder instead;
615 // - not all operators are embeddable only the following are: [All],
616 // [Any], [ArrayEach], [Bag], [Between], [Contains],
617 // [ContainsKey], [Empty], [First], [Grep], [Gt], [Gte],
618 // [HasPrefix], [HasSuffix], [Ignore], [JSONPointer], [Keys],
619 // [Last], [Len], [Lt], [Lte], [MapEach], [N], [NaN], [Nil],
620 // [None], [Not], [NotAny], [NotEmpty], [NotNaN], [NotNil],
621 // [NotZero], [Re], [ReAll], [Set], [Sort], [Sorted], [SubBagOf],
622 // [SubMapOf], [SubSetOf], [SuperBagOf], [SuperMapOf],
623 // [SuperSetOf], [Values] and [Zero].
624 //
625 // It is also possible to embed operators in JSON strings. This way,
626 // the JSON specification can be fulfilled. To avoid collision with
627 // possible strings, just prefix the first operator name with
628 // "$^". The previous example becomes:
629 //
630 // td.Cmp(t, gotValue,
631 // td.JSON(`
632 // {
633 // "fullname": "$^HasPrefix(\"Foo\")",
634 // "age": "$^Between(41, 43)",
635 // "details": "$^SuperMapOf({
636 // \"address\": NotEmpty, // () are optional when no parameters
637 // \"car\": Any(\"Peugeot\", \"Tesla\", \"Jeep\") // any of these
638 // })"
639 // }`))
640 //
641 // As you can see, in this case, strings in strings have to be
642 // escaped. Fortunately, newlines are accepted, but unfortunately they
643 // are forbidden by JSON specification. To avoid too much escaping,
644 // raw strings are accepted. A raw string is a "r" followed by a
645 // delimiter, the corresponding delimiter closes the string. The
646 // following raw strings are all the same as "foo\\bar(\"zip\")!":
647 // - r'foo\bar"zip"!'
648 // - r,foo\bar"zip"!,
649 // - r%foo\bar"zip"!%
650 // - r(foo\bar("zip")!)
651 // - r{foo\bar("zip")!}
652 // - r[foo\bar("zip")!]
653 // - r<foo\bar("zip")!>
654 //
655 // So non-bracketing delimiters use the same character before and
656 // after, but the 4 sorts of ASCII brackets (round, angle, square,
657 // curly) all nest: r[x[y]z] equals "x[y]z". The end delimiter cannot
658 // be escaped.
659 //
660 // With raw strings, the previous example becomes:
661 //
662 // td.Cmp(t, gotValue,
663 // td.JSON(`
664 // {
665 // "fullname": "$^HasPrefix(r<Foo>)",
666 // "age": "$^Between(41, 43)",
667 // "details": "$^SuperMapOf({
668 // r<address>: NotEmpty, // () are optional when no parameters
669 // r<car>: Any(r<Peugeot>, r<Tesla>, r<Jeep>) // any of these
670 // })"
671 // }`))
672 //
673 // Note that raw strings are accepted anywhere, not only in original
674 // JSON strings.
675 //
676 // To be complete, $^ can prefix an operator even outside a
677 // string. This is accepted for compatibility purpose as the first
678 // operator embedding feature used this way to embed some operators.
679 //
680 // So the following calls are all equivalent:
681 //
682 // td.Cmp(t, gotValue, td.JSON(`{"id": $1}`, td.NotZero()))
683 // td.Cmp(t, gotValue, td.JSON(`{"id": NotZero}`))
684 // td.Cmp(t, gotValue, td.JSON(`{"id": NotZero()}`))
685 // td.Cmp(t, gotValue, td.JSON(`{"id": $^NotZero}`))
686 // td.Cmp(t, gotValue, td.JSON(`{"id": $^NotZero()}`))
687 // td.Cmp(t, gotValue, td.JSON(`{"id": "$^NotZero"}`))
688 // td.Cmp(t, gotValue, td.JSON(`{"id": "$^NotZero()"}`))
689 //
690 // As for placeholders, there is no differences between $^NotZero and
691 // "$^NotZero".
692 //
693 // Tip: when an [io.Reader] is expected to contain JSON data, it
694 // cannot be tested directly, but using the [Smuggle] operator simply
695 // solves the problem:
696 //
697 // var body io.Reader
698 // // …
699 // td.Cmp(t, body, td.Smuggle(json.RawMessage{}, td.JSON(`{"foo":1}`)))
700 // // or equally
701 // td.Cmp(t, body, td.Smuggle(json.RawMessage(nil), td.JSON(`{"foo":1}`)))
702 //
703 // [Smuggle] reads from body into an [encoding/json.RawMessage] then
704 // this buffer is unmarshaled by JSON operator before the comparison.
705 //
706 // TypeBehind method returns the [reflect.Type] of the expectedJSON
707 // once JSON unmarshaled. So it can be bool, string, float64, []any,
708 // map[string]any or any in case expectedJSON is "null".
709 //
710 // See also [JSONPointer], [SubJSONOf] and [SuperJSONOf].
711 func JSON(expectedJSON any, params ...any) TestDeep {
712 j := &tdJSON{
713 baseOKNil: newBaseOKNil(3),
714 }
715
716 ju := newJSONUnmarshaler(j.GetLocation())
717
718 v, err := ju.unmarshal(expectedJSON, params)
719 if err != nil {
720 j.err = err
721 } else {
722 j.expected = reflect.ValueOf(v)
723 j.options = ju.options
724 }
725
726 return j
727 }
728
729 func (j *tdJSON) Match(ctx ctxerr.Context, got reflect.Value) *ctxerr.Error {
730 if j.err != nil {
731 return ctx.CollectError(j.err)
732 }
733
734 err := gotViaJSON(ctx, &got, j.options)
735 if err != nil {
736 return ctx.CollectError(err)
737 }
738
739 ctx.BeLax = true
740
741 return deepValueEqual(ctx, got, j.expected)
742 }
743
744 func (j *tdJSON) String() string {
745 if j.err != nil {
746 return j.stringError()
747 }
748
749 return jsonStringify("JSON", j.expected)
750 }
751
752 func jsonStringify(opName string, v reflect.Value) string {
753 if !v.IsValid() {
754 return "JSON(null)"
755 }
756
757 var b bytes.Buffer
758
759 b.WriteString(opName)
760 b.WriteByte('(')
761 json.AppendMarshal(&b, v.Interface(), len(opName)+1) //nolint: errcheck
762 b.WriteByte(')')
763
764 return b.String()
765 }
766
767 func (j *tdJSON) TypeBehind() reflect.Type {
768 if j.err != nil {
769 return nil
770 }
771
772 if j.expected.IsValid() {
773 // In case we have an operator at the root, delegate it the call
774 if tdOp, ok := j.expected.Interface().(TestDeep); ok {
775 return tdOp.TypeBehind()
776 }
777 return j.expected.Type()
778 }
779 return types.Interface
780 }
781
782 type tdMapJSON struct {
783 tdMap
784 expected reflect.Value
785 options jsonv2Options
786 }
787
788 var _ TestDeep = &tdMapJSON{}
789
790 // summary(SubJSONOf): compares struct or map against JSON
791 // representation but with potentially some exclusions
792 // input(SubJSONOf): map,struct,ptr(ptr on map/struct)
793
794 // SubJSONOf operator allows to compare the JSON representation of
795 // data against expectedJSON. Unlike [JSON] operator, marshaled data
796 // must be a JSON object/map (aka {…}). expectedJSON can be a:
797 //
798 // - string containing JSON data like `{"fullname":"Bob","age":42}`
799 // - string containing a JSON filename, ending with ".json" (its
800 // content is [os.ReadFile] before unmarshaling)
801 // - []byte containing JSON data
802 // - [encoding/json.RawMessage] containing JSON data
803 // - [io.Reader] stream containing JSON data (is [io.ReadAll] before
804 // unmarshaling)
805 //
806 // JSON data contained in expectedJSON must be a JSON object/map
807 // (aka {…}) too. During a match, each expected entry should match in
808 // the compared map. But some expected entries can be missing from the
809 // compared map.
810 //
811 // type MyStruct struct {
812 // Name string `json:"name"`
813 // Age int `json:"age"`
814 // }
815 // got := MyStruct{
816 // Name: "Bob",
817 // Age: 42,
818 // }
819 // td.Cmp(t, got, td.SubJSONOf(`{"name": "Bob", "age": 42, "city": "NY"}`)) // succeeds
820 // td.Cmp(t, got, td.SubJSONOf(`{"name": "Bob", "zip": 666}`)) // fails, extra "age"
821 //
822 // expectedJSON JSON value can contain placeholders. The params are
823 // for any placeholder parameters in expectedJSON. params can contain
824 // [TestDeep] operators as well as raw values. A placeholder can be
825 // numeric like $2 or named like $name and always references an item
826 // in params. params can also contains [encoding/json/v2.Options] when
827 // [encoding/json/v2] must be used, see jsonv2 example.
828 //
829 // Numeric placeholders reference the n'th "operators" item (starting
830 // at 1). Named placeholders are used with [Tag] operator as follows:
831 //
832 // td.Cmp(t, gotValue,
833 // td.SubJSONOf(`{"fullname": $name, "age": $2, "gender": $3}`,
834 // td.Tag("name", td.HasPrefix("Foo")), // matches $1 and $name
835 // td.Between(41, 43), // matches only $2
836 // "male")) // matches only $3
837 //
838 // Note that placeholders can be double-quoted as in:
839 //
840 // td.Cmp(t, gotValue,
841 // td.SubJSONOf(`{"fullname": "$name", "age": "$2", "gender": "$3"}`,
842 // td.Tag("name", td.HasPrefix("Foo")), // matches $1 and $name
843 // td.Between(41, 43), // matches only $2
844 // "male")) // matches only $3
845 //
846 // It makes no difference whatever the underlying type of the replaced
847 // item is (= double quoting a placeholder matching a number is not a
848 // problem). It is just a matter of taste, double-quoting placeholders
849 // can be preferred when the JSON data has to conform to the JSON
850 // specification, like when used in a ".json" file.
851 //
852 // SubJSONOf does its best to convert back the JSON corresponding to a
853 // placeholder to the type of the placeholder or, if the placeholder
854 // is an operator, to the type behind the operator. Allowing to do
855 // things like:
856 //
857 // td.Cmp(t, gotValue,
858 // td.SubJSONOf(`{"foo":$1, "bar": 12}`, []int{1, 2, 3, 4}))
859 // td.Cmp(t, gotValue,
860 // td.SubJSONOf(`{"foo":$1, "bar": 12}`, []any{1, 2, td.Between(2, 4), 4}))
861 // td.Cmp(t, gotValue,
862 // td.SubJSONOf(`{"foo":$1, "bar": 12}`, td.Between(27, 32)))
863 //
864 // Of course, it does this conversion only if the expected type can be
865 // guessed. In the case the conversion cannot occur, data is compared
866 // as is, in its freshly unmarshaled JSON form (so as bool, float64,
867 // string, []any, map[string]any or simply nil).
868 //
869 // Note expectedJSON can be a []byte, an [encoding/json.RawMessage], a
870 // JSON filename or a [io.Reader]:
871 //
872 // td.Cmp(t, gotValue, td.SubJSONOf("file.json", td.Between(12, 34)))
873 // td.Cmp(t, gotValue, td.SubJSONOf([]byte(`[1, $1, 3]`), td.Between(12, 34)))
874 // td.Cmp(t, gotValue, td.SubJSONOf(osFile, td.Between(12, 34)))
875 //
876 // A JSON filename ends with ".json".
877 //
878 // To avoid a legit "$" string prefix causes a bad placeholder error,
879 // just double it to escape it. Note it is only needed when the "$" is
880 // the first character of a string:
881 //
882 // td.Cmp(t, gotValue,
883 // td.SubJSONOf(`{"fullname": "$name", "details": "$$info", "age": $2}`,
884 // td.Tag("name", td.HasPrefix("Foo")), // matches $1 and $name
885 // td.Between(41, 43))) // matches only $2
886 //
887 // For the "details" key, the raw value "$info" is expected, no
888 // placeholders are involved here.
889 //
890 // Note that [Lax] mode is automatically enabled by SubJSONOf operator to
891 // simplify numeric tests.
892 //
893 // Comments can be embedded in JSON data:
894 //
895 // td.Cmp(t, gotValue,
896 // SubJSONOf(`
897 // {
898 // // A guy properties:
899 // "fullname": "$name", // The full name of the guy
900 // "details": "$$info", // Literally "$info", thanks to "$" escape
901 // "age": $2 /* The age of the guy:
902 // - placeholder unquoted, but could be without
903 // any change
904 // - to demonstrate a multi-lines comment */
905 // }`,
906 // td.Tag("name", td.HasPrefix("Foo")), // matches $1 and $name
907 // td.Between(41, 43))) // matches only $2
908 //
909 // Comments, like in go, have 2 forms. To quote the Go language specification:
910 // - line comments start with the character sequence // and stop at the
911 // end of the line.
912 // - multi-lines comments start with the character sequence /* and stop
913 // with the first subsequent character sequence */.
914 //
915 // Other JSON divergences:
916 // - ',' can precede a '}' or a ']' (as in go);
917 // - strings can contain non-escaped \n, \r and \t;
918 // - raw strings are accepted (r{raw}, r!raw!, …), see below;
919 // - int_lit & float_lit numbers as defined in go spec are accepted;
920 // - numbers can be prefixed by '+'.
921 //
922 // Most operators can be directly embedded in SubJSONOf without requiring
923 // any placeholder. If an operators does not take any parameter, the
924 // parenthesis can be omitted.
925 //
926 // td.Cmp(t, gotValue,
927 // td.SubJSONOf(`
928 // {
929 // "fullname": HasPrefix("Foo"),
930 // "age": Between(41, 43),
931 // "details": SuperMapOf({
932 // "address": NotEmpty, // () are optional when no parameters
933 // "car": Any("Peugeot", "Tesla", "Jeep") // any of these
934 // })
935 // }`))
936 //
937 // Placeholders can be used anywhere, even in operators parameters as in:
938 //
939 // td.Cmp(t, gotValue,
940 // td.SubJSONOf(`{"fullname": HasPrefix($1), "bar": 42}`, "Zip"))
941 //
942 // A few notes about operators embedding:
943 // - [SubMapOf] and [SuperMapOf] take only one parameter, a JSON object;
944 // - the optional 3rd parameter of [Between] has to be specified as a string
945 // and can be: "[]" or "BoundsInIn" (default), "[[" or "BoundsInOut",
946 // "]]" or "BoundsOutIn", "][" or "BoundsOutOut";
947 // - the optional 3rd parameter of [JSONPointer] (opts) is filled by all
948 // [encoding/json/v2.Options] values found in params, so it uses the
949 // same marshal/unmarshal semantics as JSON itself. If that's not
950 // desirable, do not embed [JSONPointer] and use a placeholder instead;
951 // - not all operators are embeddable only the following are: [All],
952 // [Any], [ArrayEach], [Bag], [Between], [Contains],
953 // [ContainsKey], [Empty], [First], [Grep], [Gt], [Gte],
954 // [HasPrefix], [HasSuffix], [Ignore], [JSONPointer], [Keys],
955 // [Last], [Len], [Lt], [Lte], [MapEach], [N], [NaN], [Nil],
956 // [None], [Not], [NotAny], [NotEmpty], [NotNaN], [NotNil],
957 // [NotZero], [Re], [ReAll], [Set], [Sort], [Sorted], [SubBagOf],
958 // [SubMapOf], [SubSetOf], [SuperBagOf], [SuperMapOf],
959 // [SuperSetOf], [Values] and [Zero].
960 //
961 // It is also possible to embed operators in JSON strings. This way,
962 // the JSON specification can be fulfilled. To avoid collision with
963 // possible strings, just prefix the first operator name with
964 // "$^". The previous example becomes:
965 //
966 // td.Cmp(t, gotValue,
967 // td.SubJSONOf(`
968 // {
969 // "fullname": "$^HasPrefix(\"Foo\")",
970 // "age": "$^Between(41, 43)",
971 // "details": "$^SuperMapOf({
972 // \"address\": NotEmpty, // () are optional when no parameters
973 // \"car\": Any(\"Peugeot\", \"Tesla\", \"Jeep\") // any of these
974 // })"
975 // }`))
976 //
977 // As you can see, in this case, strings in strings have to be
978 // escaped. Fortunately, newlines are accepted, but unfortunately they
979 // are forbidden by JSON specification. To avoid too much escaping,
980 // raw strings are accepted. A raw string is a "r" followed by a
981 // delimiter, the corresponding delimiter closes the string. The
982 // following raw strings are all the same as "foo\\bar(\"zip\")!":
983 // - r'foo\bar"zip"!'
984 // - r,foo\bar"zip"!,
985 // - r%foo\bar"zip"!%
986 // - r(foo\bar("zip")!)
987 // - r{foo\bar("zip")!}
988 // - r[foo\bar("zip")!]
989 // - r<foo\bar("zip")!>
990 //
991 // So non-bracketing delimiters use the same character before and
992 // after, but the 4 sorts of ASCII brackets (round, angle, square,
993 // curly) all nest: r[x[y]z] equals "x[y]z". The end delimiter cannot
994 // be escaped.
995 //
996 // With raw strings, the previous example becomes:
997 //
998 // td.Cmp(t, gotValue,
999 // td.SubJSONOf(`
1000 // {
1001 // "fullname": "$^HasPrefix(r<Foo>)",
1002 // "age": "$^Between(41, 43)",
1003 // "details": "$^SuperMapOf({
1004 // r<address>: NotEmpty, // () are optional when no parameters
1005 // r<car>: Any(r<Peugeot>, r<Tesla>, r<Jeep>) // any of these
1006 // })"
1007 // }`))
1008 //
1009 // Note that raw strings are accepted anywhere, not only in original
1010 // JSON strings.
1011 //
1012 // To be complete, $^ can prefix an operator even outside a
1013 // string. This is accepted for compatibility purpose as the first
1014 // operator embedding feature used this way to embed some operators.
1015 //
1016 // So the following calls are all equivalent:
1017 //
1018 // td.Cmp(t, gotValue, td.SubJSONOf(`{"id": $1}`, td.NotZero()))
1019 // td.Cmp(t, gotValue, td.SubJSONOf(`{"id": NotZero}`))
1020 // td.Cmp(t, gotValue, td.SubJSONOf(`{"id": NotZero()}`))
1021 // td.Cmp(t, gotValue, td.SubJSONOf(`{"id": $^NotZero}`))
1022 // td.Cmp(t, gotValue, td.SubJSONOf(`{"id": $^NotZero()}`))
1023 // td.Cmp(t, gotValue, td.SubJSONOf(`{"id": "$^NotZero"}`))
1024 // td.Cmp(t, gotValue, td.SubJSONOf(`{"id": "$^NotZero()"}`))
1025 //
1026 // As for placeholders, there is no differences between $^NotZero and
1027 // "$^NotZero".
1028 //
1029 // Tip: when an [io.Reader] is expected to contain JSON data, it
1030 // cannot be tested directly, but using the [Smuggle] operator simply
1031 // solves the problem:
1032 //
1033 // var body io.Reader
1034 // // …
1035 // td.Cmp(t, body, td.Smuggle(json.RawMessage{}, td.SubJSONOf(`{"foo":1,"bar":2}`)))
1036 // // or equally
1037 // td.Cmp(t, body, td.Smuggle(json.RawMessage(nil), td.SubJSONOf(`{"foo":1,"bar":2}`)))
1038 //
1039 // [Smuggle] reads from body into an [encoding/json.RawMessage] then
1040 // this buffer is unmarshaled by SubJSONOf operator before the comparison.
1041 //
1042 // TypeBehind method returns the map[string]any type.
1043 //
1044 // See also [JSON], [JSONPointer] and [SuperJSONOf].
1045 func SubJSONOf(expectedJSON any, params ...any) TestDeep {
1046 m := &tdMapJSON{
1047 tdMap: tdMap{
1048 tdExpectedType: tdExpectedType{
1049 base: newBase(3),
1050 expectedType: reflect.TypeOf((map[string]any)(nil)),
1051 },
1052 kind: subMap,
1053 },
1054 }
1055
1056 ju := newJSONUnmarshaler(m.GetLocation())
1057
1058 v, err := ju.unmarshal(expectedJSON, params)
1059 if err != nil {
1060 m.err = err
1061 return m
1062 }
1063
1064 _, ok := v.(map[string]any)
1065 if !ok {
1066 m.err = ctxerr.OpBad("SubJSONOf", "SubJSONOf() only accepts JSON objects {…}")
1067 return m
1068 }
1069
1070 m.expected = reflect.ValueOf(v)
1071 m.options = ju.options
1072
1073 m.populateExpectedEntries(nil, m.expected)
1074 return m
1075 }
1076
1077 // summary(SuperJSONOf): compares struct or map against JSON
1078 // representation but with potentially extra entries
1079 // input(SuperJSONOf): map,struct,ptr(ptr on map/struct)
1080
1081 // SuperJSONOf operator allows to compare the JSON representation of
1082 // data against expectedJSON. Unlike JSON operator, marshaled data
1083 // must be a JSON object/map (aka {…}). expectedJSON can be a:
1084 //
1085 // - string containing JSON data like `{"fullname":"Bob","age":42}`
1086 // - string containing a JSON filename, ending with ".json" (its
1087 // content is [os.ReadFile] before unmarshaling)
1088 // - []byte containing JSON data
1089 // - [encoding/json.RawMessage] containing JSON data
1090 // - [io.Reader] stream containing JSON data (is [io.ReadAll] before
1091 // unmarshaling)
1092 //
1093 // JSON data contained in expectedJSON must be a JSON object/map
1094 // (aka {…}) too. During a match, each expected entry should match in
1095 // the compared map. But some entries in the compared map may not be
1096 // expected.
1097 //
1098 // type MyStruct struct {
1099 // Name string `json:"name"`
1100 // Age int `json:"age"`
1101 // City string `json:"city"`
1102 // }
1103 // got := MyStruct{
1104 // Name: "Bob",
1105 // Age: 42,
1106 // City: "TestCity",
1107 // }
1108 // td.Cmp(t, got, td.SuperJSONOf(`{"name": "Bob", "age": 42}`)) // succeeds
1109 // td.Cmp(t, got, td.SuperJSONOf(`{"name": "Bob", "zip": 666}`)) // fails, miss "zip"
1110 //
1111 // expectedJSON JSON value can contain placeholders. The params are
1112 // for any placeholder parameters in expectedJSON. params can contain
1113 // [TestDeep] operators as well as raw values. A placeholder can be
1114 // numeric like $2 or named like $name and always references an item
1115 // in params. params can also contains [encoding/json/v2.Options] when
1116 // [encoding/json/v2] must be used, see jsonv2 example.
1117 //
1118 // Numeric placeholders reference the n'th "operators" item (starting
1119 // at 1). Named placeholders are used with [Tag] operator as follows:
1120 //
1121 // td.Cmp(t, gotValue,
1122 // SuperJSONOf(`{"fullname": $name, "age": $2, "gender": $3}`,
1123 // td.Tag("name", td.HasPrefix("Foo")), // matches $1 and $name
1124 // td.Between(41, 43), // matches only $2
1125 // "male")) // matches only $3
1126 //
1127 // Note that placeholders can be double-quoted as in:
1128 //
1129 // td.Cmp(t, gotValue,
1130 // td.SuperJSONOf(`{"fullname": "$name", "age": "$2", "gender": "$3"}`,
1131 // td.Tag("name", td.HasPrefix("Foo")), // matches $1 and $name
1132 // td.Between(41, 43), // matches only $2
1133 // "male")) // matches only $3
1134 //
1135 // It makes no difference whatever the underlying type of the replaced
1136 // item is (= double quoting a placeholder matching a number is not a
1137 // problem). It is just a matter of taste, double-quoting placeholders
1138 // can be preferred when the JSON data has to conform to the JSON
1139 // specification, like when used in a ".json" file.
1140 //
1141 // SuperJSONOf does its best to convert back the JSON corresponding to a
1142 // placeholder to the type of the placeholder or, if the placeholder
1143 // is an operator, to the type behind the operator. Allowing to do
1144 // things like:
1145 //
1146 // td.Cmp(t, gotValue,
1147 // td.SuperJSONOf(`{"foo":$1}`, []int{1, 2, 3, 4}))
1148 // td.Cmp(t, gotValue,
1149 // td.SuperJSONOf(`{"foo":$1}`, []any{1, 2, td.Between(2, 4), 4}))
1150 // td.Cmp(t, gotValue,
1151 // td.SuperJSONOf(`{"foo":$1}`, td.Between(27, 32)))
1152 //
1153 // Of course, it does this conversion only if the expected type can be
1154 // guessed. In the case the conversion cannot occur, data is compared
1155 // as is, in its freshly unmarshaled JSON form (so as bool, float64,
1156 // string, []any, map[string]any or simply nil).
1157 //
1158 // Note expectedJSON can be a []byte, an [encoding/json.RawMessage], a
1159 // JSON filename or a [io.Reader]:
1160 //
1161 // td.Cmp(t, gotValue, td.SuperJSONOf("file.json", td.Between(12, 34)))
1162 // td.Cmp(t, gotValue, td.SuperJSONOf([]byte(`[1, $1, 3]`), td.Between(12, 34)))
1163 // td.Cmp(t, gotValue, td.SuperJSONOf(osFile, td.Between(12, 34)))
1164 //
1165 // A JSON filename ends with ".json".
1166 //
1167 // To avoid a legit "$" string prefix causes a bad placeholder error,
1168 // just double it to escape it. Note it is only needed when the "$" is
1169 // the first character of a string:
1170 //
1171 // td.Cmp(t, gotValue,
1172 // td.SuperJSONOf(`{"fullname": "$name", "details": "$$info", "age": $2}`,
1173 // td.Tag("name", td.HasPrefix("Foo")), // matches $1 and $name
1174 // td.Between(41, 43))) // matches only $2
1175 //
1176 // For the "details" key, the raw value "$info" is expected, no
1177 // placeholders are involved here.
1178 //
1179 // Note that [Lax] mode is automatically enabled by SuperJSONOf operator to
1180 // simplify numeric tests.
1181 //
1182 // Comments can be embedded in JSON data:
1183 //
1184 // td.Cmp(t, gotValue,
1185 // td.SuperJSONOf(`
1186 // {
1187 // // A guy properties:
1188 // "fullname": "$name", // The full name of the guy
1189 // "details": "$$info", // Literally "$info", thanks to "$" escape
1190 // "age": $2 /* The age of the guy:
1191 // - placeholder unquoted, but could be without
1192 // any change
1193 // - to demonstrate a multi-lines comment */
1194 // }`,
1195 // td.Tag("name", td.HasPrefix("Foo")), // matches $1 and $name
1196 // td.Between(41, 43))) // matches only $2
1197 //
1198 // Comments, like in go, have 2 forms. To quote the Go language specification:
1199 // - line comments start with the character sequence // and stop at the
1200 // end of the line.
1201 // - multi-lines comments start with the character sequence /* and stop
1202 // with the first subsequent character sequence */.
1203 //
1204 // Other JSON divergences:
1205 // - ',' can precede a '}' or a ']' (as in go);
1206 // - strings can contain non-escaped \n, \r and \t;
1207 // - raw strings are accepted (r{raw}, r!raw!, …), see below;
1208 // - int_lit & float_lit numbers as defined in go spec are accepted;
1209 // - numbers can be prefixed by '+'.
1210 //
1211 // Most operators can be directly embedded in SuperJSONOf without requiring
1212 // any placeholder. If an operators does not take any parameter, the
1213 // parenthesis can be omitted.
1214 //
1215 // td.Cmp(t, gotValue,
1216 // td.SuperJSONOf(`
1217 // {
1218 // "fullname": HasPrefix("Foo"),
1219 // "age": Between(41, 43),
1220 // "details": SuperMapOf({
1221 // "address": NotEmpty, // () are optional when no parameters
1222 // "car": Any("Peugeot", "Tesla", "Jeep") // any of these
1223 // })
1224 // }`))
1225 //
1226 // Placeholders can be used anywhere, even in operators parameters as in:
1227 //
1228 // td.Cmp(t, gotValue, td.SuperJSONOf(`{"fullname": HasPrefix($1)}`, "Zip"))
1229 //
1230 // A few notes about operators embedding:
1231 // - [SubMapOf] and [SuperMapOf] take only one parameter, a JSON object;
1232 // - the optional 3rd parameter of [Between] has to be specified as a string
1233 // and can be: "[]" or "BoundsInIn" (default), "[[" or "BoundsInOut",
1234 // "]]" or "BoundsOutIn", "][" or "BoundsOutOut";
1235 // - the optional 3rd parameter of [JSONPointer] (opts) is filled by all
1236 // [encoding/json/v2.Options] values found in params, so it uses the
1237 // same marshal/unmarshal semantics as JSON itself. If that's not
1238 // desirable, do not embed [JSONPointer] and use a placeholder instead;
1239 // - not all operators are embeddable only the following are: [All],
1240 // [Any], [ArrayEach], [Bag], [Between], [Contains],
1241 // [ContainsKey], [Empty], [First], [Grep], [Gt], [Gte],
1242 // [HasPrefix], [HasSuffix], [Ignore], [JSONPointer], [Keys],
1243 // [Last], [Len], [Lt], [Lte], [MapEach], [N], [NaN], [Nil],
1244 // [None], [Not], [NotAny], [NotEmpty], [NotNaN], [NotNil],
1245 // [NotZero], [Re], [ReAll], [Set], [Sort], [Sorted], [SubBagOf],
1246 // [SubMapOf], [SubSetOf], [SuperBagOf], [SuperMapOf],
1247 // [SuperSetOf], [Values] and [Zero].
1248 //
1249 // It is also possible to embed operators in JSON strings. This way,
1250 // the JSON specification can be fulfilled. To avoid collision with
1251 // possible strings, just prefix the first operator name with
1252 // "$^". The previous example becomes:
1253 //
1254 // td.Cmp(t, gotValue,
1255 // td.SuperJSONOf(`
1256 // {
1257 // "fullname": "$^HasPrefix(\"Foo\")",
1258 // "age": "$^Between(41, 43)",
1259 // "details": "$^SuperMapOf({
1260 // \"address\": NotEmpty, // () are optional when no parameters
1261 // \"car\": Any(\"Peugeot\", \"Tesla\", \"Jeep\") // any of these
1262 // })"
1263 // }`))
1264 //
1265 // As you can see, in this case, strings in strings have to be
1266 // escaped. Fortunately, newlines are accepted, but unfortunately they
1267 // are forbidden by JSON specification. To avoid too much escaping,
1268 // raw strings are accepted. A raw string is a "r" followed by a
1269 // delimiter, the corresponding delimiter closes the string. The
1270 // following raw strings are all the same as "foo\\bar(\"zip\")!":
1271 // - r'foo\bar"zip"!'
1272 // - r,foo\bar"zip"!,
1273 // - r%foo\bar"zip"!%
1274 // - r(foo\bar("zip")!)
1275 // - r{foo\bar("zip")!}
1276 // - r[foo\bar("zip")!]
1277 // - r<foo\bar("zip")!>
1278 //
1279 // So non-bracketing delimiters use the same character before and
1280 // after, but the 4 sorts of ASCII brackets (round, angle, square,
1281 // curly) all nest: r[x[y]z] equals "x[y]z". The end delimiter cannot
1282 // be escaped.
1283 //
1284 // With raw strings, the previous example becomes:
1285 //
1286 // td.Cmp(t, gotValue,
1287 // td.SuperJSONOf(`
1288 // {
1289 // "fullname": "$^HasPrefix(r<Foo>)",
1290 // "age": "$^Between(41, 43)",
1291 // "details": "$^SuperMapOf({
1292 // r<address>: NotEmpty, // () are optional when no parameters
1293 // r<car>: Any(r<Peugeot>, r<Tesla>, r<Jeep>) // any of these
1294 // })"
1295 // }`))
1296 //
1297 // Note that raw strings are accepted anywhere, not only in original
1298 // JSON strings.
1299 //
1300 // To be complete, $^ can prefix an operator even outside a
1301 // string. This is accepted for compatibility purpose as the first
1302 // operator embedding feature used this way to embed some operators.
1303 //
1304 // So the following calls are all equivalent:
1305 //
1306 // td.Cmp(t, gotValue, td.SuperJSONOf(`{"id": $1}`, td.NotZero()))
1307 // td.Cmp(t, gotValue, td.SuperJSONOf(`{"id": NotZero}`))
1308 // td.Cmp(t, gotValue, td.SuperJSONOf(`{"id": NotZero()}`))
1309 // td.Cmp(t, gotValue, td.SuperJSONOf(`{"id": $^NotZero}`))
1310 // td.Cmp(t, gotValue, td.SuperJSONOf(`{"id": $^NotZero()}`))
1311 // td.Cmp(t, gotValue, td.SuperJSONOf(`{"id": "$^NotZero"}`))
1312 // td.Cmp(t, gotValue, td.SuperJSONOf(`{"id": "$^NotZero()"}`))
1313 //
1314 // As for placeholders, there is no differences between $^NotZero and
1315 // "$^NotZero".
1316 //
1317 // Tip: when an [io.Reader] is expected to contain JSON data, it
1318 // cannot be tested directly, but using the [Smuggle] operator simply
1319 // solves the problem:
1320 //
1321 // var body io.Reader
1322 // // …
1323 // td.Cmp(t, body, td.Smuggle(json.RawMessage{}, td.SuperJSONOf(`{"foo":1}`)))
1324 // // or equally
1325 // td.Cmp(t, body, td.Smuggle(json.RawMessage(nil), td.SuperJSONOf(`{"foo":1}`)))
1326 //
1327 // [Smuggle] reads from body into an [encoding/json.RawMessage] then
1328 // this buffer is unmarshaled by SuperJSONOf operator before the comparison.
1329 //
1330 // TypeBehind method returns the map[string]any type.
1331 //
1332 // See also [JSON], [JSONPointer] and [SubJSONOf].
1333 func SuperJSONOf(expectedJSON any, params ...any) TestDeep {
1334 m := &tdMapJSON{
1335 tdMap: tdMap{
1336 tdExpectedType: tdExpectedType{
1337 base: newBase(3),
1338 expectedType: reflect.TypeOf((map[string]any)(nil)),
1339 },
1340 kind: superMap,
1341 },
1342 }
1343
1344 v, err := newJSONUnmarshaler(m.GetLocation()).unmarshal(expectedJSON, params)
1345 if err != nil {
1346 m.err = err
1347 return m
1348 }
1349
1350 _, ok := v.(map[string]any)
1351 if !ok {
1352 m.err = ctxerr.OpBad("SuperJSONOf", "SuperJSONOf() only accepts JSON objects {…}")
1353 return m
1354 }
1355
1356 m.expected = reflect.ValueOf(v)
1357
1358 m.populateExpectedEntries(nil, m.expected)
1359 return m
1360 }
1361
1362 func (m *tdMapJSON) Match(ctx ctxerr.Context, got reflect.Value) *ctxerr.Error {
1363 if m.err != nil {
1364 return ctx.CollectError(m.err)
1365 }
1366
1367 err := gotViaJSON(ctx, &got, m.options)
1368 if err != nil {
1369 return ctx.CollectError(err)
1370 }
1371
1372 // nil case
1373 if !got.IsValid() {
1374 if ctx.BooleanError {
1375 return ctxerr.BooleanError
1376 }
1377 return ctx.CollectError(&ctxerr.Error{
1378 Message: "values differ",
1379 Got: types.RawString("null"),
1380 Expected: types.RawString("non-null"),
1381 })
1382 }
1383
1384 ctx.BeLax = true
1385
1386 return m.match(ctx, got)
1387 }
1388
1389 func (m *tdMapJSON) String() string {
1390 if m.err != nil {
1391 return m.stringError()
1392 }
1393
1394 return jsonStringify(m.GetLocation().Func, m.expected)
1395 }
1396
1397 func (m *tdMapJSON) HandleInvalid() bool {
1398 return true
1399 }