forked from sohamkamani/blog_example__go_web_app
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bird_handlers_test.go
92 lines (69 loc) · 1.82 KB
/
bird_handlers_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 main
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"strconv"
"testing"
)
func TestGetBirdsHandler(t *testing.T) {
birds = []Bird{
{"sparrow", "A small harmless bird"},
}
req, err := http.NewRequest("GET", "", nil)
if err != nil {
t.Fatal(err)
}
recorder := httptest.NewRecorder()
hf := http.HandlerFunc(getBirdHandler)
hf.ServeHTTP(recorder, req)
if status := recorder.Code; status != http.StatusOK {
t.Errorf("handler returned wrong status code: got %v want %v",
status, http.StatusOK)
}
expected := Bird{"sparrow", "A small harmless bird"}
b := []Bird{}
err = json.NewDecoder(recorder.Body).Decode(&b)
if err != nil {
t.Fatal(err)
}
actual := b[0]
if actual != expected {
t.Errorf("handler returned unexpected body: got %v want %v", actual, expected)
}
}
func TestCreateBirdsHandler(t *testing.T) {
birds = []Bird{
{"sparrow", "A small harmless bird"},
}
form := newCreateBirdForm()
req, err := http.NewRequest("POST", "", bytes.NewBufferString(form.Encode()))
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.Header.Add("Content-Length", strconv.Itoa(len(form.Encode())))
if err != nil {
t.Fatal(err)
}
recorder := httptest.NewRecorder()
hf := http.HandlerFunc(createBirdHandler)
hf.ServeHTTP(recorder, req)
if status := recorder.Code; status != http.StatusFound {
t.Errorf("handler returned wrong status code: got %v want %v",
status, http.StatusOK)
}
expected := Bird{"eagle", "A bird of prey"}
if err != nil {
t.Fatal(err)
}
actual := birds[1]
if actual != expected {
t.Errorf("handler returned unexpected body: got %v want %v", actual, expected)
}
}
func newCreateBirdForm() *url.Values {
form := url.Values{}
form.Set("species", "eagle")
form.Set("description", "A bird of prey")
return &form
}