-
Notifications
You must be signed in to change notification settings - Fork 3
/
server_test.go
82 lines (72 loc) · 1.8 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
78
79
80
81
82
package nasa
import (
"html/template"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
type httpTestList struct {
method string
path string
code int
contains string
}
func TestHandleIndex(t *testing.T) {
testList := []httpTestList{
{"GET", "/", http.StatusOK, "#explanation"},
{"GET", "/abcd", http.StatusNotFound, ""},
}
var err error
tmpl, err = template.New("tmpl").Parse(tmplHTML)
if err != nil {
t.Fatal(err)
}
for _, v := range testList {
req, err := http.NewRequest(v.method, v.path, nil)
if err != nil {
t.Fatal(err)
}
rr := httptest.NewRecorder()
handler := http.HandlerFunc(handleIndex)
handler.ServeHTTP(rr, req)
if rr.Code != v.code {
t.Errorf("handleIndex returned wrong status got %d, want %d", rr.Code, v.code)
}
if !strings.Contains(rr.Body.String(), v.contains) {
t.Errorf("handleIndex returned body missing wanted text: %s", v.contains)
}
}
}
func TestRandomHandler(t *testing.T) {
testList := []httpTestList{
{"GET", "/abcd", http.StatusNotFound, ""},
{"GET", "/random-apod/abcd", http.StatusNotFound, ""},
{"GET", "/random-apod/", http.StatusOK, "#explanation"},
}
var err error
tmpl, err = template.New("tmpl").Parse(tmplHTML)
if err != nil {
t.Fatal(err)
}
for _, v := range testList {
req, err := http.NewRequest(v.method, v.path, nil)
if err != nil {
t.Fatal(err)
}
rr := httptest.NewRecorder()
handler := &randomHandler{
lastUpdate: time.Now().Add(-10 * time.Hour),
cachedApod: &Image{},
tmpl: tmpl,
}
handler.ServeHTTP(rr, req)
if rr.Code != v.code {
t.Errorf("randomHandler returned wrong status got %d, want %d", rr.Code, v.code)
}
if !strings.Contains(rr.Body.String(), v.contains) {
t.Errorf("randomHandler missing expected text in returned body: %s", v.contains)
}
}
}