File: request_test.go

package info (click to toggle)
golang-github-sourcegraph-jsonrpc2 0.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 188 kB
  • sloc: makefile: 2
file content (64 lines) | stat: -rw-r--r-- 1,720 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package jsonrpc2_test

import (
	"bytes"
	"encoding/json"
	"reflect"
	"testing"

	"github.com/sourcegraph/jsonrpc2"
)

func TestRequest_MarshalJSON_jsonrpc(t *testing.T) {
	b, err := json.Marshal(&jsonrpc2.Request{})
	if err != nil {
		t.Fatal(err)
	}
	if want := `{"id":0,"jsonrpc":"2.0","method":""}`; string(b) != want {
		t.Errorf("got %q, want %q", b, want)
	}
}

func TestRequest_MarshalUnmarshalJSON(t *testing.T) {
	obj := json.RawMessage(`{"foo":"bar"}`)
	tests := []struct {
		data []byte
		want jsonrpc2.Request
	}{
		{
			data: []byte(`{"id":123,"jsonrpc":"2.0","method":"m","params":{"foo":"bar"}}`),
			want: jsonrpc2.Request{ID: jsonrpc2.ID{Num: 123}, Method: "m", Params: &obj},
		},
		{
			data: []byte(`{"id":123,"jsonrpc":"2.0","method":"m","params":null}`),
			want: jsonrpc2.Request{ID: jsonrpc2.ID{Num: 123}, Method: "m", Params: &jsonNull},
		},
		{
			data: []byte(`{"id":123,"jsonrpc":"2.0","method":"m"}`),
			want: jsonrpc2.Request{ID: jsonrpc2.ID{Num: 123}, Method: "m", Params: nil},
		},
		{
			data: []byte(`{"id":123,"jsonrpc":"2.0","method":"m","sessionId":"session"}`),
			want: jsonrpc2.Request{ID: jsonrpc2.ID{Num: 123}, Method: "m", Params: nil, ExtraFields: []jsonrpc2.RequestField{{Name: "sessionId", Value: "session"}}},
		},
	}
	for _, test := range tests {
		var got jsonrpc2.Request
		if err := json.Unmarshal(test.data, &got); err != nil {
			t.Error(err)
			continue
		}
		if !reflect.DeepEqual(got, test.want) {
			t.Errorf("%q: got %+v, want %+v", test.data, got, test.want)
			continue
		}
		data, err := json.Marshal(got)
		if err != nil {
			t.Error(err)
			continue
		}
		if !bytes.Equal(data, test.data) {
			t.Errorf("got JSON %q, want %q", data, test.data)
		}
	}
}