-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrouter_test.go
More file actions
91 lines (70 loc) · 2.1 KB
/
router_test.go
File metadata and controls
91 lines (70 loc) · 2.1 KB
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
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
type FakeFileReader struct {}
func (reader FakeFileReader) ReadFile(filename string) ([]byte, error) {
return []byte("content"), nil
}
func TestGetRoute(t *testing.T) {
expected := "Hello World"
handler := func (w http.ResponseWriter, r RequestContext) {
w.WriteHeader(200)
w.Write([]byte(expected))
}
writer := httptest.NewRecorder()
request := httptest.NewRequest("GET", "/", nil)
router := CreateRouter(func(r *Router) {
r.reader = FakeFileReader{}
})
router.Get("/", handler)
router.ServeHTTP(writer, request)
if writer.Body.String() != expected {
t.Error("expected router not hit\n")
}
}
func TestPostRoute(t *testing.T) {
handler := func (w http.ResponseWriter, r RequestContext) {
w.WriteHeader(200)
r.Request.ParseForm()
name := r.Request.FormValue("name")
fmt.Printf("name: %s\n", name)
result := fmt.Sprintf("My name is %s", name)
w.Write([]byte(result))
}
writer := httptest.NewRecorder()
formData := "name=dmitri"
request := httptest.NewRequest("POST", "/", strings.NewReader(formData))
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
router := CreateRouter()
router.Post("/", handler)
router.ServeHTTP(writer, request)
expected := "My name is dmitri"
if writer.Code != 200 {
t.Error("expected 200 code\n")
}
if writer.Body.String() != expected {
t.Errorf("unexpected file body: %s", writer.Body.String())
}
}
func TestGetRouteWithParam(t *testing.T) {
expected := "Hello account 123"
handler := func (w http.ResponseWriter, r RequestContext) {
w.WriteHeader(200)
w.Write(fmt.Appendf(nil, "Hello account %s", r.Params["id"]))
}
writer := httptest.NewRecorder()
request := httptest.NewRequest("GET", "/accounts/123", nil)
router := CreateRouter(func(r *Router) {
r.reader = FakeFileReader{}
})
router.Get("/accounts/:id", handler)
router.ServeHTTP(writer, request)
if writer.Body.String() != expected {
t.Error("expected router not hit\n")
}
}