1 // Copyright 2020 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.
13 "golang.org/x/tools/internal/jsonrpc2"
16 var wireIDTestData = []struct {
30 id: jsonrpc2.NewIntID(43),
31 encoded: []byte(`43`),
36 id: jsonrpc2.NewStringID("life"),
37 encoded: []byte(`"life"`),
43 func TestIDFormat(t *testing.T) {
44 for _, test := range wireIDTestData {
45 t.Run(test.name, func(t *testing.T) {
46 if got := fmt.Sprint(test.id); got != test.plain {
47 t.Errorf("got %s expected %s", got, test.plain)
49 if got := fmt.Sprintf("%q", test.id); got != test.quoted {
50 t.Errorf("got %s want %s", got, test.quoted)
56 func TestIDEncode(t *testing.T) {
57 for _, test := range wireIDTestData {
58 t.Run(test.name, func(t *testing.T) {
59 data, err := json.Marshal(&test.id)
63 checkJSON(t, data, test.encoded)
68 func TestIDDecode(t *testing.T) {
69 for _, test := range wireIDTestData {
70 t.Run(test.name, func(t *testing.T) {
72 if err := json.Unmarshal(test.encoded, &got); err != nil {
76 t.Errorf("got nil want %s", test.id)
77 } else if *got != test.id {
78 t.Errorf("got %s want %s", got, test.id)
84 func TestErrorEncode(t *testing.T) {
85 b, err := json.Marshal(jsonrpc2.NewError(0, ""))
89 checkJSON(t, b, []byte(`{
95 func TestErrorResponse(t *testing.T) {
96 // originally reported in #39719, this checks that result is not present if
97 // it is an error response
98 r, _ := jsonrpc2.NewResponse(jsonrpc2.NewIntID(3), nil, fmt.Errorf("computing fix edits"))
99 data, err := json.Marshal(r)
103 checkJSON(t, data, []byte(`{
107 "message":"computing fix edits"
113 func checkJSON(t *testing.T, got, want []byte) {
114 // compare the compact form, to allow for formatting differences
116 if err := json.Compact(g, []byte(got)); err != nil {
120 if err := json.Compact(w, []byte(want)); err != nil {
123 if g.String() != w.String() {
124 t.Fatalf("Got:\n%s\nWant:\n%s", g, w)