forked from fjl/go-couchdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
x_test.go
72 lines (63 loc) · 2.06 KB
/
x_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
// This file contains stuff that is used across all the tests.
package couchdb_test
import (
"bytes"
"io/ioutil"
"net/http"
"net/http/httptest"
"reflect"
"testing"
"github.com/cabify/go-couchdb"
)
// testClient is a very special couchdb.Client that also implements
// the http.RoundTripper interface. The tests can register HTTP
// handlers on the testClient. Any requests made through the client are
// dispatched to a matching handler. This allows us to test what the
// HTTP client in the couchdb package does without actually using the network.
//
// If no handler matches the requests method/path combination, the test
// fails with a descriptive error.
type testClient struct {
*couchdb.Client
t *testing.T
handlers map[string]http.Handler
}
func (s *testClient) Handle(pat string, f func(http.ResponseWriter, *http.Request)) {
s.handlers[pat] = http.HandlerFunc(f)
}
func (s *testClient) ClearHandlers() {
s.handlers = make(map[string]http.Handler)
}
func (s *testClient) RoundTrip(req *http.Request) (*http.Response, error) {
handler, ok := s.handlers[req.Method+" "+req.URL.Path]
if !ok {
s.t.Fatalf("unhandled request: %s %s", req.Method, req.URL.Path)
return nil, nil
}
recorder := httptest.NewRecorder()
recorder.Body = new(bytes.Buffer)
handler.ServeHTTP(recorder, req)
resp := &http.Response{
Proto: "HTTP/1.1",
ProtoMajor: 1,
ProtoMinor: 1,
StatusCode: recorder.Code,
Status: http.StatusText(recorder.Code),
Header: recorder.HeaderMap,
ContentLength: int64(recorder.Body.Len()),
Body: ioutil.NopCloser(recorder.Body),
Request: req,
}
return resp, nil
}
func newTestClient(t *testing.T) *testClient {
tc := &testClient{t: t, handlers: make(map[string]http.Handler)}
client := couchdb.NewClient(asURL("http://testClient:5984/"), &http.Client{Transport: tc}, nil)
tc.Client = client
return tc
}
func check(t *testing.T, field string, expected, actual interface{}) {
if !reflect.DeepEqual(expected, actual) {
t.Errorf("%s mismatch:\nwant %#v\ngot %#v", field, expected, actual)
}
}