-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain_test.go
1130 lines (1077 loc) · 39.5 KB
/
main_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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bytes"
"encoding/json"
"log"
"net/http"
"net/http/httptest"
"os"
"strconv"
"testing"
"github.com/go-chi/chi/v5"
"github.com/okdv/wrench-turn/controllers"
"github.com/okdv/wrench-turn/db"
"github.com/okdv/wrench-turn/models"
)
var r *chi.Mux
var createdUser *models.User
var createdJob *models.Job
var createdTask *models.Task
var createdVehicle *models.Vehicle
var createdAlert *models.Alert
var createdLabel *models.Label
var req *http.Request
var w *httptest.ResponseRecorder
var testUsername string
var testPassword string
var jwtCookie *http.Cookie
func TestMain(m *testing.M) {
// check if db file exists
dbFilename := "test.db"
if _, err := os.Stat(dbFilename); os.IsNotExist(err) {
// if not, create it
log.Printf("database file %v does not exist, running db setup... ", dbFilename)
file, err := os.Create(dbFilename)
if err != nil {
log.Fatal("failed to create database file")
}
file.Close()
// read sql from schema
sqlBytes, err := os.ReadFile("schema.sql")
if err != nil {
log.Fatalf("failed to read schema file: %v", err)
}
err = db.CreateDatabase(dbFilename, string(sqlBytes))
if err != nil {
log.Fatalf("failed to create database: %v", err)
}
log.Print("Will attempt to connect to db now...")
}
// test db connection
DB, err := db.ConnectDatabase(dbFilename)
if err != nil {
panic("Unable to open database: " + err.Error())
}
log.Print("Successfully connected to database")
// declare router
r = chi.NewRouter()
// create controllers
userController := controllers.NewUserController()
authController := controllers.NewAuthController()
jobController := controllers.NewJobController()
taskController := controllers.NewTaskController()
vehicleController := controllers.NewVehicleController()
alertController := controllers.NewAlertController()
labelController := controllers.NewLabelController()
// create routes
// auth routes
r.Post("/auth", authController.Auth)
r.Get("/verify", authController.Verify(authController.TestVerify))
r.Get("/refresh", authController.Verify(authController.Refresh))
// user routes
r.Get("/users", userController.ListUsers)
r.Get("/users/{username}", userController.GetUserByUsername)
r.Post("/users/create", userController.CreateUser)
r.Delete("/users/{username}", authController.Verify(userController.DeleteUser))
r.Post("/users/edit", authController.Verify(userController.EditUser))
// job routes
r.Get("/jobs", jobController.ListJobs)
r.Get("/jobs/{id:[0-9]+}", jobController.GetJob)
r.Post("/jobs/{jobId:[0-9]+}/assignLabel/{labelId:[0-9]+}", authController.Verify(jobController.AssignJobLabel))
r.Post("/jobs/create", authController.Verify(jobController.CreateJob))
r.Post("/jobs/edit", authController.Verify(jobController.EditJob))
r.Delete("/jobs/{id:[0-9]+}", authController.Verify(jobController.DeleteJob))
// task routes
r.Get("/jobs/{jobId:[0-9]+}/tasks", taskController.ListTasks)
r.Get("/jobs/{jobId:[0-9]+}/tasks/{taskId:[0-9]+}", taskController.GetTask)
r.Patch("/jobs/{jobId:[0-9]+}/tasks/{taskId:[0-9]+}/complete", authController.Verify(taskController.MarkComplete))
r.Post("/jobs/{jobId:[0-9]+}/tasks/create", authController.Verify(taskController.CreateTask))
r.Post("/jobs/{jobId:[0-9]+}/tasks/edit", authController.Verify(taskController.EditTask))
r.Delete("/jobs/{jobId:[0-9]+}/tasks/{taskId:[0-9]+}", authController.Verify(taskController.DeleteTask))
r.Delete("/jobs/{jobId:[0-9]+}/tasks", authController.Verify(taskController.DeleteTask))
// vehicle routes
r.Get("/vehicles", vehicleController.ListVehicles)
r.Get("/vehicles/{id:[0-9]+}", vehicleController.GetVehicle)
r.Post("/vehicles/create", authController.Verify(vehicleController.CreateVehicle))
r.Post("/vehicles/edit", authController.Verify(vehicleController.EditVehicle))
r.Delete("/vehicles/{id:[0-9]+}", authController.Verify(vehicleController.DeleteVehicle))
// alert routes
r.Get("/alerts", authController.Verify(alertController.ListAlerts))
r.Get("/alerts/{id:[0-9]+}", authController.Verify(alertController.GetAlert))
r.Patch("/alerts/{id:[0-9]+}/read", authController.Verify(alertController.MarkRead))
r.Post("/alerts/create", authController.Verify(alertController.CreateAlert))
r.Post("/alerts/edit", authController.Verify(alertController.EditAlert))
r.Delete("/alerts/{id:[0-9]+}", authController.Verify(alertController.DeleteAlert))
// label routes
r.Get("/labels", labelController.ListLabels)
r.Get("/labels/{id:[0-9]+}", labelController.GetLabel)
r.Post("/labels/create", authController.Verify(labelController.CreateLabel))
r.Post("/labels/edit", authController.Verify(labelController.EditLabel))
r.Delete("/labels/{id:[0-9]+}", authController.Verify(labelController.DeleteLabel))
// run tests
exitCode := m.Run()
// Close the database connection explicitly
if DB != nil {
if err := DB.Close(); err != nil {
panic(err)
}
}
// Cleanup after all tests
if err := os.Remove(dbFilename); err != nil {
panic(err)
}
os.Exit(exitCode)
}
// TestCreateUser
// Tests creating a new user using default credentials and user controller
func TestCreateUser(t *testing.T) {
// setup user
testUsername = "wrench-turn_go_test_user"
testPassword = "Password123"
newUser := &models.NewUser{
Username: testUsername,
Password: &testPassword,
}
// convert to json
jsonData, err := json.Marshal(newUser)
if err != nil {
t.Errorf("Error encoding request body: %v", err)
}
// post user json to api
req = httptest.NewRequest("POST", "/users/create", bytes.NewReader(jsonData))
w = httptest.NewRecorder()
r.ServeHTTP(w, req)
// error if unexpected HTTP status
if w.Code != http.StatusCreated {
t.Errorf("Expted status code %d, got %d", http.StatusOK, w.Code)
}
// error if unable to decode response
if err := json.NewDecoder(w.Body).Decode(&createdUser); err != nil {
t.Errorf("Error decoding response body: %v", err)
}
log.Print("Successfully created user")
}
// TestListUsers
// Tests getting all users
func TestListUsers(t *testing.T) {
// get from api
req = httptest.NewRequest("GET", "/users", nil)
w = httptest.NewRecorder()
r.ServeHTTP(w, req)
// error if unexpected HTTP status
if w.Code != http.StatusOK {
t.Errorf("Expted status code %d, got %d", http.StatusOK, w.Code)
}
// error if unable to decode response
var users *[]models.User
if err := json.NewDecoder(w.Body).Decode(&users); err != nil {
t.Errorf("Error decoding response body: %v", err)
}
// error if no returned users
if users == nil || len(*users) == 0 {
t.Errorf("No users retreived, at least one (test user from TestCreateUser) should exist")
}
log.Print("Successfully retrieved users")
}
// TestAuth
// Tests auth with user created by TestCreateUser
func TestAuth(t *testing.T) {
creds := &models.Credentials{
Username: testUsername,
Password: testPassword,
}
jsonData, err := json.Marshal(creds)
if err != nil {
t.Errorf("Error encoding request body: %v", err)
}
// post auth credentials to api
req = httptest.NewRequest("POST", "/auth", bytes.NewReader(jsonData))
w = httptest.NewRecorder()
r.ServeHTTP(w, req)
// error if unable to decode response
if err := json.NewDecoder(w.Body).Decode(&jwtCookie); err != nil {
t.Errorf("Error decoding response body: %v", err)
}
// error if jwt is still empty
if jwtCookie == nil {
t.Errorf("JWT not present")
}
log.Print("Successfully logged in")
}
// TestVerify
// Tests verify endpoint
func TestVerify(t *testing.T) {
// test via api
req = httptest.NewRequest("GET", "/verify", nil)
req.Header.Add("Authorization", "Bearer "+jwtCookie.Value)
w = httptest.NewRecorder()
r.ServeHTTP(w, req)
// error if unexpected HTTP status
if w.Code != http.StatusOK {
t.Errorf("Expted status code %d, got %d", http.StatusOK, w.Code)
}
log.Print("Successfully verified with endpoint")
}
// TestVerify
// Tests verify endpoint
func TestRefresh(t *testing.T) {
// refresh via api (should not work since jwt doesnt expire within 24 hours)
req = httptest.NewRequest("GET", "/refresh", nil)
req.Header.Add("Authorization", "Bearer "+jwtCookie.Value)
w = httptest.NewRecorder()
r.ServeHTTP(w, req)
// error if unexpected HTTP status
if w.Code != http.StatusNoContent {
t.Errorf("Expted status code %d, got %d", http.StatusNoContent, w.Code)
}
log.Print("Successfully called refresh")
// force refresh via api
req = httptest.NewRequest("GET", "/refresh?force=true", nil)
req.Header.Add("Authorization", "Bearer "+jwtCookie.Value)
w = httptest.NewRecorder()
r.ServeHTTP(w, req)
// error if unexpected HTTP status
if w.Code != http.StatusOK {
t.Errorf("Expted status code %d, got %d", http.StatusNoContent, w.Code)
}
// error if unable to decode response
if err := json.NewDecoder(w.Body).Decode(&jwtCookie); err != nil {
t.Errorf("Error decoding response body: %v", err)
}
// error if jwt is still empty
if jwtCookie == nil {
t.Errorf("JWT not present")
}
log.Print("Successfully forced refresh")
}
// TestGetAndEditUser
// Tests getting and editing user created by TestCreateUser
func TestGetAndEditUser(t *testing.T) {
// get from api
req = httptest.NewRequest("GET", "/users/"+createdUser.Username, nil)
w = httptest.NewRecorder()
r.ServeHTTP(w, req)
// error if unexpected HTTP status
if w.Code != http.StatusOK {
t.Errorf("Expted status code %d, got %d", http.StatusOK, w.Code)
}
// error if unable to decode response
var fetchedUser *models.User
if err := json.NewDecoder(w.Body).Decode(&fetchedUser); err != nil {
t.Errorf("Error decoding response body: %v", err)
}
// error if returned user ID is not the same as created user ID
if fetchedUser.ID != createdUser.ID {
t.Errorf("Username %v fetched a different user ID, %d, than expected, %d", createdUser.Username, fetchedUser.ID, createdUser.ID)
}
log.Print("Successfully retrieved test user")
// change user description
testDescription := "Test Description"
fetchedUser.Description = &testDescription
// convert to json for editing
jsonData, err := json.Marshal(fetchedUser)
if err != nil {
t.Errorf("Error encoding request body: %v", err)
}
// edit via post req
req = httptest.NewRequest("POST", "/users/edit", bytes.NewReader(jsonData))
req.Header.Add("Authorization", "Bearer "+jwtCookie.Value)
w = httptest.NewRecorder()
r.ServeHTTP(w, req)
// error if unexpected HTTP status
if w.Code != http.StatusOK {
t.Errorf("Expted status code %d, got %d", http.StatusOK, w.Code)
}
// decode body from json or error
if err := json.NewDecoder(w.Body).Decode(&fetchedUser); err != nil {
t.Errorf("Error decoding response body: %v", err)
}
// compare dscriptions to confirm successful edit
if fetchedUser.Description != &testDescription {
t.Error("Description was not updated")
}
log.Print("Successfully edited user")
}
// TestCreateVehicle
// Tests createing a vehicle with user created by TestCreateUser
func TestCreateVehicle(t *testing.T) {
// setup new test vehicle
newVehicle := &models.NewVehicle{
Name: "wrench-turn go test vehicle",
}
// convert to json
jsonData, err := json.Marshal(newVehicle)
if err != nil {
t.Errorf("Error encoding request body: %v", err)
}
// create via api
req = httptest.NewRequest("POST", "/vehicles/create", bytes.NewReader(jsonData))
req.Header.Add("Authorization", "Bearer "+jwtCookie.Value)
req.Header.Add("Content-Type", "application/json")
w = httptest.NewRecorder()
r.ServeHTTP(w, req)
// error if unexpected HTTP status
if w.Code != http.StatusCreated {
t.Errorf("Expted status code %d, got %d", http.StatusOK, w.Code)
}
// error if unable to decode response
if err := json.NewDecoder(w.Body).Decode(&createdVehicle); err != nil {
t.Errorf("Error decoding response body: %v", err)
}
log.Print("Successfully created vehicle")
}
// TestListVehicles
// Tests getting all vehicles
func TestListVehicles(t *testing.T) {
// get from api
req = httptest.NewRequest("GET", "/vehicles", nil)
w = httptest.NewRecorder()
r.ServeHTTP(w, req)
// error if unexpected HTTP status
if w.Code != http.StatusOK {
t.Errorf("Expted status code %d, got %d", http.StatusOK, w.Code)
}
// error if unable to decode response
var vehicles *[]models.Vehicle
if err := json.NewDecoder(w.Body).Decode(&vehicles); err != nil {
t.Errorf("Error decoding response body: %v", err)
}
// error if no returned users
if vehicles == nil || len(*vehicles) == 0 {
t.Errorf("No vehicles retreived, at least one (test vehicles from TestCreateVehicle) should exist")
}
log.Print("Successfully retrieved vehicles")
}
// TestGetAndEditVehicle
// Tests getting and editing job created by TestCreateVehicle
func TestGetAndEditVehicle(t *testing.T) {
// get from api
req = httptest.NewRequest("GET", "/vehicles/"+strconv.FormatInt(createdVehicle.ID, 10), nil)
w = httptest.NewRecorder()
r.ServeHTTP(w, req)
// error if unexpected HTTP status
if w.Code != http.StatusOK {
t.Errorf("Expted status code %d, got %d", http.StatusOK, w.Code)
}
// error if unable to decode response
var fetchedVehicle *models.Vehicle
if err := json.NewDecoder(w.Body).Decode(&fetchedVehicle); err != nil {
t.Errorf("Error decoding response body: %v", err)
}
// error if returned vehicle ID is not the same as created vehicle ID
if fetchedVehicle.ID != createdVehicle.ID {
t.Errorf("Vehicle ID %d fetched a different vehicle, ID %d, than expected", createdVehicle.ID, fetchedVehicle.ID)
}
log.Print("Successfully retrieved test vehicle")
// change vehicle description
testDescription := "Test Description"
fetchedVehicle.Description = &testDescription
// convert to json
jsonData, err := json.Marshal(fetchedVehicle)
if err != nil {
t.Errorf("Error encoding request body: %v", err)
}
// edit via post req
req = httptest.NewRequest("POST", "/vehicles/edit", bytes.NewReader(jsonData))
req.Header.Add("Authorization", "Bearer "+jwtCookie.Value)
w = httptest.NewRecorder()
r.ServeHTTP(w, req)
// error if unexpected HTTP status
if w.Code != http.StatusOK {
t.Errorf("Expted status code %d, got %d", http.StatusOK, w.Code)
}
// decode body from json or error
if err := json.NewDecoder(w.Body).Decode(&fetchedVehicle); err != nil {
t.Errorf("Error decoding response body: %v", err)
}
// compare dscriptions to confirm successful edit
if fetchedVehicle.Description != &testDescription {
t.Error("Description was not updated")
}
log.Print("Successfully edited vehicle")
}
// TestCreateJob
// Tests createing a job with user created by TestCreateUser
func TestCreateJob(t *testing.T) {
// setuop new test job
newJob := &models.NewJob{
Name: "wrench-turn go test job",
Vehicle: &createdVehicle.ID,
}
// convert to json
jsonData, err := json.Marshal(newJob)
if err != nil {
t.Errorf("Error encoding request body: %v", err)
}
// create via api
req = httptest.NewRequest("POST", "/jobs/create", bytes.NewReader(jsonData))
req.Header.Add("Authorization", "Bearer "+jwtCookie.Value)
w = httptest.NewRecorder()
r.ServeHTTP(w, req)
// error if unexpected HTTP status
if w.Code != http.StatusCreated {
t.Errorf("Expted status code %d, got %d", http.StatusOK, w.Code)
}
// error if unable to decode response
if err := json.NewDecoder(w.Body).Decode(&createdJob); err != nil {
t.Errorf("Error decoding response body: %v", err)
}
log.Print("Successfully created job")
// create a second job, this one to be auto deleted on vehicle deletion
req = httptest.NewRequest("POST", "/jobs/create", bytes.NewReader(jsonData))
req.Header.Add("Authorization", "Bearer "+jwtCookie.Value)
w = httptest.NewRecorder()
r.ServeHTTP(w, req)
// error if unexpected HTTP status
if w.Code != http.StatusCreated {
t.Errorf("Expted status code %d, got %d", http.StatusOK, w.Code)
}
log.Print("Successfully created job")
}
// TestCreateLabel
// Tests createing a label with user created by TestCreateUser
func TestCreateLabel(t *testing.T) {
defaultColor := "ff0000"
// setuop new test label
newLabel := &models.NewLabel{
Name: "wrench-turn go test label",
Color: &defaultColor,
User: &createdUser.ID,
}
// convert to json
jsonData, err := json.Marshal(newLabel)
if err != nil {
t.Errorf("Error encoding request body: %v", err)
}
// create via api
req = httptest.NewRequest("POST", "/labels/create", bytes.NewReader(jsonData))
req.Header.Add("Authorization", "Bearer "+jwtCookie.Value)
w = httptest.NewRecorder()
r.ServeHTTP(w, req)
// error if unexpected HTTP status
if w.Code != http.StatusCreated {
t.Errorf("Expted status code %d, got %d", http.StatusOK, w.Code)
}
// error if unable to decode response
if err := json.NewDecoder(w.Body).Decode(&createdLabel); err != nil {
t.Errorf("Error decoding response body: %v", err)
}
log.Print("Successfully created label")
}
// TestAssignAndUnassignJobLabel
// Tests assigning and unassigning a label created by TestCreateLabel to job created by TestCreateJob
func TestAssignAndUnassignJobLabel(t *testing.T) {
// assign via api
req = httptest.NewRequest("POST", "/jobs/"+strconv.FormatInt(createdJob.ID, 10)+"/assignLabel/"+strconv.FormatInt(createdLabel.ID, 10), nil)
req.Header.Add("Authorization", "Bearer "+jwtCookie.Value)
w = httptest.NewRecorder()
r.ServeHTTP(w, req)
// error if unexpected HTTP status
if w.Code != http.StatusOK {
t.Errorf("Expted status code %d, got %d", http.StatusOK, w.Code)
}
log.Print("Successfully assigned label")
// will be unassigned on job delete
}
// TestGetJob
// Tests getting job
func TestGetJob(t *testing.T) {
// get from api
req = httptest.NewRequest("GET", "/jobs/"+strconv.FormatInt(createdJob.ID, 10), nil)
w = httptest.NewRecorder()
r.ServeHTTP(w, req)
// error if unexpected HTTP status
if w.Code != http.StatusOK {
t.Errorf("Expted status code %d, got %d", http.StatusOK, w.Code)
}
// error if unable to decode response
var job *models.Job
if err := json.NewDecoder(w.Body).Decode(&job); err != nil {
t.Errorf("Error decoding response body: %v", err)
}
// error if no returned users
if job == nil {
t.Errorf("No job retreived, at least one (test jobs from TestCreateJob) should exist")
}
log.Print("Successfully retrieved jobs")
}
// TestGetLabel
// Tests getting label
func TestGetLabel(t *testing.T) {
// get from api
req = httptest.NewRequest("GET", "/labels/"+strconv.FormatInt(createdLabel.ID, 10), nil)
w = httptest.NewRecorder()
r.ServeHTTP(w, req)
// error if unexpected HTTP status
if w.Code != http.StatusOK {
t.Errorf("Expted status code %d, got %d", http.StatusOK, w.Code)
}
// error if unable to decode response
var label *models.Label
if err := json.NewDecoder(w.Body).Decode(&label); err != nil {
t.Errorf("Error decoding response body: %v", err)
}
// error if no returned users
if label == nil {
t.Errorf("No label retreived, at least one (test labels from TestCreateLabel) should exist")
}
log.Print("Successfully retrieved labels")
}
// TestGetAndEditJob
// Tests getting and editing job created by TestCreateJob
func TestGetAndEditJob(t *testing.T) {
// get from api
req = httptest.NewRequest("GET", "/jobs/"+strconv.FormatInt(createdJob.ID, 10), nil)
w = httptest.NewRecorder()
r.ServeHTTP(w, req)
// error if unexpected HTTP status
if w.Code != http.StatusOK {
t.Errorf("Expted status code %d, got %d", http.StatusOK, w.Code)
}
// error if unable to decode response
var fetchedJob *models.Job
if err := json.NewDecoder(w.Body).Decode(&fetchedJob); err != nil {
t.Errorf("Error decoding response body: %v", err)
}
// error if returned job ID is not the same as created job ID
if fetchedJob.ID != createdJob.ID {
t.Errorf("Job ID %d fetched a different job, ID %d, than expected", createdJob.ID, fetchedJob.ID)
}
log.Print("Successfully retrieved test job")
// change job description
testDescription := "Test Description"
fetchedJob.Description = &testDescription
// convert to json
jsonData, err := json.Marshal(fetchedJob)
if err != nil {
t.Errorf("Error encoding request body: %v", err)
}
// edit via post req
req = httptest.NewRequest("POST", "/jobs/edit", bytes.NewReader(jsonData))
req.Header.Add("Authorization", "Bearer "+jwtCookie.Value)
w = httptest.NewRecorder()
r.ServeHTTP(w, req)
// error if unexpected HTTP status
if w.Code != http.StatusOK {
t.Errorf("Expted status code %d, got %d", http.StatusOK, w.Code)
}
// decode body from json or error
if err := json.NewDecoder(w.Body).Decode(&fetchedJob); err != nil {
t.Errorf("Error decoding response body: %v", err)
}
// compare dscriptions to confirm successful edit
if fetchedJob.Description != &testDescription {
t.Error("Description was not updated")
}
log.Print("Successfully edited job")
}
// TestGetAndEditLabel
// Tests getting and editing label created by TestCreateLabel
func TestGetAndEditLabel(t *testing.T) {
// get from api
req = httptest.NewRequest("GET", "/labels/"+strconv.FormatInt(createdLabel.ID, 10), nil)
w = httptest.NewRecorder()
r.ServeHTTP(w, req)
// error if unexpected HTTP status
if w.Code != http.StatusOK {
t.Errorf("Expted status code %d, got %d", http.StatusOK, w.Code)
}
// error if unable to decode response
var fetchedLabel *models.Label
if err := json.NewDecoder(w.Body).Decode(&fetchedLabel); err != nil {
t.Errorf("Error decoding response body: %v", err)
}
// error if returned label ID is not the same as created label ID
if fetchedLabel.ID != createdLabel.ID {
t.Errorf("Label ID %d fetched a different label, ID %d, than expected", createdLabel.ID, fetchedLabel.ID)
}
log.Print("Successfully retrieved test label")
// change label description
testColor := "0400ff"
fetchedLabel.Color = &testColor
// convert to json
jsonData, err := json.Marshal(fetchedLabel)
if err != nil {
t.Errorf("Error encoding request body: %v", err)
}
// edit via post req
req = httptest.NewRequest("POST", "/labels/edit", bytes.NewReader(jsonData))
req.Header.Add("Authorization", "Bearer "+jwtCookie.Value)
w = httptest.NewRecorder()
r.ServeHTTP(w, req)
// error if unexpected HTTP status
if w.Code != http.StatusOK {
t.Errorf("Expted status code %d, got %d", http.StatusOK, w.Code)
}
// decode body from json or error
if err := json.NewDecoder(w.Body).Decode(&fetchedLabel); err != nil {
t.Errorf("Error decoding response body: %v", err)
}
// compare dscriptions to confirm successful edit
if fetchedLabel.Color != &testColor {
t.Error("Color was not updated")
}
log.Print("Successfully edited label")
}
// TestCreateTask
// Test creating task on job created by TestCreateJob
func TestCreateTask(t *testing.T) {
// setuop new test job
newTask := &models.NewTask{
Name: "wrench-turn go test task",
}
// convert to json
jsonData, err := json.Marshal(newTask)
if err != nil {
t.Errorf("Error encoding request body: %v", err)
}
log.Println(createdJob.User)
log.Println(createdUser.ID)
// create via api
req = httptest.NewRequest("POST", "/jobs/"+strconv.FormatInt(createdJob.ID, 10)+"/tasks/create", bytes.NewReader(jsonData))
req.Header.Add("Authorization", "Bearer "+jwtCookie.Value)
w = httptest.NewRecorder()
r.ServeHTTP(w, req)
// error if unexpected HTTP status
if w.Code != http.StatusCreated {
t.Errorf("Expted status code %d, got %d", http.StatusCreated, w.Code)
}
// error if unable to decode response
if err := json.NewDecoder(w.Body).Decode(&createdTask); err != nil {
t.Errorf("Error decoding response body: %v", err)
}
// create second task to test deletion workflow when job is deleted
// create via api
req = httptest.NewRequest("POST", "/jobs/"+strconv.FormatInt(createdJob.ID, 10)+"/tasks/create", bytes.NewReader(jsonData))
req.Header.Add("Authorization", "Bearer "+jwtCookie.Value)
w = httptest.NewRecorder()
r.ServeHTTP(w, req)
// error if unexpected HTTP status
if w.Code != http.StatusCreated {
t.Errorf("Expted status code %d, got %d", http.StatusCreated, w.Code)
}
log.Print("Successfully created task")
}
// TestGetTask
// Tests getting all tasks for created job
func TestGetTask(t *testing.T) {
// get from api
req = httptest.NewRequest("GET", "/jobs/"+strconv.FormatInt(createdJob.ID, 10)+"/tasks/"+strconv.FormatInt(createdTask.ID, 10), nil)
w = httptest.NewRecorder()
r.ServeHTTP(w, req)
// error if unexpected HTTP status
if w.Code != http.StatusOK {
t.Errorf("Expted status code %d, got %d", http.StatusOK, w.Code)
}
// error if unable to decode response
var task *models.Job
if err := json.NewDecoder(w.Body).Decode(&task); err != nil {
t.Errorf("Error decoding response body: %v", err)
}
// error if no returned users
if task == nil {
t.Errorf("No task retreived, task (test task from TestCreateTask) should exist")
}
log.Print("Successfully retrieved tasks")
}
// TestGetAndMarkCompleteAndEditTask
// Tests getting and editing task created by TestCreateTask
func TestGetAndMarkCompleteAndEditTask(t *testing.T) {
// mark complete in api
req = httptest.NewRequest("PATCH", "/jobs/"+strconv.FormatInt(createdJob.ID, 10)+"/tasks/"+strconv.FormatInt(createdTask.ID, 10)+"/complete", nil)
req.Header.Add("Authorization", "Bearer "+jwtCookie.Value)
w = httptest.NewRecorder()
r.ServeHTTP(w, req)
// error if unexpected HTTP status
if w.Code != http.StatusOK {
t.Errorf("Expted status code %d, got %d", http.StatusOK, w.Code)
}
// get from api
req = httptest.NewRequest("GET", "/jobs/"+strconv.FormatInt(createdJob.ID, 10)+"/tasks/"+strconv.FormatInt(createdTask.ID, 10), nil)
w = httptest.NewRecorder()
r.ServeHTTP(w, req)
// error if unexpected HTTP status
if w.Code != http.StatusOK {
t.Errorf("Expted status code %d, got %d", http.StatusOK, w.Code)
}
// error if unable to decode response
var fetchedTask *models.Task
if err := json.NewDecoder(w.Body).Decode(&fetchedTask); err != nil {
t.Errorf("Error decoding response body: %v", err)
}
// error if returned taskID is not the same as created task ID
if fetchedTask.ID != createdTask.ID {
t.Errorf("Task ID %d fetched a different task, ID %d, than expected", createdTask.ID, fetchedTask.ID)
}
// error if task is not completed
if fetchedTask.Is_complete != 1 {
t.Error("Task should be completed, is still incomplete", http.StatusOK)
}
log.Print("Successfully retrieved test task")
// change job description
testDescription := "Test Description"
fetchedTask.Description = &testDescription
// convert to json
jsonData, err := json.Marshal(fetchedTask)
if err != nil {
t.Errorf("Error encoding request body: %v", err)
}
// edit via post req
req = httptest.NewRequest("POST", "/jobs/"+strconv.FormatInt(createdJob.ID, 10)+"/tasks/edit", bytes.NewReader(jsonData))
req.Header.Add("Authorization", "Bearer "+jwtCookie.Value)
w = httptest.NewRecorder()
r.ServeHTTP(w, req)
// error if unexpected HTTP status
if w.Code != http.StatusOK {
t.Errorf("Expted status code %d, got %d", http.StatusOK, w.Code)
}
// decode body from json or error
if err := json.NewDecoder(w.Body).Decode(&fetchedTask); err != nil {
t.Errorf("Error decoding response body: %v", err)
}
// compare dscriptions to confirm successful edit
if fetchedTask.Description != &testDescription {
t.Error("Description was not updated")
}
log.Print("Successfully edited task")
}
// TestCreateAlert
// Tests creating a alert with user created by TestCreateUser
func TestCreateAlert(t *testing.T) {
alertName := "wrench-turn go test alert"
// setuop new test alert
newAlert := &models.NewAlert{
Name: &alertName,
Type: "notification",
Vehicle: &createdVehicle.ID,
Job: &createdJob.ID,
Task: &createdTask.ID,
}
// convert to json
jsonData, err := json.Marshal(newAlert)
if err != nil {
t.Errorf("Error encoding request body: %v", err)
}
// create via api
req = httptest.NewRequest("POST", "/alerts/create", bytes.NewReader(jsonData))
req.Header.Add("Authorization", "Bearer "+jwtCookie.Value)
w = httptest.NewRecorder()
r.ServeHTTP(w, req)
// error if unexpected HTTP status
if w.Code != http.StatusCreated {
t.Errorf("Expted status code %d, got %d", http.StatusOK, w.Code)
}
// error if unable to decode response
if err := json.NewDecoder(w.Body).Decode(&createdAlert); err != nil {
t.Errorf("Error decoding response body: %v", err)
}
// create another alert to be deleted at job deletion
req = httptest.NewRequest("POST", "/alerts/create", bytes.NewReader(jsonData))
req.Header.Add("Authorization", "Bearer "+jwtCookie.Value)
w = httptest.NewRecorder()
r.ServeHTTP(w, req)
// error if unexpected HTTP status
if w.Code != http.StatusCreated {
t.Errorf("Expted status code %d, got %d", http.StatusOK, w.Code)
}
// create another alert to be deleted at vehicle deletion
// set job and task nil to ensure this alert is not deleted by other tests
newAlert.Job = nil
newAlert.Task = nil
req = httptest.NewRequest("POST", "/alerts/create", bytes.NewReader(jsonData))
req.Header.Add("Authorization", "Bearer "+jwtCookie.Value)
w = httptest.NewRecorder()
r.ServeHTTP(w, req)
// error if unexpected HTTP status
if w.Code != http.StatusCreated {
t.Errorf("Expted status code %d, got %d", http.StatusOK, w.Code)
}
log.Print("Successfully created alerts")
}
// TestGetAlert
// Tests getting alert
func TestGetAlert(t *testing.T) {
// get from api
req = httptest.NewRequest("GET", "/alerts/"+strconv.FormatInt(createdAlert.ID, 10), nil)
req.Header.Add("Authorization", "Bearer "+jwtCookie.Value)
w = httptest.NewRecorder()
r.ServeHTTP(w, req)
// error if unexpected HTTP status
if w.Code != http.StatusOK {
t.Errorf("Expted status code %d, got %d", http.StatusOK, w.Code)
}
// error if unable to decode response
var alert *models.Alert
if err := json.NewDecoder(w.Body).Decode(&alert); err != nil {
t.Errorf("Error decoding response body: %v", err)
}
// error if no returned alerts
if alert == nil {
t.Errorf("No alert retreived, at least one (test alerts from TestCreateAlert) should exist")
}
log.Print("Successfully retrieved alerts")
}
// TestGetAndMarkReadAndEditAlert
// Tests getting and editing alert created by TestCreateAlert
func TestGetAndMarkReadAndEditAlert(t *testing.T) {
// mark read in api
req = httptest.NewRequest("PATCH", "/alerts/"+strconv.FormatInt(createdAlert.ID, 10)+"/read", nil)
req.Header.Add("Authorization", "Bearer "+jwtCookie.Value)
w = httptest.NewRecorder()
r.ServeHTTP(w, req)
// error if unexpected HTTP status
if w.Code != http.StatusOK {
t.Errorf("Expted status code %d, got %d", http.StatusOK, w.Code)
}
// get from api
req = httptest.NewRequest("GET", "/alerts/"+strconv.FormatInt(createdAlert.ID, 10), nil)
req.Header.Add("Authorization", "Bearer "+jwtCookie.Value)
w = httptest.NewRecorder()
r.ServeHTTP(w, req)
// error if unexpected HTTP status
if w.Code != http.StatusOK {
t.Errorf("Expted status code %d, got %d", http.StatusOK, w.Code)
}
// error if unable to decode response
var fetchedAlert *models.Alert
if err := json.NewDecoder(w.Body).Decode(&fetchedAlert); err != nil {
t.Errorf("Error decoding response body: %v", err)
}
// error if returned taskID is not the same as created alert ID
if fetchedAlert.ID != createdAlert.ID {
t.Errorf("Alert ID %d fetched a different alert, ID %d, than expected", createdAlert.ID, fetchedAlert.ID)
}
// error if alert is not read
if *fetchedAlert.Is_read != 1 {
t.Error("Alert should be read, is still unread", http.StatusOK)
}
log.Print("Successfully retrieved test alert")
// change job description
testDescription := "Test Description"
fetchedAlert.Description = &testDescription
// convert to json
jsonData, err := json.Marshal(fetchedAlert)
if err != nil {
t.Errorf("Error encoding request body: %v", err)
}
// edit via post req
req = httptest.NewRequest("POST", "/alerts/edit", bytes.NewReader(jsonData))
req.Header.Add("Authorization", "Bearer "+jwtCookie.Value)
w = httptest.NewRecorder()
r.ServeHTTP(w, req)
// error if unexpected HTTP status
if w.Code != http.StatusOK {
t.Errorf("Expted status code %d, got %d", http.StatusOK, w.Code)
}
// decode body from json or error
if err := json.NewDecoder(w.Body).Decode(&fetchedAlert); err != nil {
t.Errorf("Error decoding response body: %v", err)
}
// compare dscriptions to confirm successful edit
if fetchedAlert.Description != &testDescription {
t.Error("Description was not updated")
}
log.Print("Successfully edited alert")
}
// TestDeleteAlert
// Tests deleting the alert created by TestCreateTask
func TestDeleteAlert(t *testing.T) {
// delete via api
req = httptest.NewRequest("DELETE", "/alerts/"+strconv.FormatInt(createdAlert.ID, 10), nil)
req.Header.Add("Authorization", "Bearer "+jwtCookie.Value)
w = httptest.NewRecorder()
r.ServeHTTP(w, req)
// error if unexpected http status
if w.Code != http.StatusOK {
t.Errorf("Expted status code %d, got %d", http.StatusOK, w.Code)
// if issue deleting alert, log that id as it may need to be manually deleted from db
log.Printf("Test alert ID %d may still exist, delete manually if so", createdAlert.ID)
}
log.Print("Successfully deleted alert")
}
// TestDeleteTask
// Tests deleting the task created by TestCreateTask
func TestDeleteTask(t *testing.T) {
// delete via api
req = httptest.NewRequest("DELETE", "/jobs/"+strconv.FormatInt(createdJob.ID, 10)+"/tasks/"+strconv.FormatInt(createdTask.ID, 10), nil)
req.Header.Add("Authorization", "Bearer "+jwtCookie.Value)
w = httptest.NewRecorder()
r.ServeHTTP(w, req)
// error if unexpected http status
if w.Code != http.StatusOK {
t.Errorf("Expted status code %d, got %d", http.StatusOK, w.Code)
// if issue deleting task, log that id as it may need to be manually deleted from db
log.Printf("Test task ID %d may still exist, delete manually if so", createdJob.ID)
}
log.Print("Successfully deleted task")
}
// TestDeleteJob
// Tests deleting the job created by TestCreateJob
func TestDeleteJob(t *testing.T) {
// delete via api
req = httptest.NewRequest("DELETE", "/jobs/"+strconv.FormatInt(createdJob.ID, 10), nil)
req.Header.Add("Authorization", "Bearer "+jwtCookie.Value)
w = httptest.NewRecorder()
r.ServeHTTP(w, req)
// error if unexpected http status
if w.Code != http.StatusOK {
t.Errorf("Expted status code %d, got %d", http.StatusOK, w.Code)
// if issue deleting job, log that id as it may need to be manually deleted from db
log.Printf("Test job ID %d may still exist, delete manually if so", createdJob.ID)
}
log.Print("Successfully deleted job")
}
// TestListLabels
// Tests getting all labels
func TestListLabels(t *testing.T) {
// get from api
req = httptest.NewRequest("GET", "/labels", nil)
w = httptest.NewRecorder()
r.ServeHTTP(w, req)
// error if unexpected HTTP status
if w.Code != http.StatusOK {
t.Errorf("Expted status code %d, got %d", http.StatusOK, w.Code)
}
// error if unable to decode response
var labels *[]models.Label
if err := json.NewDecoder(w.Body).Decode(&labels); err != nil {
t.Errorf("Error decoding response body: %v", err)
}
// error if no returned users
if labels == nil || len(*labels) == 0 {
t.Errorf("No labels retreived, at least one (test labels from TestCreateLabel) should exist")
}
log.Print("Successfully retrieved labels")
// get from api ofr job only, should be nil
req = httptest.NewRequest("GET", "/labels?job="+strconv.FormatInt(createdLabel.ID, 10), nil)
w = httptest.NewRecorder()
r.ServeHTTP(w, req)
// error if unexpected HTTP status
if w.Code != http.StatusOK {
t.Errorf("Expted status code %d, got %d", http.StatusOK, w.Code)
}
// error if unable to decode response