1
0
mirror of https://github.com/golang/go synced 2024-11-05 14:36:11 -07:00
go/internal/jsonrpc2/wire_test.go
Ian Cottrell 7504fd2219 internal/lsp: fix broken lsp logs
ID's are now by value not pointer, which caused it to not use the Format
method, resulting in broken id strings
The id maps need to be crossover (set and get go to different maps for a given direction of message)

Change-Id: Ide2b63ec1b009ae3587ee10e8bce018732ea342c
Reviewed-on: https://go-review.googlesource.com/c/tools/+/229244
Run-TryBot: Ian Cottrell <iancottrell@google.com>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Peter Weinberger <pjw@google.com>
2020-04-21 17:00:05 +00:00

98 lines
2.0 KiB
Go

// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package jsonrpc2_test
import (
"bytes"
"encoding/json"
"fmt"
"testing"
"golang.org/x/tools/internal/jsonrpc2"
)
var wireIDTestData = []struct {
name string
id jsonrpc2.ID
encoded []byte
plain string
quoted string
}{
{
name: `empty`,
encoded: []byte(`0`),
plain: `0`,
quoted: `#0`,
}, {
name: `number`,
id: jsonrpc2.NewIntID(43),
encoded: []byte(`43`),
plain: `43`,
quoted: `#43`,
}, {
name: `string`,
id: jsonrpc2.NewStringID("life"),
encoded: []byte(`"life"`),
plain: `life`,
quoted: `"life"`,
},
}
func TestIDFormat(t *testing.T) {
for _, test := range wireIDTestData {
t.Run(test.name, func(t *testing.T) {
if got := fmt.Sprint(test.id); got != test.plain {
t.Errorf("got %s expected %s", got, test.plain)
}
if got := fmt.Sprintf("%q", test.id); got != test.quoted {
t.Errorf("got %s want %s", got, test.quoted)
}
})
}
}
func TestIDEncode(t *testing.T) {
for _, test := range wireIDTestData {
t.Run(test.name, func(t *testing.T) {
data, err := json.Marshal(&test.id)
if err != nil {
t.Fatal(err)
}
checkJSON(t, data, test.encoded)
})
}
}
func TestIDDecode(t *testing.T) {
for _, test := range wireIDTestData {
t.Run(test.name, func(t *testing.T) {
var got *jsonrpc2.ID
if err := json.Unmarshal(test.encoded, &got); err != nil {
t.Fatal(err)
}
if got == nil {
t.Errorf("got nil want %s", test.id)
} else if *got != test.id {
t.Errorf("got %s want %s", got, test.id)
}
})
}
}
func checkJSON(t *testing.T, got, want []byte) {
// compare the compact form, to allow for formatting differences
g := &bytes.Buffer{}
if err := json.Compact(g, []byte(got)); err != nil {
t.Fatal(err)
}
w := &bytes.Buffer{}
if err := json.Compact(w, []byte(want)); err != nil {
t.Fatal(err)
}
if g.String() != w.String() {
t.Fatalf("Got:\n%s\nWant:\n%s", g, w)
}
}