/
proto_test.go
96 lines (77 loc) · 2.02 KB
/
proto_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
90
91
92
93
94
95
96
package proto
import (
"context"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"google.golang.org/protobuf/proto"
)
func TestEncodeProtoRequest(t *testing.T) {
cat := &Cat{Name: "Ziggy", Age: 13, Breed: "Lumpy"}
r := httptest.NewRequest(http.MethodGet, "/cat", nil)
err := EncodeProtoRequest(context.TODO(), r, cat)
if err != nil {
t.Errorf("expected no encoding errors but got: %s", err)
return
}
const xproto = "application/x-protobuf"
if typ := r.Header.Get("Content-Type"); typ != xproto {
t.Errorf("expected content type of %q, got %q", xproto, typ)
return
}
bod, err := ioutil.ReadAll(r.Body)
if err != nil {
t.Errorf("expected no read errors but got: %s", err)
return
}
defer r.Body.Close()
var got Cat
err = proto.Unmarshal(bod, &got)
if err != nil {
t.Errorf("expected no proto errors but got: %s", err)
return
}
if !proto.Equal(&got, cat) {
t.Errorf("expected cats to be equal but got:\n\n%#v\n\nwant:\n\n%#v", got, cat)
return
}
}
func TestEncodeProtoResponse(t *testing.T) {
cat := &Cat{Name: "Ziggy", Age: 13, Breed: "Lumpy"}
wr := httptest.NewRecorder()
err := EncodeProtoResponse(context.TODO(), wr, cat)
if err != nil {
t.Errorf("expected no encoding errors but got: %s", err)
return
}
w := wr.Result()
const xproto = "application/x-protobuf"
if typ := w.Header.Get("Content-Type"); typ != xproto {
t.Errorf("expected content type of %q, got %q", xproto, typ)
return
}
if w.StatusCode != http.StatusTeapot {
t.Errorf("expected status code of %d, got %d", http.StatusTeapot, w.StatusCode)
return
}
bod, err := ioutil.ReadAll(w.Body)
if err != nil {
t.Errorf("expected no read errors but got: %s", err)
return
}
defer w.Body.Close()
var got Cat
err = proto.Unmarshal(bod, &got)
if err != nil {
t.Errorf("expected no proto errors but got: %s", err)
return
}
if !proto.Equal(&got, cat) {
t.Errorf("expected cats to be equal but got:\n\n%#v\n\nwant:\n\n%#v", got, cat)
return
}
}
func (c *Cat) StatusCode() int {
return http.StatusTeapot
}