-
Notifications
You must be signed in to change notification settings - Fork 1
/
api_person_test.go
109 lines (96 loc) · 2.38 KB
/
api_person_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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package main
import (
"bytes"
"io/ioutil"
"net/http"
"net/http/httptest"
"os"
"testing"
)
const testCreatePersonJson = `
{
"username": "lancelot",
"fullname": "Sir Lancelot"
}
`
const testUpdatePersonJson = `
{
"username": "lancelot",
"fullname": "Sir"
}
`
func TestPerson(t *testing.T) {
var w *httptest.ResponseRecorder
var r *http.Request
var p *bytes.Buffer
var err error
// create tempdir for fs based tests
tempdir, _ := ioutil.TempDir(os.TempDir(), "chickenlittle-tests-")
defer func() {
// remove tempdir
_ = os.RemoveAll(tempdir)
}()
dbfile := tempdir + "/db"
// open BoldDB handle
c.DB.Open(dbfile)
defer c.DB.Close()
// prepare the API router
router := apiRouter()
// Test CreatePerson: POST /people
w = httptest.NewRecorder()
p = bytes.NewBufferString(testCreatePersonJson)
r, err = http.NewRequest("POST", "http://localhost/people", p)
if err != nil {
t.Fatalf("Failed to create new HTTP Request: %s", err)
}
router.ServeHTTP(w, r)
// verify response
if w.Code != 200 {
t.Errorf("CreatePerson request failed")
}
// Test ListPeople: GET /people
w = httptest.NewRecorder()
r, err = http.NewRequest("GET", "http://localhost/people", nil)
if err != nil {
t.Fatalf("Failed to create new HTTP Request: %s", err)
}
router.ServeHTTP(w, r)
// verify response
if w.Code != 200 {
t.Errorf("ListPeople request failed")
}
// Test ShowPerson: GET /people/lancelot
w = httptest.NewRecorder()
r, err = http.NewRequest("GET", "http://localhost/people/lancelot", nil)
if err != nil {
t.Fatalf("Failed to create new HTTP Request: %s", err)
}
router.ServeHTTP(w, r)
// verify response
if w.Code != 200 {
t.Errorf("ShowPerson request failed")
}
// Test UpdatePerson: PUT /people/lancelog
w = httptest.NewRecorder()
p = bytes.NewBufferString(testUpdatePersonJson)
r, err = http.NewRequest("PUT", "http://localhost/people/lancelot", p)
if err != nil {
t.Fatalf("Failed to create new HTTP Request: %s", err)
}
router.ServeHTTP(w, r)
// verify response
if w.Code != 200 {
t.Errorf("UpdatePerson request failed")
}
// Test DeletePerson: DELETE /people/lancelot
w = httptest.NewRecorder()
r, err = http.NewRequest("DELETE", "http://localhost/people/lancelot", nil)
if err != nil {
t.Fatalf("Failed to create new HTTP Request: %s", err)
}
router.ServeHTTP(w, r)
// verify response
if w.Code != 200 {
t.Errorf("ShowPerson request failed")
}
}