-
Notifications
You must be signed in to change notification settings - Fork 0
/
crypto_currency_service_test.go
430 lines (338 loc) · 14.5 KB
/
crypto_currency_service_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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
package main
import (
"fmt"
"encoding/json"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
"github.com/DATA-DOG/go-sqlmock"
"github.com/gorilla/mux"
"github.com/stretchr/testify/assert"
)
func TestGetAllCryptoCurrencies(t *testing.T) {
// Create a new mock database and expected result
db, mock, err := sqlmock.New()
assert.NoError(t, err)
defer db.Close()
cryptoService := NewCryptoCurrencyService(db)
rows := sqlmock.NewRows([]string{"id", "name", "up_vote", "down_vote", "total_votes"}).
AddRow(1, "Bitcoin", 100, 20, 120).
AddRow(2, "Ethereum", 80, 10, 90)
mock.ExpectQuery("SELECT id, name, up_vote, down_vote, \\(up_vote \\+ down_vote\\) as total_votes FROM crypto_vote").
WillReturnRows(rows)
// Create a new request and recorder for testing the handler
req, err := http.NewRequest("GET", "/v1/cryptovote", nil)
assert.NoError(t, err)
rr := httptest.NewRecorder()
// Set up the router and call the handler
r := mux.NewRouter()
r.HandleFunc("/v1/cryptovote", cryptoService.GetAllCryptoCurrencies).Methods("GET")
r.ServeHTTP(rr, req)
// Check the response status code
assert.Equal(t, http.StatusOK, rr.Code)
// Parse the response body into a slice of CryptoCurrency
var cryptoCurrencies []CryptoCurrency
err = json.Unmarshal(rr.Body.Bytes(), &cryptoCurrencies)
assert.NoError(t, err)
// Check the response content
expectedCryptoCurrencies := []CryptoCurrency{
{ID: 1, Name: "Bitcoin", UpVote: 100, DownVote: 20, TotalVotes: 120},
{ID: 2, Name: "Ethereum", UpVote: 80, DownVote: 10, TotalVotes: 90},
}
assert.Equal(t, expectedCryptoCurrencies, cryptoCurrencies)
// Check that all the expected SQL queries were executed
assert.NoError(t, mock.ExpectationsWereMet())
}
func TestGetCryptoCurrencyByID(t *testing.T) {
// Create a new mock database and expected result
db, mock, err := sqlmock.New()
assert.NoError(t, err)
defer db.Close()
cryptoService := NewCryptoCurrencyService(db)
cryptoID := 1
expectedCrypto := CryptoCurrency{
ID: cryptoID,
Name: "Bitcoin",
UpVote: 100,
DownVote: 20,
TotalVotes: 120,
}
// Set the expectations for the first QueryRow call (count query)
rowsCount := sqlmock.NewRows([]string{"count"}).AddRow(1)
mock.ExpectQuery("SELECT COUNT\\(\\*\\) FROM crypto_vote WHERE id = ?").
WithArgs(cryptoID).
WillReturnRows(rowsCount)
// Set the expectations for the second QueryRow call (get cryptocurrency query)
rowsCrypto := sqlmock.NewRows([]string{"id", "name", "up_vote", "down_vote", "total_votes"}).
AddRow(expectedCrypto.ID, expectedCrypto.Name, expectedCrypto.UpVote, expectedCrypto.DownVote, expectedCrypto.TotalVotes)
mock.ExpectQuery("SELECT id, name, up_vote, down_vote, \\(up_vote \\+ down_vote\\) as total_votes FROM crypto_vote WHERE id=?").
WithArgs(cryptoID).
WillReturnRows(rowsCrypto)
// Create a new request and recorder for testing the handler
req, err := http.NewRequest("GET", "/v1/cryptovote/"+strconv.Itoa(cryptoID), nil)
assert.NoError(t, err)
rr := httptest.NewRecorder()
// Set up the router and call the handler
r := mux.NewRouter()
r.HandleFunc("/v1/cryptovote/{id:[0-9]+}", cryptoService.GetCryptoCurrencyByID).Methods("GET")
r.ServeHTTP(rr, req)
// Check the response status code
assert.Equal(t, http.StatusOK, rr.Code)
// Parse the response body into a CryptoCurrency object
var actualCrypto CryptoCurrency
err = json.Unmarshal(rr.Body.Bytes(), &actualCrypto)
assert.NoError(t, err)
// Check the response content
assert.Equal(t, expectedCrypto, actualCrypto)
// Check that all the expected SQL queries were executed
assert.NoError(t, mock.ExpectationsWereMet())
}
func TestCreateCryptoCurrency(t *testing.T) {
// Create a new mock database and expected result
db, mock, err := sqlmock.New()
assert.NoError(t, err)
defer db.Close()
cryptoService := NewCryptoCurrencyService(db)
// Mock the database query to check if the cryptocurrency name already exists
rows := sqlmock.NewRows([]string{"count"}).AddRow(0)
mock.ExpectQuery("SELECT COUNT\\(\\*\\) FROM crypto_vote WHERE name = ?").
WithArgs("Bitcoin").
WillReturnRows(rows)
// Mock the database insert to create a new cryptocurrency
result := sqlmock.NewResult(1, 1) // Last insert ID: 1, Rows affected: 1
mock.ExpectExec("INSERT INTO crypto_vote \\(name\\) VALUES \\(\\?\\)").
WithArgs("Bitcoin").
WillReturnResult(result)
// Create a new request and recorder for testing the handler
jsonData := `{"name": "Bitcoin"}`
req, err := http.NewRequest("POST", "/v1/cryptovote", strings.NewReader(jsonData))
assert.NoError(t, err)
rr := httptest.NewRecorder()
// Set up the router and call the handler
r := mux.NewRouter()
r.HandleFunc("/v1/cryptovote", cryptoService.CreateCryptoCurrency).Methods("POST")
r.ServeHTTP(rr, req)
// Check the response status code
assert.Equal(t, http.StatusCreated, rr.Code)
// Parse the response body into a CryptoCurrency object
var createdCrypto CryptoCurrency
err = json.Unmarshal(rr.Body.Bytes(), &createdCrypto)
assert.NoError(t, err)
// Check the response content
expectedCrypto := CryptoCurrency{
ID: 1, // Last insert ID
Name: "Bitcoin",
UpVote: 0, // Default value for a new cryptocurrency
DownVote: 0, // Default value for a new cryptocurrency
TotalVotes: 0, // Default value for a new cryptocurrency
}
assert.Equal(t, expectedCrypto, createdCrypto)
// Check that all the expected SQL queries were executed
assert.NoError(t, mock.ExpectationsWereMet())
}
func TestVoteCryptoCurrency(t *testing.T) {
// Common setup for both upvote and downvote tests
db, mock, err := sqlmock.New()
assert.NoError(t, err)
defer db.Close()
cryptoService := NewCryptoCurrencyService(db)
cryptoID := 1
// Set the expectations for the first QueryRow call (count query)
rowsCount := sqlmock.NewRows([]string{"count"}).AddRow(1)
mock.ExpectQuery("SELECT COUNT\\(\\*\\) FROM crypto_vote WHERE id = ?").
WithArgs(cryptoID).
WillReturnRows(rowsCount)
// Set the expectations for the second Exec call (update votes query)
result := sqlmock.NewResult(1, 1) // Rows affected: 1
mock.ExpectExec("UPDATE crypto_vote SET .* WHERE id = ?").
WithArgs(cryptoID).
WillReturnResult(result)
// Set the expectations for the third QueryRow call (get updated cryptocurrency query)
rowsCrypto := sqlmock.NewRows([]string{"id", "name", "up_vote", "down_vote", "total_votes"}).
AddRow(1, "Bitcoin", 100, 21, 121)
mock.ExpectQuery("SELECT id, name, up_vote, down_vote, \\(up_vote \\+ down_vote\\) as total_votes FROM crypto_vote WHERE id=?").
WithArgs(cryptoID).
WillReturnRows(rowsCrypto)
t.Run("UpVote", func(t *testing.T) {
// Create a new request and recorder for upvote testing
req, err := http.NewRequest("PUT", "/v1/cryptovote/"+strconv.Itoa(cryptoID)+"/upvote", nil)
assert.NoError(t, err)
rr := httptest.NewRecorder()
// Set up the router and call the handler for upvote
r := mux.NewRouter()
r.HandleFunc("/v1/cryptovote/{id:[0-9]+}/upvote", cryptoService.UpVoteCryptoCurrency).Methods("PUT")
r.ServeHTTP(rr, req)
// Check the response status code
assert.Equal(t, http.StatusOK, rr.Code)
// Parse the response body into a CryptoCurrency object
var updatedCrypto CryptoCurrency
err = json.Unmarshal(rr.Body.Bytes(), &updatedCrypto)
assert.NoError(t, err)
// Check the response content for upvote
expectedCrypto := CryptoCurrency{
ID: 1,
Name: "Bitcoin",
UpVote: 100,
DownVote: 21,
TotalVotes: 121,
}
assert.Equal(t, expectedCrypto, updatedCrypto)
// Check that all the expected SQL queries were executed for upvote
assert.NoError(t, mock.ExpectationsWereMet())
})
t.Run("DownVote", func(t *testing.T) {
// Set the expectations for the first QueryRow call (count query for downvote)
rowsCountDownVote := sqlmock.NewRows([]string{"count"}).AddRow(1)
mock.ExpectQuery("SELECT COUNT\\(\\*\\) FROM crypto_vote WHERE id = ?").
WithArgs(cryptoID).
WillReturnRows(rowsCountDownVote)
// Set the expectations for the second Exec call (update votes query for downvote)
resultDownVote := sqlmock.NewResult(1, 1) // Rows affected: 1
mock.ExpectExec("UPDATE crypto_vote SET .* WHERE id = ?").
WithArgs(cryptoID).
WillReturnResult(resultDownVote)
// Set the expectations for the third QueryRow call (get updated cryptocurrency query for downvote)
rowsCryptoDownVote := sqlmock.NewRows([]string{"id", "name", "up_vote", "down_vote", "total_votes"}).
AddRow(1, "Bitcoin", 100, 21, 121) // Corrected values for downvote
mock.ExpectQuery("SELECT id, name, up_vote, down_vote, \\(up_vote \\+ down_vote\\) as total_votes FROM crypto_vote WHERE id=?").
WithArgs(cryptoID).
WillReturnRows(rowsCryptoDownVote)
// Create a new request and recorder for downvote testing
req, err := http.NewRequest("PUT", "/v1/cryptovote/"+strconv.Itoa(cryptoID)+"/downvote", nil)
assert.NoError(t, err)
rr := httptest.NewRecorder()
// Set up the router and call the handler for downvote
r := mux.NewRouter()
r.HandleFunc("/v1/cryptovote/{id:[0-9]+}/downvote", cryptoService.DownVoteCryptoCurrency).Methods("PUT")
r.ServeHTTP(rr, req)
// Check the response status code
assert.Equal(t, http.StatusOK, rr.Code)
// Parse the response body into a CryptoCurrency object
var updatedCrypto CryptoCurrency
err = json.Unmarshal(rr.Body.Bytes(), &updatedCrypto)
assert.NoError(t, err)
// Check the response content for downvote
expectedCryptoDownVote := CryptoCurrency{
ID: 1,
Name: "Bitcoin",
UpVote: 100,
DownVote: 21,
TotalVotes: 121,
}
assert.Equal(t, expectedCryptoDownVote, updatedCrypto)
// Check that all the expected SQL queries were executed for downvote
assert.NoError(t, mock.ExpectationsWereMet())
})
}
func TestDeleteCryptoCurrency(t *testing.T) {
t.Run("DeleteExistingCrypto", func(t *testing.T) {
// Create a new mock database and expected result
db, mock, err := sqlmock.New()
assert.NoError(t, err)
defer db.Close()
cryptoService := NewCryptoCurrencyService(db)
cryptoID := 1
// Set the expectations for the first QueryRow call (count query)
rowsCount := sqlmock.NewRows([]string{"count"}).AddRow(1)
mock.ExpectQuery("SELECT COUNT\\(\\*\\) FROM crypto_vote WHERE id = ?").
WithArgs(cryptoID).
WillReturnRows(rowsCount)
// Set the expectations for the Exec call (delete cryptocurrency query)
result := sqlmock.NewResult(1, 1) // Rows affected: 1
mock.ExpectExec("DELETE FROM crypto_vote WHERE id = ?").
WithArgs(cryptoID).
WillReturnResult(result)
// Create a new request and recorder for testing the handler
req, err := http.NewRequest("DELETE", "/v1/cryptovote/"+strconv.Itoa(cryptoID), nil)
assert.NoError(t, err)
rr := httptest.NewRecorder()
// Set up the router and call the handler
r := mux.NewRouter()
r.HandleFunc("/v1/cryptovote/{id:[0-9]+}", cryptoService.DeleteCryptoCurrency).Methods("DELETE")
r.ServeHTTP(rr, req)
// Check the response status code
assert.Equal(t, http.StatusNoContent, rr.Code)
// Check that all the expected SQL queries were executed
assert.NoError(t, mock.ExpectationsWereMet())
})
t.Run("DeleteNonExistingCrypto", func(t *testing.T) {
// Create a new mock database and expected result
db, mock, err := sqlmock.New()
assert.NoError(t, err)
defer db.Close()
cryptoService := NewCryptoCurrencyService(db)
cryptoID := 1
// Set the expectations for the first QueryRow call (count query for non-existing cryptocurrency)
rowsCount := sqlmock.NewRows([]string{"count"}).AddRow(0)
mock.ExpectQuery("SELECT COUNT\\(\\*\\) FROM crypto_vote WHERE id = ?").
WithArgs(cryptoID).
WillReturnRows(rowsCount)
// Create a new request and recorder for testing the handler
req, err := http.NewRequest("DELETE", "/v1/cryptovote/"+strconv.Itoa(cryptoID), nil)
assert.NoError(t, err)
rr := httptest.NewRecorder()
// Set up the router and call the handler
r := mux.NewRouter()
r.HandleFunc("/v1/cryptovote/{id:[0-9]+}", cryptoService.DeleteCryptoCurrency).Methods("DELETE")
r.ServeHTTP(rr, req)
// Check the response status code
assert.Equal(t, http.StatusNotFound, rr.Code)
// Check that all the expected SQL queries were executed
assert.NoError(t, mock.ExpectationsWereMet())
})
t.Run("DatabaseErrorOnCountQuery", func(t *testing.T) {
// Create a new mock database and simulate an error during the count query
db, mock, err := sqlmock.New()
assert.NoError(t, err)
defer db.Close()
cryptoService := NewCryptoCurrencyService(db)
cryptoID := 1
// Set the expectations for the first QueryRow call (count query)
mock.ExpectQuery("SELECT COUNT\\(\\*\\) FROM crypto_vote WHERE id = ?").
WithArgs(cryptoID).
WillReturnError(fmt.Errorf("database error"))
// Create a new request and recorder for testing the handler
req, err := http.NewRequest("DELETE", "/v1/cryptovote/"+strconv.Itoa(cryptoID), nil)
assert.NoError(t, err)
rr := httptest.NewRecorder()
// Set up the router and call the handler
r := mux.NewRouter()
r.HandleFunc("/v1/cryptovote/{id:[0-9]+}", cryptoService.DeleteCryptoCurrency).Methods("DELETE")
r.ServeHTTP(rr, req)
// Check the response status code
assert.Equal(t, http.StatusInternalServerError, rr.Code)
// Check that all the expected SQL queries were executed
assert.NoError(t, mock.ExpectationsWereMet())
})
t.Run("DatabaseErrorOnDeleteQuery", func(t *testing.T) {
// Create a new mock database and simulate an error during the delete query
db, mock, err := sqlmock.New()
assert.NoError(t, err)
defer db.Close()
cryptoService := NewCryptoCurrencyService(db)
cryptoID := 1
// Set the expectations for the first QueryRow call (count query)
rowsCount := sqlmock.NewRows([]string{"count"}).AddRow(1)
mock.ExpectQuery("SELECT COUNT\\(\\*\\) FROM crypto_vote WHERE id = ?").
WithArgs(cryptoID).
WillReturnRows(rowsCount)
// Set the expectations for the Exec call (delete cryptocurrency query with error)
mock.ExpectExec("DELETE FROM crypto_vote WHERE id = ?").
WithArgs(cryptoID).
WillReturnError(fmt.Errorf("database error"))
// Create a new request and recorder for testing the handler
req, err := http.NewRequest("DELETE", "/v1/cryptovote/"+strconv.Itoa(cryptoID), nil)
assert.NoError(t, err)
rr := httptest.NewRecorder()
// Set up the router and call the handler
r := mux.NewRouter()
r.HandleFunc("/v1/cryptovote/{id:[0-9]+}", cryptoService.DeleteCryptoCurrency).Methods("DELETE")
r.ServeHTTP(rr, req)
// Check the response status code
assert.Equal(t, http.StatusInternalServerError, rr.Code)
// Check that all the expected SQL queries were executed
assert.NoError(t, mock.ExpectationsWereMet())
})
}