...
1 package proto
2
3 import (
4 "context"
5 "io/ioutil"
6 "net/http"
7 "net/http/httptest"
8 "testing"
9
10 "google.golang.org/protobuf/proto"
11 )
12
13 func TestEncodeProtoRequest(t *testing.T) {
14 cat := &Cat{Name: "Ziggy", Age: 13, Breed: "Lumpy"}
15
16 r := httptest.NewRequest(http.MethodGet, "/cat", nil)
17
18 err := EncodeProtoRequest(context.TODO(), r, cat)
19 if err != nil {
20 t.Errorf("expected no encoding errors but got: %s", err)
21 return
22 }
23
24 const xproto = "application/x-protobuf"
25 if typ := r.Header.Get("Content-Type"); typ != xproto {
26 t.Errorf("expected content type of %q, got %q", xproto, typ)
27 return
28 }
29
30 bod, err := ioutil.ReadAll(r.Body)
31 if err != nil {
32 t.Errorf("expected no read errors but got: %s", err)
33 return
34 }
35 defer r.Body.Close()
36
37 var got Cat
38 err = proto.Unmarshal(bod, &got)
39 if err != nil {
40 t.Errorf("expected no proto errors but got: %s", err)
41 return
42 }
43
44 if !proto.Equal(&got, cat) {
45 t.Errorf("expected cats to be equal but got:\n\n%#v\n\nwant:\n\n%#v", got, cat)
46 return
47 }
48 }
49
50 func TestEncodeProtoResponse(t *testing.T) {
51 cat := &Cat{Name: "Ziggy", Age: 13, Breed: "Lumpy"}
52
53 wr := httptest.NewRecorder()
54
55 err := EncodeProtoResponse(context.TODO(), wr, cat)
56 if err != nil {
57 t.Errorf("expected no encoding errors but got: %s", err)
58 return
59 }
60
61 w := wr.Result()
62
63 const xproto = "application/x-protobuf"
64 if typ := w.Header.Get("Content-Type"); typ != xproto {
65 t.Errorf("expected content type of %q, got %q", xproto, typ)
66 return
67 }
68
69 if w.StatusCode != http.StatusTeapot {
70 t.Errorf("expected status code of %d, got %d", http.StatusTeapot, w.StatusCode)
71 return
72 }
73
74 bod, err := ioutil.ReadAll(w.Body)
75 if err != nil {
76 t.Errorf("expected no read errors but got: %s", err)
77 return
78 }
79 defer w.Body.Close()
80
81 var got Cat
82 err = proto.Unmarshal(bod, &got)
83 if err != nil {
84 t.Errorf("expected no proto errors but got: %s", err)
85 return
86 }
87
88 if !proto.Equal(&got, cat) {
89 t.Errorf("expected cats to be equal but got:\n\n%#v\n\nwant:\n\n%#v", got, cat)
90 return
91 }
92 }
93
94 func (c *Cat) StatusCode() int {
95 return http.StatusTeapot
96 }
97
View as plain text