-
Notifications
You must be signed in to change notification settings - Fork 689
/
entity_accessors_test.go
69 lines (62 loc) · 1.63 KB
/
entity_accessors_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
package restful
import (
"bytes"
"fmt"
"io"
"net/http"
"net/http/httptest"
"reflect"
"testing"
)
type keyvalue struct {
readCalled bool
writeCalled bool
}
func (kv *keyvalue) Read(req *Request, v interface{}) error {
//t := reflect.TypeOf(v)
//rv := reflect.ValueOf(v)
kv.readCalled = true
return nil
}
func (kv *keyvalue) Write(resp *Response, status int, v interface{}) error {
t := reflect.TypeOf(v)
rv := reflect.ValueOf(v)
for ix := 0; ix < t.NumField(); ix++ {
sf := t.Field(ix)
io.WriteString(resp, sf.Name)
io.WriteString(resp, "=")
io.WriteString(resp, fmt.Sprintf("%v\n", rv.Field(ix).Interface()))
}
kv.writeCalled = true
return nil
}
// go test -v -test.run TestKeyValueEncoding ...restful
func TestKeyValueEncoding(t *testing.T) {
type Book struct {
Title string
Author string
PublishedYear int
}
kv := new(keyvalue)
RegisterEntityAccessor("application/kv", kv)
b := Book{"Singing for Dummies", "john doe", 2015}
// Write
httpWriter := httptest.NewRecorder()
// Accept Produces
resp := Response{ResponseWriter: httpWriter, requestAccept: "application/kv,*/*;q=0.8", routeProduces: []string{"application/kv"}, prettyPrint: true}
resp.WriteEntity(b)
t.Log(string(httpWriter.Body.Bytes()))
if !kv.writeCalled {
t.Error("Write never called")
}
// Read
bodyReader := bytes.NewReader(httpWriter.Body.Bytes())
httpRequest, _ := http.NewRequest("GET", "/test", bodyReader)
httpRequest.Header.Set("Content-Type", "application/kv; charset=UTF-8")
request := NewRequest(httpRequest)
var bb Book
request.ReadEntity(&bb)
if !kv.readCalled {
t.Error("Read never called")
}
}