-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_endpoints.py
More file actions
1771 lines (1486 loc) · 68.5 KB
/
test_endpoints.py
File metadata and controls
1771 lines (1486 loc) · 68.5 KB
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
import os
import tempfile
import pytest
import json
import pdb
import unittest
from backend import app, db, bcrypt, mail
from backend.models.user import User, UserSchema, user_schema, Role
from backend.models.client_templates import ClientTemplate, ClientSession, ClientExercise, CheckIn, TrainingEntry
from backend.models.coach_templates import CoachTemplate, CoachSession, CoachExercise, Exercise
from flask_sqlalchemy import SQLAlchemy
from flask_session import Session
from datetime import datetime as dt
from datetime import date, timedelta
from flask_mail import Mail
DATE_FORMAT = '%Y-%m-%d'
# ----------------- SETUP -----------------
# Test client object that should be used when creating test clients
test_client = {
'first_name': 'test',
'last_name': 'client',
'email': 'test@client.com',
'password': 'fakepassword',
'role': 'CLIENT'
}
# Test client object that should be used when creating test coaches
test_coach = {
'first_name': 'test',
'last_name': 'coach',
'email': 'test@coach.com',
'password': 'fakepassword',
'role': 'COACH'
}
# Creates the app test client so that we can use it to call endpoints in our applicatoin
@pytest.fixture(scope='function')
def client(request):
test_client = app.test_client()
return test_client
# Database fixture. We create an in-memory SQlite database and use this for all tests. That way
# we don't put stress on our production database. It's important here that the scope is set to function
# so that the transactions are rolled back on every transaction
@pytest.fixture(scope='function')
def _db():
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite://"
# Comment above and uncomment below to persist the database to the local folder structure
# app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///test.db"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['TESTING'] = True
assert app.testing
mail = Mail(app)
# Create sessions table to handle login sessions
session = Session(app)
session.app.session_interface.db.create_all()
# We migrate the model into the sqlite database. It will create all tables based on the schema.
# We need to use the production database in order to migrate the data because the models are attached to this
# object
db.create_all()
return db
# ------------------------------------- CONFIGURATION TEST -------------------------------------
# Test that the mocked db_session works and doesn't persist beyond the scope of a test
def test_a_transaction(db_session):
user = User(
first_name=test_client['first_name'], last_name=test_client['last_name'],
email=test_client['email'], password=test_client['password'],
role=test_client['role'], verified=False
)
db_session.add(user)
db_session.commit()
def test_transaction_doesnt_persist(db_session):
user = db_session.query(User).filter_by(email=test_client['email']).first()
assert user == None
def test_health(client):
resp, code = request(client, 'GET', '/health')
assert code == 200
assert resp == {'success': True}
# ------------------------------------- USER TESTS -------------------------------------
def role_check(client, db_session, request_type, url):
client_user = sign_up_user_for_testing(client, test_client)
assert client_user['user'] != None
assert client_user['user']['role'] == 'CLIENT'
# Sign in as the client
login_resp = login_user_for_testing(client, test_client)
assert login_resp['user']['id'] != None and login_resp['user']['id'] != ""
resp, code = request(client, request_type, url)
return resp, code
def test_signup(client, db_session):
resp = sign_up_user_for_testing(client, test_client)
del resp['user']['id']
assert resp ==\
{
'user': {
'approved': False,
'check_in': None,
'coach_id': None,
'email': test_client['email'],
'first_name': test_client['first_name'],
'last_name': test_client['last_name'],
'reset_token': None,
'role': test_client['role'],
'verified': False
}
}
def test_verify_client(client, db_session):
# Create an unapproved user
resp = sign_up_user_for_testing(client, test_client)
assert resp['user']['approved'] == False
# Query the user so we can grab the verification token
user = User.query.filter_by(email=resp['user']['email']).first()
assert user != None
assert user.verification_token != None and user.verification_token != ""
# Approve the user using his verification token
url = '/verifyUser?verification_token={}&email={}'.format(user.verification_token, user.email)
resp, code = request(client, "GET", url)
# Refresh the user and check that they have been verified
user = User.query.get(user.id)
assert user.verified == True
# Check that the server redirected the client
assert code == 302
assert resp == None
def test_client_list(client, db_session):
# Sign up a coach so that sign is as a coach.
user = sign_up_user_for_testing(client, test_coach)
assert user['user'] != None
assert user['user']['role'] == 'COACH'
# Sign into the coach
login_resp = login_user_for_testing(client, test_coach)
assert login_resp['user']['id'] != None and login_resp['user']['id'] != ""
# Populate the database with approved, unapproved and past clients
clients = [
User(
first_name='test1', last_name='test1',
email='test1@user.com', password='fakepassword',
role='CLIENT', verified=False, approved=None
),
User(
first_name='test2', last_name='test2',
email='test2@user.com', password='fakepassword',
role='CLIENT', verified=False, approved=True
),
User(
first_name='test3', last_name='test3',
email='test3@user.com', password='fakepassword',
role='CLIENT', verified=False, approved=False
)
]
db_session.bulk_save_objects(clients)
db_session.commit()
# Grab the clients through the endpoint
clients_resp, code = request(client, "GET", '/clientList')
assert clients_resp != None and code == 200
# Check that the clients are returned
assert len(clients_resp['approvedClients']) != 0
assert len(clients_resp['unapprovedClients']) != 0
assert len(clients_resp['pastClients']) != 0
def test_update_profile(client, db_session):
# sign up as client
client_user = sign_up_user_for_testing(client, test_client)
assert client_user['user'] != None
assert client_user['user']['role'] == 'CLIENT'
# login as client
login_resp = login_user_for_testing(client, test_client)
assert login_resp['user']['id'] != None and login_resp['user']['id'] != ""
data = {
'first_name': 'changed first name',
'last_name': 'changed last name',
'email': 'changed@email.com',
'password': 'changedpassword',
'oldpassword': 'fakepassword'
}
# make updates
resp, code = request(client, "PUT", '/updateProfile', data=data)
assert resp != None and code == 200
assert resp['user']['first_name'] == 'changed first name'
assert resp['user']['last_name'] == 'changed last name'
assert resp['user']['email'] == 'changed@email.com'
# call updates with no data to test that nothing happens
resp, code = request(client, "PUT", '/updateProfile', data={})
assert code == 200
# def test_logout(client):
# new_user = create_new_user()
# signup_rv = sign_up_user_for_testing(client, new_user)
# login_rv = login_user_for_testing(client, new_user)
# logout_rv = client.get("auth/logout")
# assert logout_rv.json == {'success': True}
# forgot password and reset password have to be tested in the same endpoint because all db transactions are
# rolled back after the test ends (the user will lose their reset_token)
def test_forgot_password_flow(client, db_session):
# sign up as client
client_user = sign_up_user_for_testing(client, test_client)
assert client_user['user'] != None
assert client_user['user']['email'] == 'test@client.com'
assert client_user['user']['reset_token'] == None
# pass email to endpoint
url = '/forgotPassword?email={}'.format(client_user['user']['email'])
resp, code = request(client, "GET", url)
assert code == 200 and resp != None
assert resp['success'] == True
# check to see that a reset token was created for the user
user = User.query.get(client_user['user']['id'])
assert user != None
assert user.reset_token != None
# reset the users password with the generated reset_token and a new password
data = {
'password': 'testchangepassword',
'reset_token': user.reset_token
}
resp, code = request(client, "POST", 'resetPassword', data=data)
assert code == 200 and resp != None
assert resp['success'] == True
# Query the user again and check that the password has changed.
# TODO: Refreshing doesn't work for some reason
user = User.query.get(client_user['user']['id'])
assert bcrypt.check_password_hash(user.password, data['password'].encode(encoding='utf-8'))
def test_terminate_client(client, db_session):
# sign up a coach
coach_user = sign_up_user_for_testing(client, test_coach)
assert coach_user['user'] != None
assert coach_user['user']['role'] == 'COACH'
# sign up a client
client_user = sign_up_user_for_testing(client, test_client)
assert client_user['user'] != None
assert client_user['user']['role'] == 'CLIENT'
data = {
"id": client_user['user']['id']
}
# remove a client with insufficient permissions, should return 400
resp, code = request(client, "PUT", '/terminateClient', data=data)
assert code == 400 and resp != None
assert resp['error'] == 'Expected role of COACH'
# login as coach
login_resp = login_user_for_testing(client, test_coach)
assert login_resp['user']['id'] != None and login_resp['user']['id'] != ""
# remove a client logged in as coach, should succeed
resp, code = request(client, "PUT", '/terminateClient', data=data)
assert code == 200 and resp != None
assert resp['user']['approved'] == None
def test_delete_user(client, db_session):
# sign up a client to delete
client_user = sign_up_user_for_testing(client, test_client)
assert client_user['user'] != None
assert client_user['user']['role'] == 'CLIENT'
# sign up a coach
coach_user = sign_up_user_for_testing(client, test_coach)
assert coach_user['user'] != None
assert coach_user['user']['role'] == 'COACH'
# login as coach
login_resp = login_user_for_testing(client, test_coach)
assert login_resp['user']['id'] != None and login_resp['user']['id'] != ""
# Delete user with no id parameter, check that 400 is returned
url = "/user"
resp, code = request(client, "DELETE", url)
assert code == 400
assert resp['error'] == 'No id parameter found in request query'
# Delete user with no bogus id, check that 404 is returned
url = "/user?id={}".format(420)
resp, code = request(client, "DELETE", url)
assert code == 404
assert resp['error'] == 'No user found with passed id'
# Delete user
db_session.expire_all()
db_session.begin_nested()
url = "/user?id={}".format(client_user['user']['id'])
resp, code = request(client, "DELETE", url)
def test_get_user(client, db_session):
# sign up a client
client_user = sign_up_user_for_testing(client, test_client)
assert client_user['user'] != None
assert client_user['user']['role'] == 'CLIENT'
# get client with invalid credentials. should return 400
url = '/getUser?id={}'.format(client_user['user']['id'])
resp, code = request(client, "GET", url)
assert code == 400
assert resp['error'] == 'Expected role of COACH'
# sign up a coach
coach_user = sign_up_user_for_testing(client, test_coach)
assert coach_user['user'] != None
assert coach_user['user']['role'] == 'COACH'
# login as coach
login_resp = login_user_for_testing(client, test_coach)
assert login_resp['user']['id'] != None and login_resp['user']['id'] != ""
# get client with no id parameter, should return 404
url = '/getUser'
resp, code = request(client, "GET", url)
assert code == 404
assert resp['error'] == 'No id parameter found in request'
# get client with bogus id, should return 404
url = '/getUser?id={}'.format(420)
resp, code = request(client, "GET", url)
assert code == 404
assert resp['error'] == 'Invalid id'
# get client
url = '/getUser?id={}'.format(client_user['user']['id'])
resp, code = request(client, "GET", url)
assert code == 200 and resp != None
assert resp['user']['id'] == client_user['user']['id']
def test_approve_client(client, db_session):
# sign up a coach
coach_user = sign_up_user_for_testing(client, test_coach)
assert coach_user['user'] != None
assert coach_user['user']['role'] == 'COACH'
# login as coach
login_resp = login_user_for_testing(client, test_coach)
assert login_resp['user']['id'] != None and login_resp['user']['id'] != ""
# create the user to approve
user = User(
first_name='Test', last_name='Test', email='test@test.com', password='test', role='CLIENT',
verified=True, approved=False
)
db_session.add(user)
db_session.commit()
db_session.refresh(user)
data = {
'id': user.id
}
resp, code = request(client, "PUT", "/approveClient", data=data)
assert code == 200
assert resp != None
assert resp['Approved'] != None
current_db_session = db_session.object_session(user)
current_db_session.refresh(user)
assert user.approved
# ------------------------------------------- CLIENT TEMPLATES ------------------------------------------------------
def test_get_client_template(client, db_session):
# Create and sign into the client
user = sign_up_user_for_testing(client, test_client)
assert user['user'] != None
assert user['user']['role'] == 'CLIENT'
login_resp = login_user_for_testing(client, test_client)
assert login_resp['user']['id'] != None and login_resp['user']['id'] != ""
# Create a template for retrieval
template = generate_client_template_model()
template.user_id = user['user']['id']
db_session.add(template)
db_session.commit()
db_session.refresh(template)
# Calling endpoint without client_template_id should return a 400
url = '/client/template'
resp, code = request(client, "GET", url)
assert code == 400
assert resp['error'] == 'Need to pass EITHER client_template_id or client_template_slug as a request parameter'
# Retrieve template id
url = '/client/template?client_template_id={}'.format(str(template.id))
resp, code = request(client, "GET", url)
assert code == 200
assert resp != None
assert resp['id'] == template.id
# Retrieve template using slug
url = '/client/template?client_template_slug={}'.format(template.slug)
resp, code = request(client, "GET", url)
assert code == 200
assert resp != None
assert resp['id'] == template.id
def test_get_client_templates(client, db_session):
# Create and sign into the client
user = sign_up_user_for_testing(client, test_client)
assert user['user'] != None
assert user['user']['role'] == 'CLIENT'
login_resp = login_user_for_testing(client, test_client)
assert login_resp['user']['id'] != None and login_resp['user']['id'] != ""
# Create 2 templates for multiple template retrieval
template1 = generate_client_template_model()
template2 = generate_client_template_model()
template1.user_id = user['user']['id']
template2.user_id = user['user']['id']
db_session.add(template1)
db_session.add(template2)
db_session.commit()
db_session.refresh(template1)
db_session.refresh(template2)
# Check that we get a 400 back if we don't supply the user_id
url = '/client/templates'
resp, code = request(client, "GET", url)
assert code == 400
assert resp['error'] == 'No query parameter user_id found in request'
url = '/client/templates?user_id={}'.format(str(user['user']['id']))
resp, code = request(client, "GET", url)
assert code == 200
assert len(resp['templates']) == 2
assert resp['templates'][0]['id'] == template1.id or resp['templates'][0]['id'] == template2.id
assert resp['templates'][1]['id'] == template1.id or resp['templates'][1]['id'] == template2.id
def test_post_client_template(client, db_session):
# Create a coach to create the template and a client to assign it to
coach_user = sign_up_user_for_testing(client, test_coach)
assert coach_user['user'] != None
assert coach_user['user']['role'] == 'COACH'
client_user = sign_up_user_for_testing(client, test_client)
assert client_user['user'] != None
assert client_user['user']['role'] == 'CLIENT'
# Sign in as the coach
login_resp = login_user_for_testing(client, test_coach)
assert login_resp['user']['id'] != None and login_resp['user']['id'] != ""
# Create the client template, this function returns the coach_template used to assign to a client
# This also creates checkins so we can check that functionality
resp, code, coach_template = create_client_template(client, db_session, client_user['user']['id'])
check_ins = db_session.query(CheckIn).all()
assert code == 200
assert resp != None
assert resp['name'] == coach_template.name and resp['user_id'] == client_user['user']['id']
assert check_ins != None
assert len(check_ins) == 1
assert check_ins[0].start_date == date.today().strftime(DATE_FORMAT)
assert check_ins[0].end_date == (date.today() + timedelta(days=len(resp['sessions']))).strftime(DATE_FORMAT)
# Create a second client template to test slugification
resp, code, coach_template = create_client_template(client, db_session, client_user['user']['id'], starting_exercise_id=3)
assert code == 200
assert resp != None
assert resp['slug'] == 'test-coach-template-2-test-client'
# Create a third client template using a previous client template to test re-assigning and slugification
client_template = ClientTemplate.query.get(resp['id'])
assert client_template.id == resp['id']
data = {
'role': 'CLIENT',
'template_id': client_template.id,
'client_id': client_user['user']['id'],
}
# Create template without sessions, should get 400 back
resp, code = request(client, "POST", "/client/template", data=data)
assert code == 400
assert resp['error'] == 'Need to specify a valid template_id (int), client_id (int), sessions (array), and role (enum)'
data['sessions'] = []
# Create template with empty sessions, should return 400
resp, code = request(client, "POST", "/client/template", data=data)
assert code == 400
assert resp['error'] == 'Length of sessions supplied is 0'
data['sessions'] = [
{
'id': client_template.sessions[0].id,
'exercises': [
{
'id': client_template.sessions[0].exercises[0].id,
'sets': 4,
'reps': 10,
'weight': 150
}
]
}
]
resp, code = request(client, "POST", "/client/template", data=data)
assert code == 200
assert resp != None
assert resp['slug'] == 'test-coach-template-2-test-client-1'
assert resp['sessions'] != None
assert len(resp['sessions']) == 1
# error handling (check client_template error)
data['template_id'] = 10
data['role'] = 'COACH'
resp, code = request(client, "POST", "/client/template", data=data)
assert code == 404
assert resp['error'] == 'No coach template found with coach_template_id: 10'
# check error handling for user role
data['role'] = 'User'
resp, code = request(client, "POST", "/client/template", data=data)
assert code == 400
assert resp['error'] == "Parameter role should be either COACH or CLIENT"
def test_put_client_template(client, db_session):
# Create a coach to create the template and a client to assign it to
coach_user = sign_up_user_for_testing(client, test_coach)
assert coach_user['user'] != None
assert coach_user['user']['role'] == 'COACH'
client_user = sign_up_user_for_testing(client, test_client)
assert client_user['user'] != None
assert client_user['user']['role'] == 'CLIENT'
# Sign in as the coach
login_resp = login_user_for_testing(client, test_coach)
assert login_resp['user']['id'] != None and login_resp['user']['id'] != ""
# error test: pass an invalid id
data = {
"id": 10
}
resp, code = request(client, "PUT", '/client/template', data=data)
assert code == 404
assert resp['error'] == "No client template found with id: " + str(data['id'])
# Create the client template, this function returns the coach_template used to assign to a client
client_template, code, coach_template = create_client_template(client, db_session, client_user['user']['id'])
assert code == 200
assert client_template != None
assert client_template['name'] == coach_template.name and client_template['user_id'] == client_user['user']['id']
# Change name of template and ordering or sessions
# TODO: Need to test deleting a session through this endpoint. Getting make_transient error
data = {
'name': 'Test Template Name Change',
'user_id': client_user['user']['id'],
'sessions': [
{
'id': client_template['sessions'][0]['id'],
'name': 'Test Session Name Change 2',
'order': 2
},
{
'id': client_template['sessions'][1]['id'],
'name': 'Test Session Name Change 1',
'order': 1
}
]
}
# Not specifying an id should return 400
updated_client_template, code = request(client, "PUT", '/client/template', data=data)
assert code == 400
data['id'] = 1
updated_client_template, code = request(client, "PUT", '/client/template', data=data)
assert updated_client_template != None and code == 200
assert updated_client_template['name'] == 'Test Template Name Change'
assert len(updated_client_template['sessions']) == 2
assert updated_client_template['sessions'][0]['name'] == 'Test Session Name Change 1' and updated_client_template['sessions'][0]['id'] == data['sessions'][1]['id']
assert updated_client_template['sessions'][1]['name'] == 'Test Session Name Change 2' and updated_client_template['sessions'][1]['id'] == data['sessions'][0]['id']
def test_get_client_session(client, db_session):
# Create a coach to create the template and a client to assign it to
coach_user = sign_up_user_for_testing(client, test_coach)
assert coach_user['user'] != None
assert coach_user['user']['role'] == 'COACH'
client_user = sign_up_user_for_testing(client, test_client)
assert client_user['user'] != None
assert client_user['user']['role'] == 'CLIENT'
# Sign in as the coach
login_resp = login_user_for_testing(client, test_coach)
assert login_resp['user']['id'] != None and login_resp['user']['id'] != ""
# Create the client template, this function returns the coach_template used to assign to a client
client_template, code, coach_template = create_client_template(client, db_session, client_user['user']['id'])
assert code == 200
assert client_template != None
assert client_template['name'] == coach_template.name and client_template['user_id'] == client_user['user']['id']
# Retrieve a particular session from the client template
url = '/client/session?client_session_id={}'.format(client_template['sessions'][0]['id'])
client_session, code = request(client, 'GET', url)
assert code == 200
assert client_session != None
assert client_session['id'] == client_template['sessions'][0]['id']
# error test: pass all vars
session_id = 10
template_slug = "test-slug"
session_slug = "session_slug"
url = '/client/session?client_session_id={}&client_template_slug={}&client_session_slug={}'.format(session_id, template_slug, session_slug)
resp, code = request(client, 'GET', url)
assert code == 400
assert resp['error'] == "Pass EITHER client_session_id OR client_template_slug + client_session_slug in the request parameter"
# error test: pass template_slug != None and session_slug == None
url = '/client/session?client_template_slug={}'.format(template_slug)
resp, code = request(client, 'GET', url)
assert code == 400
assert resp['error'] == "Pass EITHER client_session_id OR client_template_slug + client_session_slug in the request parameter"
# error test: wrong template slug
url = '/client/session?client_template_slug={}&client_session_slug={}'.format(template_slug, session_slug)
resp, code = request(client, 'GET', url)
assert code == 404
assert resp['error'] == "No client template found with slug: " + template_slug
def test_get_client_next_session(client, db_session):
# Create a coach to create the template and a client to assign it to
coach_user = sign_up_user_for_testing(client, test_coach)
assert coach_user['user'] != None
assert coach_user['user']['role'] == 'COACH'
client_user = sign_up_user_for_testing(client, test_client)
assert client_user['user'] != None
assert client_user['user']['role'] == 'CLIENT'
# Sign in as the coach
login_resp = login_user_for_testing(client, test_coach)
assert login_resp['user']['id'] != None and login_resp['user']['id'] != ""
# Create the client template, this function returns the coach_template used to assign to a client
client_template, code, coach_template = create_client_template(client, db_session, client_user['user']['id'])
assert code == 200
assert client_template != None
assert client_template['name'] == coach_template.name and client_template['user_id'] == client_user['user']['id']
# Retrieve a particular session from the client template
url = '/client/session/next?client_id={}'.format(client_user['user']['id'])
next_session, code = request(client, 'GET', url)
assert code == 200
assert next_session != None
assert next_session['completed'] == False and next_session['client_template_id'] == client_template['id'] and client_template['active'] == True
# check error handling
url = '/client/session/next'
resp, code = request(client, 'GET', url)
assert code == 400
assert resp['error'] == "No query parameter client_id found in request"
# check error handling: wrong client_id
client_id = 100
url = '/client/session/next?client_id={}'.format(client_id)
resp, code = request(client, 'GET', url)
assert code == 404
assert resp['error'] == "No active template found with client_id: " + str(client_id)
def test_post_client_session(client, db_session):
# Create a coach to create the template and a client to assign it to
coach_user = sign_up_user_for_testing(client, test_coach)
assert coach_user['user'] != None
assert coach_user['user']['role'] == 'COACH'
client_user = sign_up_user_for_testing(client, test_client)
assert client_user['user'] != None
assert client_user['user']['role'] == 'CLIENT'
# Sign in as the coach
login_resp = login_user_for_testing(client, test_coach)
assert login_resp['user']['id'] != None and login_resp['user']['id'] != ""
# Create the client template, this function returns the coach_template used to assign to a client
client_template, code, coach_template = create_client_template(client, db_session, client_user['user']['id'])
assert code == 200
assert client_template != None
assert client_template['name'] == coach_template.name and client_template['user_id'] == client_user['user']['id']
assert len(client_template['sessions']) == 2
data1 = {
'client_template_id': client_template['id'],
'name': 'Feet Day 1',
'exercises': [
{
"name": "Tip Toe",
"category": "Arch",
"sets": 3,
"reps": 15,
"weight": 150,
"order": 1
},
]
}
data2 = {
'client_template_id': client_template['id'],
'name': 'Feet Day 2',
'exercises': [
{
"name": "Tip Toe",
"category": "Arch",
"sets": 3,
"reps": 15,
"weight": 150,
"order": 1
},
]
}
# Test creating a client session as a coach (exercises should be added into exercises)
client_session_1, code = request(client, "POST", '/client/session', data=data1)
assert code == 200
assert client_session_1['name'] == 'Feet Day 1'
assert len(client_session_1['exercises']) == 1 and len(client_session_1['training_entries']) == 0
login_resp = login_user_for_testing(client, test_client)
assert login_resp['user']['id'] != None and login_resp['user']['id'] != ""
client_session_2, code = request(client, "POST", '/client/session', data=data2)
assert code == 200
assert client_session_2['name'] == 'Feet Day 2'
assert len(client_session_2['exercises']) == 0 and len(client_session_2['training_entries']) == 1
# error test: missing arg
data3 = {
'name': 'Feet Day 1',
'exercises': [
{
"name": "Tip Toe",
"category": "Arch",
"sets": 3,
"reps": 15,
"weight": 150,
"order": 1
},
]
}
resp, code = request(client, "POST", '/client/session', data=data3)
assert code == 400
assert resp['error'] == "Must specify client_template_id (int) name (string) and exercises (array)"
# error test: invalid client_template_id
data2['client_template_id'] = 100
resp, code = request(client, "POST", '/client/session', data=data2)
assert code == 404
assert resp['error'] == "No client template found with template id: " + str(data2['client_template_id'])
# error test: invalid session name
data2['client_template_id'] = client_template['id']
data2['name'] = 'Feet Day 1'
resp, code = request(client, "POST", '/client/session', data=data2)
assert code == 409
assert resp['error'] == "Duplicate session name found in template: " + str(data2['name'])
def test_put_client_session(client, db_session):
# Create a coach to create the template and a client to assign it to
coach_user = sign_up_user_for_testing(client, test_coach)
assert coach_user['user'] != None
assert coach_user['user']['role'] == 'COACH'
client_user = sign_up_user_for_testing(client, test_client)
assert client_user['user'] != None
assert client_user['user']['role'] == 'CLIENT'
# Sign in as the coach
login_resp = login_user_for_testing(client, test_coach)
assert login_resp['user']['id'] != None and login_resp['user']['id'] != ""
# Create the client template, this function returns the coach_template used to assign to a client
client_template, code, coach_template = create_client_template(client, db_session, client_user['user']['id'])
assert code == 200
assert client_template != None
assert client_template['name'] == coach_template.name and client_template['user_id'] == client_user['user']['id']
# Update a particular client session, we will update the first client session. Set completed to true so we can test if the completed_date is being
# set correctly
data = {
'id': client_template['sessions'][0]['id'],
'name': 'Client session name change',
'completed': True,
'exercises': [
{
"name": "Deadlifts",
"category": "Lower Back",
"sets": 1,
"reps": 1,
"weight": 100,
"order": 1
}
]
}
resp, code = request(client, "PUT", '/client/session', data=data)
assert code == 200
assert resp != None
assert len(resp['exercises']) == 1
assert resp['name'] == 'Client session name change'
assert resp['completed'] == True
assert resp['completed_date'] == (date.today() + timedelta(days=resp['order'])).strftime(DATE_FORMAT)
# test error: wrong id
data['id'] = 100
resp, code = request(client, "PUT", '/client/session', data=data)
assert code == 404
assert resp['error'] == "No client session found with supplied id"
# test error: missing id
del data['id']
resp, code = request(client, "PUT", '/client/session', data=data)
assert code == 400
assert resp['error'] == "No id parameter found in request body"
def test_get_active_client_template(client, db_session):
# Create and sign into the client
user = sign_up_user_for_testing(client, test_client)
assert user['user'] != None
assert user['user']['role'] == 'CLIENT'
login_resp = login_user_for_testing(client, test_client)
assert login_resp['user']['id'] != None and login_resp['user']['id'] != ""
# Create 2 templates so that we can grab the specific active template. We also want to check if there are 2
# active templates that the response returns a 409 error code
template1 = generate_client_template_model(active=True)
template2 = generate_client_template_model(active=True)
template1.user_id = user['user']['id']
template2.user_id = user['user']['id']
db_session.add(template1)
db_session.add(template2)
db_session.commit()
db_session.refresh(template1)
db_session.refresh(template2)
url = '/client/template/active'
resp, code = request(client, "GET", url)
assert code == 400 and resp['error'] == 'No query parameter user_id found in request'
url = '/client/template/active?user_id={}'.format(user['user']['id'])
resp, code = request(client, "GET", url)
assert code == 409 and resp['error'] == "More than 1 active template found for client"
# Update one of the templates to not be active (template 2). IMPORTANT to update and delete objects you have to grab the current session
# that is handling the specific template
template2.active = False
current_db_session = db_session.object_session(template2)
current_db_session.commit()
url = '/client/template/active?user_id={}'.format(user['user']['id'])
resp, code = request(client, "GET", url)
assert code == 200
assert resp != None
assert resp['id'] == template1.id
# ------------------------------------- HELPER METHODS -------------------------------------
# sign up a user. It returns the user response. It also error checks
def sign_up_user_for_testing(client, user):
mimetype = 'application/json'
headers = {
'Content-Type': mimetype,
'Accept': mimetype
}
# Set test to true so that an album isn't created for the user
data = {
'first_name': user['first_name'],
'last_name': user['last_name'],
'email': user['email'],
'password': user['password'],
'role': user['role'],
'test': True
}
resp = client.post('signUp', data=json.dumps(data), headers=headers)
assert resp.json != None
assert resp._status_code == 200
return resp.json
# request is a helper method to make a request with the application client
def request(client, method, url, data=None):
mimetype = 'application/json'
headers = {
'Content-Type': mimetype,
'Accept': mimetype
}
resp = None
if method == "GET":
resp = client.get(url)
elif method == "POST":
resp = client.post(url, data=json.dumps(data), headers=headers)
elif method == "PUT":
resp = client.put(url, data=json.dumps(data), headers=headers)
elif method == "DELETE":
resp = client.delete(url)
return resp.json, resp._status_code
# test http guard
# Logs a user in. Input user should contain email and password. It also error checks
def login_user_for_testing(client, user):
mimetype = 'application/json'
headers = {
'Content-Type': mimetype,
'Accept': mimetype
}
data = {
'email': user['email'],
'password': user['password']
}
resp = client.post("/auth/login", data=json.dumps(data), headers=headers)
assert resp.json != None
assert resp._status_code == 200
return resp.json
def logout_user_for_testing(client):
resp = client.get("/auth/logout")
assert resp.json != None
assert resp._status_code == 200
return resp.json
def generate_client_template_model(active=True):
return ClientTemplate(
name='Test Client Template', slug='test-client-template', start_date='2020-12-12', completed=False, active=active, sessions=[
ClientSession(
name='Test Session 1', order=1, completed=False, completed_date='2020-12-13', slug='test-session-1', exercises=[
ClientExercise(
sets=3, reps=12, weight=225, category='Lower Back', name='Deadlifts', order=1
)
]
)
]
)
# This method generates a CoachTemplate model and adds the corresponding exercises to the database.
# The CoachTemplate will have 2 coach sessions with 2 exercises each
def generate_coach_template_model(db_session, id):
db_session.add(Exercise(id=id, category='Lower Back', name='Deadlifts'))
db_session.add(Exercise(id=id + 1, category='Latisimus Dorsi', name='Pullups'))
db_session.commit()
if id == 1:
name = 'Test Coach Template'
slug = 'test-coach-template'
elif id == 3:
name = 'Test Coach Template 2'
slug = 'test-coach-template-2'
return CoachTemplate(
id=id, name=name, slug=slug, sessions=[
CoachSession(
name='Test Session 1', slug='test-session-1', order=1, coach_exercises=[
CoachExercise(
exercise_id=id, order=1,
),