-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson_test.go
89 lines (82 loc) · 2.37 KB
/
json_test.go
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package nidhi_test
import (
"testing"
"github.com/akshayjshah/attest"
jsoniter "github.com/json-iterator/go"
"github.com/srikrsna/nidhi"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/testing/protocmp"
"google.golang.org/protobuf/types/known/anypb"
)
type jsonStdLib jsoniterReadWriter
type jsoniterReadWriter struct {
Id string `json:"id,omitempty"`
}
func (v *jsoniterReadWriter) WriteJSON(w *jsoniter.Stream) {
if v == nil {
w.WriteEmptyObject()
return
}
w.WriteObjectStart()
if v.Id != "" {
w.WriteObjectField("name")
w.WriteString(v.Id)
}
w.WriteObjectEnd()
}
func (v *jsoniterReadWriter) ReadJSON(r *jsoniter.Iterator) {
for field := r.ReadObject(); field != ""; field = r.ReadObject() {
switch field {
case "name":
v.Id = r.ReadString()
default:
r.Skip()
}
}
}
func TestGetJson(t *testing.T) {
t.Parallel()
t.Run("metadata", func(t *testing.T) {
t.Parallel()
md := nidhi.Metadata{"part": &metadataPart{Value: "some"}, "second": &metadataPart{}}
w, err := nidhi.GetJson(md)
attest.Ok(t, err)
attest.True(t, string(w.Buffer()) == `{"part":{"value":"some"},"second":{}}` || string(w.Buffer()) == `{"second":{},"part":{"value":"some"}}`)
emd := nidhi.Metadata{"part": &metadataPart{}, "second": &metadataPart{}}
attest.Ok(t, nidhi.UnmarshalJson(w.Buffer(), emd))
attest.Equal(t, emd, md)
})
t.Run("jsoniter", func(t *testing.T) {
t.Parallel()
rw := &jsoniterReadWriter{Id: "some"}
w, err := nidhi.GetJson(rw)
attest.Ok(t, err)
attest.Equal(t, string(w.Buffer()), `{"name":"some"}`)
var grw jsoniterReadWriter
attest.Ok(t, nidhi.UnmarshalJson(w.Buffer(), &grw))
attest.Equal(t, &grw, rw)
})
t.Run("proto", func(t *testing.T) {
t.Parallel()
pt, err := anypb.New(&anypb.Any{})
attest.Ok(t, err)
w, err := nidhi.GetJson(pt)
attest.Ok(t, err)
var pany anypb.Any
protojson.Unmarshal(w.Buffer(), &pany)
attest.Equal(t, &pany, pt, attest.Cmp(protocmp.Transform()))
var gpt anypb.Any
attest.Ok(t, nidhi.UnmarshalJson(w.Buffer(), &gpt))
attest.Equal(t, &gpt, pt, attest.Cmp(protocmp.Transform()))
})
t.Run("stdlib", func(t *testing.T) {
t.Parallel()
rw := &jsonStdLib{Id: "some"}
w, err := nidhi.GetJson(rw)
attest.Ok(t, err)
attest.Equal(t, string(w.Buffer()), `{"id":"some"}`)
var grw jsonStdLib
attest.Ok(t, nidhi.UnmarshalJson(w.Buffer(), &grw))
attest.Equal(t, &grw, rw)
})
}