Debian Codegraph @

internal/jsonrpc2_v2/jsonrpc2_test.go

raw symbols SCIP
1 // Copyright 2018 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package jsonrpc2_test
6
7 import (
8 "context"
9 "encoding/json"
10 "fmt"
11 "path"
12 "reflect"
13 "testing"
14
15 jsonrpc2 "golang.org/x/tools/internal/jsonrpc2_v2"
16 )
17
18 var callTests = []invoker{
19 call{"no_args", nil, true},
20 call{"one_string", "fish", "got:fish"},
21 call{"one_number", 10, "got:10"},
22 call{"join", []string{"a", "b", "c"}, "a/b/c"},
23 sequence{"notify", []invoker{
24 notify{"set", 3},
25 notify{"add", 5},
26 call{"get", nil, 8},
27 }},
28 sequence{"preempt", []invoker{
29 async{"a", "wait", "a"},
30 notify{"unblock", "a"},
31 collect{"a", true, false},
32 }},
33 sequence{"basic cancel", []invoker{
34 async{"b", "wait", "b"},
35 cancel{"b"},
36 collect{"b", nil, true},
37 }},
38 sequence{"queue", []invoker{
39 async{"a", "wait", "a"},
40 notify{"set", 1},
41 notify{"add", 2},
42 notify{"add", 3},
43 notify{"add", 4},
44 call{"peek", nil, 0}, // accumulator will not have any adds yet
45 notify{"unblock", "a"},
46 collect{"a", true, false},
47 call{"get", nil, 10}, // accumulator now has all the adds
48 }},
49 sequence{"fork", []invoker{
50 async{"a", "fork", "a"},
51 notify{"set", 1},
52 notify{"add", 2},
53 notify{"add", 3},
54 notify{"add", 4},
55 call{"get", nil, 10}, // fork will not have blocked the adds
56 notify{"unblock", "a"},
57 collect{"a", true, false},
58 }},
59 sequence{"concurrent", []invoker{
60 async{"a", "fork", "a"},
61 notify{"unblock", "a"},
62 async{"b", "fork", "b"},
63 notify{"unblock", "b"},
64 collect{"a", true, false},
65 collect{"b", true, false},
66 }},
67 }
68
69 type binder struct {
70 framer jsonrpc2.Framer
71 runTest func(*handler)
72 }
73
74 type handler struct {
75 conn *jsonrpc2.Connection
76 accumulator int
77 waiters chan map[string]chan struct{}
78 calls map[string]*jsonrpc2.AsyncCall
79 }
80
81 type invoker interface {
82 Name() string
83 Invoke(t *testing.T, ctx context.Context, h *handler)
84 }
85
86 type notify struct {
87 method string
88 params any
89 }
90
91 type call struct {
92 method string
93 params any
94 expect any
95 }
96
97 type async struct {
98 name string
99 method string
100 params any
101 }
102
103 type collect struct {
104 name string
105 expect any
106 fails bool
107 }
108
109 type cancel struct {
110 name string
111 }
112
113 type sequence struct {
114 name string
115 tests []invoker
116 }
117
118 type echo call
119
120 type cancelParams struct{ ID int64 }
121
122 func TestConnectionRaw(t *testing.T) {
123 testConnection(t, jsonrpc2.RawFramer())
124 }
125
126 func TestConnectionHeader(t *testing.T) {
127 testConnection(t, jsonrpc2.HeaderFramer())
128 }
129
130 func testConnection(t *testing.T, framer jsonrpc2.Framer) {
131 ctx := context.Background()
132 listener, err := jsonrpc2.NetPipeListener(ctx)
133 if err != nil {
134 t.Fatal(err)
135 }
136 server := jsonrpc2.NewServer(ctx, listener, binder{framer, nil})
137 defer func() {
138 listener.Close()
139 server.Wait()
140 }()
141
142 for _, test := range callTests {
143 t.Run(test.Name(), func(t *testing.T) {
144 client, err := jsonrpc2.Dial(ctx,
145 listener.Dialer(), binder{framer, func(h *handler) {
146 defer h.conn.Close()
147 test.Invoke(t, ctx, h)
148 if call, ok := test.(*call); ok {
149 // also run all simple call tests in echo mode
150 (*echo)(call).Invoke(t, ctx, h)
151 }
152 }}, nil)
153 if err != nil {
154 t.Fatal(err)
155 }
156 client.Wait()
157 })
158 }
159 }
160
161 func (test notify) Name() string { return test.method }
162 func (test notify) Invoke(t *testing.T, ctx context.Context, h *handler) {
163 if err := h.conn.Notify(ctx, test.method, test.params); err != nil {
164 t.Fatalf("%v:Notify failed: %v", test.method, err)
165 }
166 }
167
168 func (test call) Name() string { return test.method }
169 func (test call) Invoke(t *testing.T, ctx context.Context, h *handler) {
170 results := newResults(test.expect)
171 if err := h.conn.Call(ctx, test.method, test.params).Await(ctx, results); err != nil {
172 t.Fatalf("%v:Call failed: %v", test.method, err)
173 }
174 verifyResults(t, test.method, results, test.expect)
175 }
176
177 func (test echo) Invoke(t *testing.T, ctx context.Context, h *handler) {
178 results := newResults(test.expect)
179 if err := h.conn.Call(ctx, "echo", []any{test.method, test.params}).Await(ctx, results); err != nil {
180 t.Fatalf("%v:Echo failed: %v", test.method, err)
181 }
182 verifyResults(t, test.method, results, test.expect)
183 }
184
185 func (test async) Name() string { return test.name }
186 func (test async) Invoke(t *testing.T, ctx context.Context, h *handler) {
187 h.calls[test.name] = h.conn.Call(ctx, test.method, test.params)
188 }
189
190 func (test collect) Name() string { return test.name }
191 func (test collect) Invoke(t *testing.T, ctx context.Context, h *handler) {
192 o := h.calls[test.name]
193 results := newResults(test.expect)
194 err := o.Await(ctx, results)
195 switch {
196 case test.fails && err == nil:
197 t.Fatalf("%v:Collect was supposed to fail", test.name)
198 case !test.fails && err != nil:
199 t.Fatalf("%v:Collect failed: %v", test.name, err)
200 }
201 verifyResults(t, test.name, results, test.expect)
202 }
203
204 func (test cancel) Name() string { return test.name }
205 func (test cancel) Invoke(t *testing.T, ctx context.Context, h *handler) {
206 o := h.calls[test.name]
207 if err := h.conn.Notify(ctx, "cancel", &cancelParams{o.ID().Raw().(int64)}); err != nil {
208 t.Fatalf("%v:Collect failed: %v", test.name, err)
209 }
210 }
211
212 func (test sequence) Name() string { return test.name }
213 func (test sequence) Invoke(t *testing.T, ctx context.Context, h *handler) {
214 for _, child := range test.tests {
215 child.Invoke(t, ctx, h)
216 }
217 }
218
219 // newResults makes a new empty copy of the expected type to put the results into
220 func newResults(expect any) any {
221 switch e := expect.(type) {
222 case []any:
223 var r []any
224 for _, v := range e {
225 r = append(r, reflect.New(reflect.TypeOf(v)).Interface())
226 }
227 return r
228 case nil:
229 return nil
230 default:
231 return reflect.New(reflect.TypeOf(expect)).Interface()
232 }
233 }
234
235 // verifyResults compares the results to the expected values
236 func verifyResults(t *testing.T, method string, results any, expect any) {
237 if expect == nil {
238 if results != nil {
239 t.Errorf("%v:Got results %+v where none expected", method, expect)
240 }
241 return
242 }
243 val := reflect.Indirect(reflect.ValueOf(results)).Interface()
244 if !reflect.DeepEqual(val, expect) {
245 t.Errorf("%v:Results are incorrect, got %+v expect %+v", method, val, expect)
246 }
247 }
248
249 func (b binder) Bind(ctx context.Context, conn *jsonrpc2.Connection) jsonrpc2.ConnectionOptions {
250 h := &handler{
251 conn: conn,
252 waiters: make(chan map[string]chan struct{}, 1),
253 calls: make(map[string]*jsonrpc2.AsyncCall),
254 }
255 h.waiters <- make(map[string]chan struct{})
256 if b.runTest != nil {
257 go b.runTest(h)
258 }
259 return jsonrpc2.ConnectionOptions{
260 Framer: b.framer,
261 Preempter: h,
262 Handler: h,
263 }
264 }
265
266 func (h *handler) waiter(name string) chan struct{} {
267 waiters := <-h.waiters
268 defer func() { h.waiters <- waiters }()
269 waiter, found := waiters[name]
270 if !found {
271 waiter = make(chan struct{})
272 waiters[name] = waiter
273 }
274 return waiter
275 }
276
277 func (h *handler) Preempt(ctx context.Context, req *jsonrpc2.Request) (any, error) {
278 switch req.Method {
279 case "unblock":
280 var name string
281 if err := json.Unmarshal(req.Params, &name); err != nil {
282 return nil, fmt.Errorf("%w: %s", jsonrpc2.ErrParse, err)
283 }
284 close(h.waiter(name))
285 return nil, nil
286 case "peek":
287 if len(req.Params) > 0 {
288 return nil, fmt.Errorf("%w: expected no params", jsonrpc2.ErrInvalidParams)
289 }
290 return h.accumulator, nil
291 case "cancel":
292 var params cancelParams
293 if err := json.Unmarshal(req.Params, &params); err != nil {
294 return nil, fmt.Errorf("%w: %s", jsonrpc2.ErrParse, err)
295 }
296 h.conn.Cancel(jsonrpc2.Int64ID(params.ID))
297 return nil, nil
298 default:
299 return nil, jsonrpc2.ErrNotHandled
300 }
301 }
302
303 func (h *handler) Handle(ctx context.Context, req *jsonrpc2.Request) (any, error) {
304 switch req.Method {
305 case "no_args":
306 if len(req.Params) > 0 {
307 return nil, fmt.Errorf("%w: expected no params", jsonrpc2.ErrInvalidParams)
308 }
309 return true, nil
310 case "one_string":
311 var v string
312 if err := json.Unmarshal(req.Params, &v); err != nil {
313 return nil, fmt.Errorf("%w: %s", jsonrpc2.ErrParse, err)
314 }
315 return "got:" + v, nil
316 case "one_number":
317 var v int
318 if err := json.Unmarshal(req.Params, &v); err != nil {
319 return nil, fmt.Errorf("%w: %s", jsonrpc2.ErrParse, err)
320 }
321 return fmt.Sprintf("got:%d", v), nil
322 case "set":
323 var v int
324 if err := json.Unmarshal(req.Params, &v); err != nil {
325 return nil, fmt.Errorf("%w: %s", jsonrpc2.ErrParse, err)
326 }
327 h.accumulator = v
328 return nil, nil
329 case "add":
330 var v int
331 if err := json.Unmarshal(req.Params, &v); err != nil {
332 return nil, fmt.Errorf("%w: %s", jsonrpc2.ErrParse, err)
333 }
334 h.accumulator += v
335 return nil, nil
336 case "get":
337 if len(req.Params) > 0 {
338 return nil, fmt.Errorf("%w: expected no params", jsonrpc2.ErrInvalidParams)
339 }
340 return h.accumulator, nil
341 case "join":
342 var v []string
343 if err := json.Unmarshal(req.Params, &v); err != nil {
344 return nil, fmt.Errorf("%w: %s", jsonrpc2.ErrParse, err)
345 }
346 return path.Join(v...), nil
347 case "echo":
348 var v []any
349 if err := json.Unmarshal(req.Params, &v); err != nil {
350 return nil, fmt.Errorf("%w: %s", jsonrpc2.ErrParse, err)
351 }
352 var result any
353 err := h.conn.Call(ctx, v[0].(string), v[1]).Await(ctx, &result)
354 return result, err
355 case "wait":
356 var name string
357 if err := json.Unmarshal(req.Params, &name); err != nil {
358 return nil, fmt.Errorf("%w: %s", jsonrpc2.ErrParse, err)
359 }
360 select {
361 case <-h.waiter(name):
362 return true, nil
363 case <-ctx.Done():
364 return nil, ctx.Err()
365 }
366 case "fork":
367 var name string
368 if err := json.Unmarshal(req.Params, &name); err != nil {
369 return nil, fmt.Errorf("%w: %s", jsonrpc2.ErrParse, err)
370 }
371 waitFor := h.waiter(name)
372 go func() {
373 select {
374 case <-waitFor:
375 h.conn.Respond(req.ID, true, nil)
376 case <-ctx.Done():
377 h.conn.Respond(req.ID, nil, ctx.Err())
378 }
379 }()
380 return nil, jsonrpc2.ErrAsyncResponse
381 default:
382 return nil, jsonrpc2.ErrNotHandled
383 }
384 }