-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontext_test.go
92 lines (71 loc) · 1.74 KB
/
context_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
package bowtie
import (
"errors"
"net/http"
"testing"
)
type localContext struct {
Context
x string
}
func newLocalContext(r *http.Request, w http.ResponseWriter) *localContext {
return &localContext{
Context: NewContext(r, w),
x: "",
}
}
type mockWriter struct {
header http.Header
written []byte
status int
}
func newMockWriter() *mockWriter {
return &mockWriter{
header: http.Header{},
written: []byte{},
status: 0,
}
}
func (m *mockWriter) Header() http.Header {
return m.header
}
func (m *mockWriter) Write(p []byte) (int, error) {
m.written = append(m.written, p...)
return len(p), nil
}
func (m *mockWriter) WriteHeader(status int) {
m.status = status
}
func TestContext(t *testing.T) {
r := &http.Request{}
w := newMockWriter()
c := newLocalContext(r, w)
if c.Request().Request != r {
t.Error("Unexpectedly received the wrong request object")
}
if c.Response().Written() {
t.Error("Context unexpectedly reports that it has data")
}
n, err := c.Response().Write([]byte("abc"))
if err != nil {
t.Errorf("Unable to write to context: %s", err)
}
if n != 3 {
t.Errorf("Expected 3 bytes written, got %d instead", n)
}
w.written = []byte{}
n, err = c.Response().WriteJSON(map[string]interface{}{"test": 123})
if err != nil {
t.Errorf("Unable to write JSON to context: %s", err)
}
if n != 12 {
t.Errorf("Expected 12 bytes written, got %d instead", n)
}
if len(c.Response().Errors()) > 0 {
t.Errorf("Context unexpectedly has errors after writing JSON: %#v", c.Response().Errors)
}
c.Response().WriteJSONOrError(map[string]interface{}{"test": 123}, errors.New("Error"))
if len(c.Response().Errors()) == 0 {
t.Error("Context unexpectedly has no errors after writing JSON with error")
}
}