-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy pathserver_test.go
77 lines (71 loc) · 2.06 KB
/
server_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
package otohttp
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/matryer/is"
)
func TestServer(t *testing.T) {
is := is.New(t)
srv := NewServer()
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`{"greeting":"Hi Mat"}`))
})
srv.Register("Service", "Method", h)
w := httptest.NewRecorder()
r := httptest.NewRequest(http.MethodPost, "/oto/Service.Method", strings.NewReader(`{"name":"Mat"}`))
srv.ServeHTTP(w, r)
is.Equal(w.Code, http.StatusOK)
is.Equal(w.Body.String(), `{"greeting":"Hi Mat"}`)
}
func TestServerBasepath(t *testing.T) {
is := is.New(t)
srv := NewServer()
srv.Basepath = "/api/"
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`{"greeting":"Hi Mat"}`))
})
srv.Register("Service", "Method", h)
w := httptest.NewRecorder()
r := httptest.NewRequest(http.MethodPost, "/api/Service.Method", strings.NewReader(`{"name":"Mat"}`))
srv.ServeHTTP(w, r)
is.Equal(w.Code, http.StatusOK)
is.Equal(w.Body.String(), `{"greeting":"Hi Mat"}`)
}
func TestEncode(t *testing.T) {
is := is.New(t)
data := struct {
Greeting string `json:"greeting"`
}{
Greeting: "Hi there",
}
w := httptest.NewRecorder()
r := httptest.NewRequest(http.MethodPost, "/oto/Service.Method", strings.NewReader(`{"name":"Mat"}`))
err := Encode(w, r, http.StatusOK, data)
is.NoErr(err)
is.Equal(w.Code, http.StatusOK)
is.Equal(w.Body.String(), `{"greeting":"Hi there"}`)
is.Equal(w.HeaderMap.Get("Content-Type"), "application/json; charset=utf-8")
}
func TestDecode(t *testing.T) {
is := is.New(t)
type r struct {
Name string
}
j := `[
{"name": "Mat"},
{"name": "David"},
{"name": "Aaron"}
]`
req, err := http.NewRequest(http.MethodPost, "/service/method", strings.NewReader(j))
is.NoErr(err)
req.Header.Set("Content-Type", "application/json")
var requestObjects []r
err = Decode(req, &requestObjects)
is.NoErr(err)
is.Equal(len(requestObjects), 3)
is.Equal(requestObjects[0].Name, "Mat")
is.Equal(requestObjects[1].Name, "David")
is.Equal(requestObjects[2].Name, "Aaron")
}