File: proto_test.go

package info (click to toggle)
golang-github-go-kit-kit 0.13.0-8
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,784 kB
  • sloc: sh: 22; makefile: 11
file content (96 lines) | stat: -rw-r--r-- 2,067 bytes parent folder | download | duplicates (2)
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
}