-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain_test.go
58 lines (50 loc) · 2.05 KB
/
main_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
package main
import (
"log"
"myblog/app"
"net/http"
"net/http/httptest"
"testing"
"github.com/gorilla/mux"
"github.com/stretchr/testify/assert"
)
func Router() *mux.Router {
router := mux.NewRouter()
router.HandleFunc("/", app.HomeHandler).Methods("GET")
router.HandleFunc("/posts/{slug}", app.PostHandler).Methods("GET")
router.HandleFunc("/about", app.AboutHandler).Methods("GET")
router.PathPrefix("/").HandlerFunc(app.CatchAllHandler)
return router
}
func TestHomeHandler(t *testing.T) {
request, _ := http.NewRequest("GET", "/", nil)
response := httptest.NewRecorder()
Router().ServeHTTP(response, request)
assert.Equal(t, 200, response.Code, "OK response is expected")
assert.Equal(t, "text/html; charset=utf-8", response.Result().Header["Content-Type"][0], "http content-type header response is expected")
}
func TestPostHandler(t *testing.T) {
request, _ := http.NewRequest("GET", "/posts/a-non-existant-post", nil)
response := httptest.NewRecorder()
Router().ServeHTTP(response, request)
assert.Equal(t, 404, response.Code, "404 response is expected")
log.Print(response.Result().Header)
// assert.Equal(t, "text/html; charset=utf-8", response.Result().Header["Content-Type"][0], "http content-type header response is expected")
request, _ = http.NewRequest("GET", "/posts/2019-02-26-website-in-a-binary", nil)
response = httptest.NewRecorder()
Router().ServeHTTP(response, request)
assert.Equal(t, 200, response.Code, "200 response is expected")
}
func TestAboutHandler(t *testing.T) {
request, _ := http.NewRequest("GET", "/about", nil)
response := httptest.NewRecorder()
Router().ServeHTTP(response, request)
assert.Equal(t, 200, response.Code, "OK response is expected")
assert.Equal(t, "text/html; charset=utf-8", response.Result().Header["Content-Type"][0], "http content-type header response is expected")
}
func TestCatchAllHandler(t *testing.T) {
request, _ := http.NewRequest("GET", "/foo", nil)
response := httptest.NewRecorder()
Router().ServeHTTP(response, request)
assert.Equal(t, 404, response.Code, "404 response is expected")
}