Debian Codegraph @

td/td_json_pointer.go

raw
1 // Copyright (c) 2020-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 "fmt"
11 "reflect"
12 "strings"
13
14 "github.com/maxatome/go-testdeep/internal/ctxerr"
15 "github.com/maxatome/go-testdeep/internal/util"
16 )
17
18 type tdJSONPointer struct {
19 tdSmugglerBase
20 pointer string
21 options jsonv2Options
22 }
23
24 var _ TestDeep = &tdJSONPointer{}
25
26 // summary(JSONPointer): compares against JSON representation using a
27 // JSON pointer
28 // input(JSONPointer): nil,bool,str,int,float,array,slice,map,struct,ptr
29
30 // JSONPointer is a smuggler operator. It takes the JSON
31 // representation of data, gets the value corresponding to the JSON
32 // pointer ptr (as [RFC 6901] specifies it) and compares it to
33 // expectedValue.
34 //
35 // By default, [encoding/json] is used to marshal and unmarshal
36 // data. But if opts are passed using [encoding/json/v2.Options]
37 // values, then [encoding/json/v2] is used (go1.27 required). Note
38 // that multiple opts are automatically merged using
39 // [encoding/json/v2.JoinOptions] before use. So the following calls
40 // are equivalent:
41 //
42 // td.Cmp(t, got, td.JSONPointer("/a/b", 123))
43 // td.Cmp(t, got, td.JSONPointer("/a/b", 123, json.DefaultOptionsV1()))
44 //
45 // [Lax] mode is automatically enabled to simplify numeric tests.
46 //
47 // JSONPointer does its best to convert back the JSON pointed data to
48 // the type of expectedValue or to the type behind the
49 // expectedValue operator, if it is an operator. Allowing to do
50 // things like:
51 //
52 // type Item struct {
53 // Val int `json:"val"`
54 // Next *Item `json:"next"`
55 // }
56 // got := Item{Val: 1, Next: &Item{Val: 2, Next: &Item{Val: 3}}}
57 //
58 // td.Cmp(t, got, td.JSONPointer("/next/next", Item{Val: 3}))
59 // td.Cmp(t, got, td.JSONPointer("/next/next", &Item{Val: 3}))
60 // td.Cmp(t,
61 // got,
62 // td.JSONPointer("/next/next",
63 // td.Struct(Item{}, td.StructFields{"Val": td.Gte(3)})),
64 // )
65 //
66 // got := map[string]int64{"zzz": 42} // 42 is int64 here
67 // td.Cmp(t, got, td.JSONPointer("/zzz", 42))
68 // td.Cmp(t, got, td.JSONPointer("/zzz", td.Between(40, 45)))
69 //
70 // Of course, it does this conversion only if the expected type can be
71 // guessed. In the case the conversion cannot occur, data is compared
72 // as is, in its freshly unmarshaled JSON form (so as bool, float64,
73 // string, []any, map[string]any or simply nil).
74 //
75 // Note that as any [TestDeep] operator can be used as expectedValue,
76 // [JSON] operator works out of the box:
77 //
78 // got := json.RawMessage(`{"foo":{"bar": {"zip": true}}}`)
79 // td.Cmp(t, got, td.JSONPointer("/foo/bar", td.JSON(`{"zip": true}`)))
80 //
81 // It can be used with structs lacking json tags. In this case, fields
82 // names have to be used in JSON pointer:
83 //
84 // type Item struct {
85 // Val int
86 // Next *Item
87 // }
88 // got := Item{Val: 1, Next: &Item{Val: 2, Next: &Item{Val: 3}}}
89 //
90 // td.Cmp(t, got, td.JSONPointer("/Next/Next", Item{Val: 3}))
91 //
92 // Contrary to [Smuggle] operator and its fields-path feature, only
93 // public fields can be followed, as private ones are never (un)marshaled.
94 //
95 // There is no JSONHas nor JSONHasnt operators to only check a JSON
96 // pointer exists or not, but they can easily be emulated:
97 //
98 // JSONHas := func(pointer string) td.TestDeep {
99 // return td.JSONPointer(pointer, td.Ignore())
100 // }
101 //
102 // JSONHasnt := func(pointer string) td.TestDeep {
103 // return td.Not(td.JSONPointer(pointer, td.Ignore()))
104 // }
105 //
106 // TypeBehind method always returns nil as the expected type cannot be
107 // guessed from a JSON pointer.
108 //
109 // See also [JSON], [SubJSONOf], [SuperJSONOf], [Smuggle] and [Flatten].
110 //
111 // [RFC 6901]: https://tools.ietf.org/html/rfc6901
112 func JSONPointer(ptr string, expectedValue any, opts ...jsonv2Options) TestDeep {
113 p := tdJSONPointer{
114 tdSmugglerBase: newSmugglerBase(expectedValue),
115 pointer: ptr,
116 }
117 for _, o := range opts {
118 p.options = joinOptions(p.options, o)
119 }
120
121 if !strings.HasPrefix(ptr, "/") && ptr != "" {
122 p.err = ctxerr.OpBad("JSONPointer", "bad JSON pointer %q", ptr)
123 return &p
124 }
125
126 if !p.isTestDeeper {
127 p.expectedValue = reflect.ValueOf(expectedValue)
128 }
129 return &p
130 }
131
132 func (p *tdJSONPointer) Match(ctx ctxerr.Context, got reflect.Value) *ctxerr.Error {
133 if p.err != nil {
134 return ctx.CollectError(p.err)
135 }
136
137 vgot, eErr := jsonify(ctx, got, p.options)
138 if eErr != nil {
139 return ctx.CollectError(eErr)
140 }
141
142 vgot, err := util.JSONPointer(vgot, p.pointer)
143 if err != nil {
144 if ctx.BooleanError {
145 return ctxerr.BooleanError
146 }
147 pErr := err.(*util.JSONPointerError)
148 ctx = jsonPointerContext(ctx, pErr.Pointer)
149 return ctx.CollectError(&ctxerr.Error{
150 Message: "cannot retrieve value via JSON pointer",
151 Summary: ctxerr.NewSummary(pErr.Type),
152 })
153 }
154
155 // Here, vgot type is either a bool, float64, string,
156 // []any, a map[string]any or simply nil
157
158 ctx = jsonPointerContext(ctx, p.pointer)
159 ctx.BeLax = true
160
161 return p.jsonValueEqual(ctx, vgot, p.options)
162 }
163
164 func (p *tdJSONPointer) String() string {
165 if p.err != nil {
166 return p.stringError()
167 }
168
169 var expected string
170 switch {
171 case p.isTestDeeper:
172 expected = p.expectedValue.Interface().(TestDeep).String()
173 case p.expectedValue.IsValid():
174 expected = util.ToString(p.expectedValue.Interface())
175 default:
176 expected = "nil"
177 }
178 return fmt.Sprintf("JSONPointer(%s, %s)", p.pointer, expected)
179 }
180
181 func (p *tdJSONPointer) HandleInvalid() bool {
182 return true
183 }
184
185 func jsonPointerContext(ctx ctxerr.Context, pointer string) ctxerr.Context {
186 return ctx.AddCustomLevel(".JSONPointer<" + pointer + ">")
187 }