-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi_test.go
59 lines (46 loc) · 1.25 KB
/
api_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
package main
import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
)
var a = App{}
func init() {
initialize(&a)
}
func TestServerHealth(t *testing.T) {
req, _ := http.NewRequest("GET", "/api/health", nil)
response := executeRequest(a, req)
checkResponseCode(t, http.StatusOK, response.Code)
if body := response.Body.String(); body != "" {
t.Errorf("Expected an empty body. Got %s", body)
}
}
type HelloWorldResponse struct {
Message string `json:"message"`
}
func TestServerDefaultPath(t *testing.T) {
req, _ := http.NewRequest("GET", "/", nil)
response := executeRequest(a, req)
checkResponseCode(t, http.StatusOK, response.Code)
var helloWorldResponse HelloWorldResponse
err := json.NewDecoder(response.Body).Decode(&helloWorldResponse)
if err != nil {
t.Errorf("Expected json, got decode error")
}
if helloWorldResponse.Message != "Hello, World!" {
t.Errorf("Expected Hello World. Got %s",
helloWorldResponse.Message)
}
}
func executeRequest(a App, req *http.Request) *httptest.ResponseRecorder {
rr := httptest.NewRecorder()
a.Router.ServeHTTP(rr, req)
return rr
}
func checkResponseCode(t *testing.T, expected, actual int) {
if expected != actual {
t.Errorf("Expected response code %d. Got %d\n", expected, actual)
}
}