-
Notifications
You must be signed in to change notification settings - Fork 0
/
http_test.go
65 lines (56 loc) · 1.37 KB
/
http_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
package main
import (
"bytes"
"encoding/json"
"fmt"
"leaderboard/config"
"net/http"
"net/http/httptest"
"os"
"testing"
"github.com/spf13/viper"
)
func TestMain(m *testing.M) {
viper.Set(config.AESKey, "DEADBEEFDEADBEEF")
viper.Set(config.CsvName, fmt.Sprintf(".%ctestdata%ctestscores.csv", os.PathSeparator, os.PathSeparator))
config.SetViperDefaults()
loadScoreTree()
code := m.Run()
os.Exit(code)
}
func buildAndSendRequest(h http.HandlerFunc, method, path string, body interface{}) (*http.Response, error) {
bodyJSON, err := json.Marshal(body)
if err != nil {
return nil, err
}
req := httptest.NewRequest(method, path, bytes.NewReader(bodyJSON))
return sendRequest(h, req)
}
func sendRequest(h http.HandlerFunc, r *http.Request) (*http.Response, error) {
w := httptest.NewRecorder()
h(w, r)
return w.Result(), nil
}
//return an error if you didnt get a 200
func checkResponse(r *http.Response) error {
if r.StatusCode != 200 {
return fmt.Errorf("status: %s code: %d", r.Status, r.StatusCode)
}
return nil
}
func TestHandler_NoSecurity(t *testing.T) {
viper.Set(config.SecurityType, "none")
viper.Set(config.InputType, "json")
input := playerValues{
Score: "123",
Name: "bob",
}
res, err := buildAndSendRequest(scorePostHandler, "POST", "/", input)
if err != nil {
t.Error(err)
}
err = checkResponse(res)
if err != nil {
t.Error(err)
}
}