-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandlers_test.go
287 lines (228 loc) · 7.85 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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
package main
import (
"io/ioutil"
"net/http/httptest"
"net/url"
"os"
"strings"
"testing"
"github.com/globalsign/mgo/bson"
"github.com/julienschmidt/httprouter"
"github.com/mariaefi29/blog/config"
"github.com/mariaefi29/blog/models"
)
var ts *httptest.Server
var router *httprouter.Router
func TestMain(m *testing.M) {
setUp()
code := m.Run()
os.Exit(code)
}
func setUp() {
router = httprouter.New()
router.GET("/", index)
router.POST("/subscribe", subscribe)
router.GET("/posts/show/:id", show)
router.POST("/posts/show/:id", like)
router.POST("/posts/show/:id/comments", comment)
router.GET("/about", about)
router.GET("/category/:category", category)
router.GET("/contact", contact)
router.POST("/contact", sendMessage)
ts = httptest.NewServer(router)
defer ts.Close()
}
// TestIndex is the simplest test: check base (/) URL
func TestIndex(t *testing.T) {
t.Parallel()
writer := httptest.NewRecorder()
req := httptest.NewRequest("GET", ts.URL+"/", nil)
index(writer, req, nil)
if writer.Code != 200 {
t.Errorf("Response code is %v", writer.Code)
}
}
// TestShow: check (/posts/show/:id) URL
// takes out all ids of all posts from a database and checks if these requests are successful
func TestShow(t *testing.T) {
t.Parallel()
//retrieves all posts from a database
allPosts, err := models.AllPosts()
if err != nil {
t.Errorf("Database error is %v", err)
}
//constracts requests for each id and checks if they are successful
for i := range allPosts {
writer := httptest.NewRecorder()
req := httptest.NewRequest("GET", ts.URL+"/posts/show/"+allPosts[i].IDstr, nil)
ps1 := httprouter.Param{Key: "id", Value: allPosts[i].IDstr}
ps := []httprouter.Param{ps1}
show(writer, req, ps)
if writer.Code != 200 {
t.Errorf("Response code is %v", writer.Code)
}
}
}
// TestLike: check post request to (/posts/show/:id) URL
func TestLike(t *testing.T) {
t.Parallel()
updatedPost := models.Post{} //a modifed post after a post request
//retrieves all posts from a database
allPosts, err := models.AllPosts()
if err != nil {
t.Errorf("Database error is %v", err)
}
//contracts requests for each id and checks if they are successful
for i := range allPosts {
writer := httptest.NewRecorder()
req := httptest.NewRequest("POST", ts.URL+"/posts/show/"+allPosts[i].IDstr, nil)
ps1 := httprouter.Param{Key: "id", Value: allPosts[i].IDstr}
ps := []httprouter.Param{ps1}
like(writer, req, ps)
if writer.Code != 200 {
t.Errorf("Response code is %v", writer.Code)
}
if err := config.Posts.Find(bson.M{"_id": allPosts[i].ID}).One(&updatedPost); err != nil {
t.Errorf("Database error is %v", err)
}
//check if the number of likes was added by one after a post request
if updatedPost.Likes != allPosts[i].Likes+1 {
t.Errorf("The likes number supposed to be %d, but got %d", allPosts[i].Likes+1, updatedPost.Likes)
} else {
//put an initial post back in the database before the post request happen
if err := config.Posts.Update(bson.M{"_id": allPosts[i].ID}, &allPosts[i]); err != nil {
t.Errorf("Database error is %v", err)
}
}
}
}
// TestLike: check (/about) URL
func TestAbout(t *testing.T) {
t.Parallel()
writer := httptest.NewRecorder()
req := httptest.NewRequest("GET", ts.URL+"/about", nil)
about(writer, req, nil)
if writer.Code != 200 {
t.Errorf("Response code is %v", writer.Code)
}
}
// TestContact: check get request to (/contact) URL
func TestContact(t *testing.T) {
t.Parallel()
writer := httptest.NewRecorder()
req := httptest.NewRequest("GET", ts.URL+"/contact", nil)
about(writer, req, nil)
if writer.Code != 200 {
t.Errorf("Response code is %v", writer.Code)
}
}
// TestCategory: check get request to (/category/:category) URL
func TestCategory(t *testing.T) {
t.Parallel()
categories := make([]string, 0)
//retrieves all distinct categories from a database
if err := config.Posts.Find(nil).Distinct("categoryeng", &categories); err != nil {
t.Errorf("Database error is %v", err)
}
categoryMap := make(map[string]int) //contains category and the amount of posts in it
//contracts requests for each category and checks if there are working
for i, v := range categories {
categoryMap[v], _ = config.Posts.Find(bson.M{"categoryeng": v}).Count()
writer := httptest.NewRecorder()
req := httptest.NewRequest("GET", ts.URL+"/category/"+categories[i], nil)
ps1 := httprouter.Param{Key: "category", Value: categories[i]}
ps := []httprouter.Param{ps1}
category(writer, req, ps)
if writer.Code != 200 {
t.Errorf("Response code is %v", writer.Code)
}
resp := writer.Result()
body, _ := ioutil.ReadAll(resp.Body)
num := strings.Count(string(body), `<div class="post-snippet">`) //number of posts displayed in the categoy
//checks if the number of posts were displayed on the page correctly
if categoryMap[v] != num {
t.Errorf("The number of posts in the category %v, was expected %v", num, categoryMap[v])
}
}
}
func TestComment(t *testing.T) {
t.Parallel()
//retrieves all posts from a database
allPosts, err := models.AllPosts()
if err != nil {
t.Errorf("Database error is %v", err)
}
for i := range allPosts {
//contracts a test comment
form := url.Values{}
form.Add("message", "Test message")
form.Add("username", "Test user")
form.Add("email", "test@gmail.com")
form.Add("website", "test.com")
form.Add("xcode2", "776")
testComment := strings.NewReader(form.Encode())
writer := httptest.NewRecorder()
ps1 := httprouter.Param{Key: "id", Value: allPosts[i].IDstr}
ps := []httprouter.Param{ps1}
req := httptest.NewRequest("POST", ts.URL+"/posts/show/"+allPosts[i].IDstr+"/comments", testComment)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
comment(writer, req, ps)
if writer.Code != 200 {
t.Errorf("Response code is %v", writer.Code)
} else {
//put an initial post back in the database without a test comment
if err := config.Posts.Update(bson.M{"_id": allPosts[i].ID}, &allPosts[i]); err != nil {
t.Errorf("Database error is %v", err)
}
if err := config.Comments.Remove(bson.M{"email": "test@gmail.com"}); err != nil {
t.Errorf("cannot remove a test comment: database error is %v", err)
}
}
}
}
func TestSubscribe(t *testing.T) {
t.Parallel()
success := "Вы успешно подписаны на обновления блога!"
fail := "Вы уже были подписаны на обновления блога!"
writer := httptest.NewRecorder()
writer2 := httptest.NewRecorder()
result := models.Email{}
if err := config.Emails.Find(nil).One(&result); err != nil {
t.Errorf("Database error is %v", err)
}
form := url.Values{}
form.Add("email", "test@gmail.com")
form.Add("noshow", "454")
//subscribe by a test email
req := httptest.NewRequest("POST", ts.URL+"/subscribe", strings.NewReader(form.Encode()))
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
subscribe(writer, req, nil)
if writer.Code != 200 {
t.Errorf("Response code is %v", writer.Code)
}
resp := writer.Result()
body, _ := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
if string(body) != success {
t.Errorf("Expected a success message: %v, but got %v", success, string(body))
}
form2 := url.Values{}
form2.Add("email", result.EmailAddress)
form2.Add("noshow", "454")
//subscribe by an existed email
req2 := httptest.NewRequest("POST", ts.URL+"/subscribe", strings.NewReader(form2.Encode()))
req2.Header.Add("Content-Type", "application/x-www-form-urlencoded")
subscribe(writer2, req2, nil)
resp2 := writer2.Result()
body2, _ := ioutil.ReadAll(resp2.Body)
defer resp2.Body.Close()
if writer2.Code != 200 {
t.Errorf("Response code is %v", writer2.Code)
}
if string(body2) != fail {
t.Errorf("Expected a fail message: %v, but got %v", fail, string(body2))
}
if err := config.Emails.Remove(bson.M{"email": "test@gmail.com"}); err != nil {
t.Errorf("Database error is %v", err)
}
}