-
Notifications
You must be signed in to change notification settings - Fork 0
/
server_test.go
87 lines (80 loc) · 1.95 KB
/
server_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
package main
import (
"github.com/bcessa/sample-twirp/proto"
"github.com/golang/protobuf/jsonpb"
"github.com/golang/protobuf/proto"
"github.com/golang/protobuf/ptypes"
"github.com/golang/protobuf/ptypes/struct"
"log"
"testing"
)
func toStruct(el proto.Message) (*structpb.Struct, error) {
m := jsonpb.Marshaler{}
js, _ := m.MarshalToString(el)
s := &structpb.Struct{}
err := jsonpb.UnmarshalString(js, s)
if err != nil {
return nil, err
}
return s, nil
}
func TestServer(t *testing.T) {
m := jsonpb.Marshaler{}
t.Run("Simple", func(t *testing.T) {
el := &sample.Item{
Name: "custom",
Time: ptypes.TimestampNow(),
}
pb, _ := proto.Marshal(el)
pj, _ := m.MarshalToString(el)
el2 := &sample.Item{}
proto.Unmarshal(pb, el2)
log.Printf("message name: %s", proto.MessageName(el))
log.Printf("encoded: %x", pb)
log.Printf("json: %s", pj)
log.Printf("decoded: %+v", el2)
})
t.Run("Extensions", func(t *testing.T) {
// Get extension
ab := &sample.AddressBook{}
ab.Contacts = append(ab.Contacts, &sample.Contact{
Name: "Rick",
LastName: "Sanchez",
Email: "[email protected]",
})
ab.Contacts = append(ab.Contacts, &sample.Contact{
Name: "Morty",
LastName: "Smith",
Email: "[email protected]",
})
s, _ := toStruct(ab)
ex := &sample.Extension{
Id: "sample.contacts",
Version: "0.1.0",
Data: s,
}
// Build record with extensions
el := &sample.Item{
Name: "record",
Time: ptypes.TimestampNow(),
Extensions: []*sample.Extension{ex},
}
pb, err := proto.Marshal(el)
if err != nil {
t.Error("failed to encode element", err)
}
pj, err := m.MarshalToString(el)
if err != nil {
t.Error("failed to encode as JSON", err)
}
el2 := &sample.Item{}
err = proto.Unmarshal(pb, el2)
if err != nil {
t.Error("failed to decode", err)
}
log.Printf("message name: %s", proto.MessageName(el))
log.Printf("encoded: %x", pb)
log.Printf("json: %s", pj)
log.Printf("decoded: %+v", el2)
})
}