forked from golang-bristol/beer-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlers_test.go
111 lines (86 loc) · 2.26 KB
/
handlers_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
110
111
package main
import (
"bytes"
"encoding/json"
"fmt"
"math/rand"
"net/http"
"net/http/httptest"
"testing"
model "github.com/golang-bristol/beer-model"
)
func TestGetBeers(t *testing.T) {
var cellarFromRequest []model.Beer
var cellarFromStorage []model.Beer
w := httptest.NewRecorder()
r, _ := http.NewRequest("GET", "/beers", nil)
router.ServeHTTP(w, r)
cellarFromStorage = db.FindBeers()
json.Unmarshal(w.Body.Bytes(), &cellarFromRequest)
if w.Code != http.StatusOK {
t.Errorf("Expected route GET /beers to be valid.")
t.FailNow()
}
if len(cellarFromRequest) != len(cellarFromStorage) {
t.Error("Expected number of beers from request to be the same as beers in the storage")
t.FailNow()
}
var mapCellar = make(map[model.Beer]int, len(cellarFromStorage))
for _, beer := range cellarFromStorage {
mapCellar[beer] = 1
}
for _, beerResp := range cellarFromRequest {
if _, ok := mapCellar[beerResp]; !ok {
t.Errorf("Expected all results to match existing records")
t.FailNow()
break
}
}
}
func TestAddBeer(t *testing.T) {
newBeer := model.Beer{
Name: "Testing beer",
Abv: 333,
Brewery: "Testing Beer Inc",
}
newBeerJSON, err := json.Marshal(newBeer)
if err != nil {
t.Fatal(err)
}
w := httptest.NewRecorder()
r, _ := http.NewRequest("POST", "/beers", bytes.NewBuffer(newBeerJSON))
router.ServeHTTP(w, r)
if w.Code != http.StatusOK {
t.Errorf("Expected route POST /beers to be valid.")
t.FailNow()
}
newBeerMissing := true
for _, b := range db.FindBeers() {
if b.Name == newBeer.Name &&
b.Abv == newBeer.Abv &&
b.Brewery == newBeer.Brewery {
newBeerMissing = false
}
}
if newBeerMissing {
t.Errorf("Expected to find new entry in storage`")
t.FailNow()
}
}
func TestGetBeer(t *testing.T) {
cellar := db.FindBeers()
choice := rand.Intn(len(cellar) - 1)
w := httptest.NewRecorder()
r, _ := http.NewRequest("GET", fmt.Sprintf("/beers/%d", cellar[choice].ID), nil)
router.ServeHTTP(w, r)
if w.Code != http.StatusOK {
t.Errorf("Expected route GET /beers/%d to be valid.", cellar[choice].ID)
t.FailNow()
}
var selectedBeer model.Beer
json.Unmarshal(w.Body.Bytes(), &selectedBeer)
if cellar[choice] != selectedBeer {
t.Errorf("Expected to match results with selected beer")
t.FailNow()
}
}