forked from hedyorg/hedy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tests_e2e.py
1809 lines (1500 loc) · 70.6 KB
/
tests_e2e.py
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
# *** NATIVE DEPENDENCIES ***
import os
import collections
import random
import json
import re
import urllib.parse
from http.cookies import SimpleCookie
# *** LIBRARIES ***
import unittest
import requests
# *** HEDY RESOURCES ***
import utils
from config import config as CONFIG
# *** GLOBAL VARIABLES ***
from hedy import HEDY_MAX_LEVEL
from hedy_content import ALL_LANGUAGES
HOST = os.getenv('ENDPOINT', 'http://localhost:' + str(CONFIG['port']) + '/')
if not HOST.endswith('/'):
HOST += '/'
# This dict has global scope and holds all created users and their still
# current sessions (as cookies), for convenient reuse wherever needed
USERS = {}
# *** HELPERS ***
def request(method, path, headers={}, body='', cookies=None):
if method not in ['get', 'post', 'put', 'delete']:
raise Exception('request - Invalid method: ' + str(method))
# We pass the X-Testing header to let the server know that this is a
# request coming from an E2E test, thus no transactional emails should be
# sent.
headers['X-Testing'] = '1'
# If sending an object as body, stringify it and set the proper content-type header
if isinstance(body, dict):
headers['content-type'] = 'application/json'
body = json.dumps(body)
start = utils.timems()
response = getattr(requests, method)(HOST + path, headers=headers, data=body, cookies=cookies)
# Remember all cookies in the cookie jar
if cookies is not None:
cookies.update(response.cookies)
ret = {'time': utils.timems() - start}
if response.history and response.history[0]:
# This code branch will be executed if there is a redirect
ret['code'] = response.history[0].status_code
ret['headers'] = response.history[0].headers
if getattr(response.history[0], '_content'):
# We can assume that bodies returned from redirected responses are always
# plain text, since no JSON endpoint in the server is reachable through a
# redirect.
ret['body'] = getattr(response.history[0], '_content').decode('utf-8')
else:
ret['code'] = response.status_code
ret['headers'] = response.headers
if 'Content-Type' in response.headers and response.headers['Content-Type'] == 'application/json':
ret['body'] = response.json()
else:
ret['body'] = response.text
return ret
class AuthHelper(unittest.TestCase):
def setUp(self):
"""SetUp gets called on a fresh instance of this object, before each test.
We have a collection of users in the USER global array. However, we store
the cookies for individual users, so that cookies from different sessions don't
interfere with each other (i.e., every user must login again in each test).
"""
self.user_cookies = collections.defaultdict(requests.cookies.RequestsCookieJar)
self.user = None
@property
def username(self):
return self.user['username'] if self.user else None
def make_username(self):
# We create usernames with a random component so that if a test fails, we don't have to do a cleaning
# of the DB so that the test suite can run again
# This also allows us to run concurrent tests without having username conflicts.
username = 'user' + str(random.randint(10000, 100000))
return username
# If user with `username` exists, return it. Otherwise, create it.
def assert_user_exists(self, username):
if not isinstance(username, str):
raise Exception('AuthHelper.assert_user_exists - Invalid username: ' + str(username))
if username in USERS:
return USERS[username]
body = {
'username': username,
'email': username + '@hedy.com',
'language': 'nl',
'keyword_language': 'en',
'agree_terms': 'yes',
'password': 'foobar',
'password_repeat': 'foobar'}
response = request('post', 'auth/signup', {}, body, cookies=self.user_cookies[username])
# It might sometimes happen that by the time we attempted to create the user, another test did it already.
# In this case, we get a 403. We invoke the function recursively.
if response['code'] == 403:
return self.assert_user_exists(username)
# Store the user & also the verify token for use in upcoming tests
USERS[username] = body
USERS[username]['verify_token'] = response['body']['token']
return USERS[username]
# Returns the first created user, if any; otherwise, creates one.
def get_any_user(self):
if len(USERS.keys()) > 0:
return USERS[next(iter(USERS))]
return self.assert_user_exists(self.make_username())
def get_any_logged_user(self):
# If there's no logged in user, we login the user
user = self.get_any_user()
return self.login_user(user['username'])
def login_user(self, username):
"""Login another user. Does not BECOME that user for all subsequent request."""
self.assert_user_exists(username)
user = USERS[username]
request('post',
'auth/login',
{},
{'username': user['username'],
'password': user['password']},
cookies=self.user_cookies[username])
return user
def given_specific_user_is_logged_in(self, username):
"""Become this specific user for all subsequent calls."""
self.user = self.login_user(username)
def get_hedy_cookie(self, cookie_string):
cookie = SimpleCookie()
cookie.load(cookie_string)
for key, cookie in cookie.items():
if key == CONFIG['session']['cookie_name']:
return cookie
def given_fresh_user_is_logged_in(self):
username = self.make_username()
self.user = self.login_user(username)
def make_current_user_teacher(self):
"""Mark the current user as teacher.
Need to log in again to refresh the session.
"""
self.post_data('admin/markAsTeacher', {'username': self.username, 'is_teacher': True})
return self.login_user(self.username)
def given_user_is_logged_in(self):
self.user = self.get_any_logged_user()
def given_teacher_is_logged_in(self):
self.given_user_is_logged_in()
self.make_current_user_teacher()
def given_fresh_teacher_is_logged_in(self):
self.given_fresh_user_is_logged_in()
self.make_current_user_teacher()
def given_any_user(self):
self.user = self.get_any_user()
def switch_user(self, user):
self.user = self.login_user(user['username'])
def post_data(
self,
path,
body,
expect_http_code=200,
no_cookie=False,
return_headers=False,
put_data=False):
cookies = self.user_cookies[self.username] if self.username and not no_cookie else None
method = 'put' if put_data else 'post'
response = request(method, path, body=body, cookies=cookies)
self.assertEqual(
response['code'],
expect_http_code,
f'While {method}ing {body} to {path} (user: {self.username}). Response: {response["body"]}')
return response['headers'] if return_headers else response['body']
def delete_data(self, path, expect_http_code=200, no_cookie=False, return_headers=False):
cookies = self.user_cookies[self.username] if self.username and not no_cookie else None
method = 'delete'
response = request(method, path, cookies=cookies)
self.assertEqual(response['code'], expect_http_code,
f'While {method}ing {path} (user: {self.username})')
return response['headers'] if return_headers else response['body']
def get_data(self, path, expect_http_code=200, no_cookie=False, return_headers=False):
cookies = self.user_cookies[self.username] if self.username and not no_cookie else None
response = request('get', path, body='', cookies=cookies)
self.assertEqual(
response['code'],
expect_http_code,
f'While reading {path} (user: {self.username}). Response: {response["body"]}')
return response['headers'] if return_headers else response['body']
def destroy_current_user(self):
assert self.username is not None
self.post_data('auth/destroy', '')
# Remove any records of this user
USERS.pop(self.username)
# *** TESTS ***
class TestPages(AuthHelper):
def test_get_login_page(self):
# WHEN attempting to get the login page
# THEN receive an OK response code from the server
self.get_data('/login')
def test_get_signup_pages(self):
# WHEN attempting to get the signup flow
# THEN receive an OK response code from the server
self.get_data('/signup')
def test_get_recover_page(self):
# WHEN attempting to get the signup page
# THEN receive an OK response code from the server
self.get_data('/recover')
def test_get_admin_page(self):
# WHEN attempting to get the admin page
# THEN receive an OK response code from the server
# (Note: this only happens in a dev environment)
self.get_data('/admin')
def test_get_cheatsheet(self):
# WHEN attempting to get the cheatsheet page
# THEN receive an OK response code from the server
self.get_data('/cheatsheet')
def test_invalid_get_cheatsheet(self):
# WHEN attempting to get the cheatsheet page with an invalid value
# THEN receive an 404 response code from the server
self.get_data('/cheatsheet/123', expect_http_code=404)
self.get_data('/cheatsheet/panda', expect_http_code=404)
def test_highscore_pages(self):
# WHEN trying all languages to reach the highscore page
# THEN receive an OK response from the server
self.given_fresh_user_is_logged_in()
body = {'email': self.user['email'], 'keyword_language': self.user['keyword_language']}
for language in ALL_LANGUAGES.keys():
body['language'] = language
self.post_data('profile', body)
self.get_data("/highscores")
def test_valid_country_highscore_page(self):
# WHEN trying to reach the highscores page for a country with a profile country
# THEN receive an OK response from the server
self.given_fresh_user_is_logged_in()
# Add a country to the user profile
body = {
'email': self.user['email'],
'language': self.user['language'],
'keyword_language': self.user['keyword_language'],
'country': 'NL'
}
self.post_data('profile', body)
# Receive a valid response
self.get_data("/highscores/country")
def test_invalid_country_highscore_page(self):
# WHEN trying to reach the highscores page for a country without a profile country
# THEN receive an error response from the server
self.given_fresh_user_is_logged_in()
self.get_data("/highscores/country", expect_http_code=403)
def test_valid_class_highscore_page(self):
# WHEN a teacher is logged in and create a class
self.given_teacher_is_logged_in()
self.post_data('class', {'name': 'class1'})
Class = self.get_data('classes')[0]
# THEN a fresh user logs in and joins this class
self.given_fresh_user_is_logged_in()
self.post_data('class/join', {'id': Class['id']}, expect_http_code=200)
# THEN we can access the class highscore page
self.get_data("/highscores/class")
def test_invalid_class_highscore_page(self):
# WHEN a fresh user is not in a class
self.given_fresh_user_is_logged_in()
# THEN we can can't access the class highscore page
self.get_data("/highscores/class", expect_http_code=403)
def test_valid_program_filtering_page(self):
# WHEN a fresh user
self.given_fresh_user_is_logged_in()
# THEN we can retrieve the different filtering options of the programs page
filters = [
"?level=null&adventure=null",
"?level=4&adventure=null"
"?level=2&adventure=story"
]
for filter in filters:
self.get_data("/programs" + filter)
def test_valid_explore_filtering_page(self):
# WHEN a fresh user
self.given_fresh_user_is_logged_in()
# THEN we can retrieve the different filtering options of the explore page
filters = [
"?level=null&adventure=null&lang=null",
"?level=3&adventure=parrot&lang=null",
"?level=11&adventure=fortune&lang=es"
]
for filter in filters:
self.get_data("/explore" + filter)
def test_all_languages(self):
# WHEN trying all languages to reach all pages
# THEN receive an OK response from the server
self.given_fresh_user_is_logged_in()
body = {'email': self.user['email'], 'keyword_language': self.user['keyword_language']}
pages = [
'/',
'/hedy',
'/landing-page',
'/tutorial',
'/explore',
'/learn-more',
'/programs',
'/my-achievements',
'/my-profile']
for language in ALL_LANGUAGES.keys():
body['language'] = language
self.post_data('profile', body)
for page in pages:
if page == "/hedy":
for i in range(2, HEDY_MAX_LEVEL + 1):
self.get_data(page + "/" + str(i))
self.get_data(page)
class TestSessionVariables(AuthHelper):
def test_get_session_variables(self):
# WHEN getting session variables from the main environment
body = self.get_data('/session_main')
# THEN the body should contain a `session` with `session_id` and a `proxy_enabled` field
self.assertIn('session', body)
self.assertIn('session_id', body['session'])
self.assertIn('proxy_enabled', body)
session = body['session']
proxy_enabled = body['proxy_enabled']
# WHEN getting session variables from the test environment
test_body = self.get_data('/session_test')
if not proxy_enabled:
# If proxying to test is disabled, there is nothing else to test.
return
# THEN the body should contain a `session` with `session_id` and a `test_session` field
self.assertIn('session', test_body)
self.assertIn('session_id', test_body['session'])
self.assertIn('test_session', test_body['session'])
self.assertEquals(test_body['session']['session_id'], session['id'])
# WHEN getting session variables from the main environment
body = self.get_data('/session_main')
# THEN the body should have a session with a session_id that is still the
# same and a `test_session` field as well
self.assertEqual(body['session']['session_id'], session['id'])
self.assertEqual(body['session']['test_session'], test_body['session']['session_id'])
class TestAuth(AuthHelper):
def test_invalid_signups(self):
# GIVEN a valid username
username = self.make_username()
# WHEN attempting signups with invalid bodies
invalid_bodies = [
'',
[],
{},
{'username': 1},
{'username': 'user@me', 'password': 'foobar', 'email': '[email protected]'},
{'username:': 'user: me', 'password': 'foobar', 'email': '[email protected]'},
{'username': 't'},
{'username': ' t '},
{'username': username},
{'username': username, 'password': 1},
{'username': username, 'password': 'foo'},
{'username': username, 'password': 'foobar'},
{'username': username, 'password': 'foobar', 'email': 'me@something'},
{'username': username, 'password': 'foobar', 'email': '[email protected]', 'language': 123},
{'username': username, 'password': 'foobar', 'email': '[email protected]', 'language': True},
{'username': username, 'password': 'foobar', 'email': '[email protected]', 'heard_about': 'foo'},
{'username': username, 'password': 'foobar', 'email': '[email protected]', 'heard_about': ['other_source', 'foo']},
{'username': username, 'password': 'foobar', 'email': '[email protected]', 'heard_about': [2]},
{'username': username, 'password': 'foobar', 'email': '[email protected]', 'prog_experience': [2]},
{'username': username, 'password': 'foobar', 'email': '[email protected]', 'prog_experience': 'foo'},
{'username': username, 'password': 'foobar', 'email': '[email protected]', 'experience_languages': 'python'}
]
for invalid_body in invalid_bodies:
# THEN receive an invalid response code from the server
self.post_data('auth/signup', invalid_body, expect_http_code=400)
def test_signup(self):
# GIVEN a valid username and signup body
username = self.make_username()
user = {
'username': username,
'email': username + '@hedy.com',
'password': 'foobar',
'password_repeat': 'foobar',
'language': 'nl',
'keyword_language': 'en',
'heard_about': 'from_another_teacher',
'agree_terms': 'yes'}
# WHEN signing up a new user
# THEN receive an OK response code from the server
body = self.post_data('auth/signup', user)
# THEN receive a body containing a token
self.assertIsInstance(body, dict)
self.assertIsInstance(body['token'], str)
# FINALLY Store the user and its token for upcoming tests
user['verify_token'] = body['token']
USERS[username] = user
def test_invalid_login(self):
# WHEN attempting logins with invalid bodies
invalid_bodies = [
'',
[],
{},
{'username': 1},
{'username': 'user@me'},
{'username:': 'user: me'}
]
for invalid_body in invalid_bodies:
# THEN receive an invalid response code from the server
self.post_data('auth/login', invalid_body, expect_http_code=400)
def test_login(self):
# GIVEN an existing user
self.given_any_user()
# WHEN logging in the user
# THEN receive an OK response code from the server
headers = self.post_data('auth/login',
{'username': self.username,
'password': self.user['password']},
return_headers=True)
# THEN validate the cookie sent in the response
self.assertIsInstance(headers['Set-Cookie'], str)
hedy_cookie = self.get_hedy_cookie(headers['Set-Cookie'])
self.assertNotEqual(hedy_cookie, None)
self.assertEqual(hedy_cookie['httponly'], True)
self.assertEqual(hedy_cookie['path'], '/')
self.assertEqual(hedy_cookie['samesite'], 'Lax,')
def test_invalid_verify_email(self):
# GIVEN a new user
# (we create a new user to ensure that the verification flow hasn't been done for this user yet)
self.given_fresh_user_is_logged_in()
# WHEN submitting invalid verifications
invalid_verifications = [
# Missing token
{'username': self.username},
# Missing username
{'token': self.user['verify_token']},
]
for invalid_verification in invalid_verifications:
# THEN receive an invalid response code from the server
self.get_data(
'auth/verify?' +
urllib.parse.urlencode(invalid_verification),
expect_http_code=400)
# WHEN submitting well-formed verifications with invalid values
incorrect_verifications = [
# Invalid username
{'username': 'foobar', 'token': self.user['verify_token']},
# Invalid token
{'username': self.username, 'token': 'foobar'}
]
for incorrect_verification in incorrect_verifications:
# THEN receive a forbidden response code from the server
self.get_data(
'auth/verify?' +
urllib.parse.urlencode(incorrect_verification),
expect_http_code=403)
def test_verify_email(self):
# GIVEN a new user
# (we create a new user to ensure that the verification flow hasn't been done for this user yet)
self.given_fresh_user_is_logged_in()
# WHEN attepting to verify the user
# THEN receive a redirect from the server taking us to `/landing-page`
headers = self.get_data(
'auth/verify?' +
urllib.parse.urlencode(
{
'username': self.username,
'token': self.user['verify_token']}),
expect_http_code=302,
return_headers=True)
self.assertEqual(headers['location'], HOST + 'landing-page')
# WHEN attepting to verify the user again (the operation should be idempotent)
# THEN (again) receive a redirect from the server taking us to `/landing-page`
headers = self.get_data(
'auth/verify?' +
urllib.parse.urlencode(
{
'username': self.username,
'token': self.user['verify_token']}),
expect_http_code=302,
return_headers=True)
self.assertEqual(headers['location'], HOST + 'landing-page')
# WHEN retrieving profile to see that the user is no longer marked with
# `verification_pending`
self.given_specific_user_is_logged_in(self.username)
profile = self.get_data('profile')
# THEN check that the `verification_pending` has been removed from the user profile
self.assertNotIn('verification_pending', profile)
# FINALLY remove token from user since it's already been used.
self.user.pop('verify_token')
def test_logout(self):
# GIVEN a logged in user
self.given_user_is_logged_in()
# WHEN logging out the user
# THEN receive an OK response code from the server
self.post_data('auth/logout', '')
# WHEN retrieving the user profile with the same cookie
# THEN receive a forbidden response code from the server
self.get_data('profile', expect_http_code=403)
def test_destroy_account(self):
# GIVEN a logged in user
self.given_user_is_logged_in()
# WHEN deleting the user account
# THEN receive an OK response code from the server
self.destroy_current_user()
# WHEN retrieving the profile of the user
# THEN receive a forbidden response code from the server
self.get_data('profile', expect_http_code=403)
def test_invalid_change_password(self):
# GIVEN a logged in user
self.given_user_is_logged_in()
# WHEN attempting change password with invalid bodies
invalid_bodies = [
'',
[],
{},
{'old_password': 123456},
{'old_password': 'pass1'},
{'old_password': 'pass1', 'new-password': 123456},
{'old_password': 'pass1', 'new-password': 'short'},
{'old_password': 'pass1', 'new-password': 123456, 'password_repeat': 'panda'},
{'old_password': 'pass1', 'new-password': 'panda'},
]
for invalid_body in invalid_bodies:
# THEN receive an invalid response code from the server
self.post_data('auth/change_password', invalid_body, expect_http_code=400)
# WHEN attempting to change password without sending the correct old password
# THEN receive an invalid response code from the server
body = {'old_password': 'pass1', 'new-password': '123456', 'password_repeat': '123456'}
self.post_data('auth/change_password', body, expect_http_code=403)
def test_change_password(self):
# GIVEN a logged in user
self.given_user_is_logged_in()
# WHEN attempting to change the user's password
new_password = 'pas1234'
# THEN receive an OK response code from the server
self.post_data('auth/change_password',
{'old_password': self.user['password'],
'new-password': 'pas1234',
'password_repeat': 'pas1234'})
# WHEN attempting to login with old password
# THEN receive a forbidden response code from the server
self.post_data('auth/login',
{'username': self.username,
'password': self.user['password']},
expect_http_code=403)
# GIVEN the same user
# WHEN attempting to login with new password
# THEN receive an OK response code from the server
self.post_data('auth/login', {'username': self.username, 'password': new_password})
# FINALLY update password on user
self.user['password'] = new_password
def test_profile_get(self):
# GIVEN a new user
# (we create a new user to ensure that the user has a clean profile)
self.given_fresh_user_is_logged_in()
# WHEN retrieving the user profile
# THEN receive an OK response code from the server
profile = self.get_data('profile')
# THEN check that the fields returned by the server have the correct values
self.assertIsInstance(profile, dict)
self.assertEqual(profile['username'], self.username),
self.assertEqual(profile['email'], self.user['email']),
self.assertEqual(profile['verification_pending'], True)
self.assertIsInstance(profile['student_classes'], list)
self.assertEqual(len(profile['student_classes']), 0)
self.assertIsInstance(profile['session_expires_at'], int)
def test_invalid_profile_modify(self):
# GIVEN a logged in user
self.given_user_is_logged_in()
# WHEN attempting profile modifications with invalid bodies
invalid_bodies = [
'',
[],
{'email': 'foobar'},
{'birth_year': 'a'},
{'birth_year': 20},
{'gender': 0},
{'gender': 'a'},
{'language': True},
{'language': 123},
{'keyword_language': True},
{'keyword_language': 123},
]
for invalid_body in invalid_bodies:
# Create a valid body that we overwrite with invalid values
if isinstance(invalid_body, dict):
body = {
'email': self.user['email'],
'language': self.user['language'],
'keyword_language': self.user['keyword_language']
}
body.update(invalid_body)
invalid_body = body
# THEN receive an invalid response code from the server
self.post_data('profile', invalid_body, expect_http_code=400)
def test_profile_modify(self):
# GIVEN a new user
# (we create a new user to ensure that the user has a clean profile)
self.given_fresh_user_is_logged_in()
# WHEN submitting valid profile changes
profile_changes = {
'birth_year': 1989,
'country': 'NL',
'gender': 'o'
}
body = {
'email': self.user['email'],
'language': self.user['language'],
'keyword_language': self.user['keyword_language']
}
for key in profile_changes:
body[key] = profile_changes[key]
# THEN receive an OK response code from the server
self.post_data('profile', body)
# WHEN retrieving the profile
profile = self.get_data('profile')
# THEN confirm that our modification has been stored by the server and
# returned in the latest version of the profile
self.assertEqual(profile[key], profile_changes[key])
# WHEN updating the user's email
# (we check email change separately since it involves a flow with a token)
# THEN receive an OK response code from the server
new_email = self.username + '@newhedy.com'
body = self.post_data('profile',
{'email': new_email,
'language': self.user['language'],
'keyword_language': self.user['keyword_language']})
# THEN confirm that the server replies with an email verification token
self.assertIsInstance(body['token'], str)
# FINALLY update the email & email verification token on user
self.user['email'] = new_email
self.user['verify_token'] = body['token']
def test_invalid_change_language(self):
# GIVEN a logged in user
self.given_user_is_logged_in()
# WHEN trying to update the profile with an invalid language
body = {
'email': self.user['email'],
'language': 'abc',
'keyword_language': self.user['keyword_language']
}
# THEN receive an invalid response code from the server
self.post_data('profile', body, expect_http_code=400)
def test_valid_change_language(self):
# GIVEN a logged in user
self.given_user_is_logged_in()
# WHEN trying to update the profile with a valid language
body = {
'email': self.user['email'],
'language': 'nl',
'keyword_language': 'nl'
}
# THEN receive a valid response code from the server
self.post_data('profile', body, expect_http_code=200)
# WHEN trying to retrieve the current profile
profile = self.get_data('profile')
# THEN verify that the language is successfully changed
self.assertEqual(profile['language'], body['language'])
def test_invalid_keyword_language(self):
# GIVEN a logged in user
self.given_user_is_logged_in()
# WHEN trying to update the profile with an invalid keyword language
invalid_keyword_language = [
'nl',
123,
'panda'
]
body = {
'email': self.user['email'],
'language': 'en'
}
for invalid_lang in invalid_keyword_language:
body['keyword_language'] = invalid_lang
# THEN receive an invalid response code from the server
self.post_data('profile', body, expect_http_code=400)
def test_valid_keyword_language(self):
# GIVEN a logged in user
self.given_user_is_logged_in()
# WHEN trying to update the profile with a valid keyword language
body = {
'email': self.user['email'],
'language': 'nl',
'keyword_language': 'nl'
}
# THEN receive a valid response code from the server
self.post_data('profile', body, expect_http_code=200)
def test_invalid_recover_password(self):
# GIVEN an existing user
self.given_any_user()
# WHEN attempting a password recovery with invalid bodies
invalid_bodies = [
'',
[],
{},
{'username': 1}
]
for invalid_body in invalid_bodies:
# THEN receive an invalid response code from the server
self.post_data('auth/recover', invalid_body, expect_http_code=400)
# WHEN attempting a password recovery with a non-existing username
# THEN receive a forbidden response code from the server
self.post_data('auth/recover', {'username': self.make_username()}, expect_http_code=403)
def test_recover_password(self):
# GIVEN an existing user
self.given_any_user()
# WHEN attempting a password recovery
# THEN receive an OK response code from the server
body = self.post_data('auth/recover', {'username': self.username})
# THEN check that we have received a password recovery token from the server
self.assertIsInstance(body['token'], str)
def test_invalid_reset_password(self):
# GIVEN an existing user
self.given_any_user()
# WHEN attempting a password reset with invalid bodies
invalid_bodies = [
'',
[],
{},
{'username': 1},
{'username': 'foobar', 'token': 1},
{'username': 'foobar', 'token': 'some'},
{'username': 'foobar', 'token': 'some', 'password': 1},
{'username': 'foobar', 'token': 'some', 'password': 'short'},
{'username': 'foobar', 'token': 'some', 'password': 'short', 'password_repeat': 123},
{'username': 'foobar', 'token': 'some', 'password_repeat': 'panda123'}
]
for invalid_body in invalid_bodies:
# THEN receive an invalid response code from the server
self.post_data('auth/reset', invalid_body, expect_http_code=400)
# WHEN attempting a password reset with an invalid token
# THEN receive a forbidden response code from the server
self.post_data('auth/reset',
{'username': self.username,
'password': '123456',
'password_repeat': '123456',
'token': 'foobar'},
expect_http_code=403)
def test_reset_password(self):
# GIVEN an existing user
self.given_any_user()
# WHEN attempting a password reset with a valid username & token combination
new_password = 'pas1234'
recover_token = self.post_data('auth/recover', {'username': self.username})['token']
# THEN receive an OK response code from the server
self.post_data('auth/reset', {'username': self.username, 'password': new_password,
'password_repeat': new_password, 'token': recover_token})
# WHEN attempting a login with the new password
# THEN receive an OK response code from the server
self.post_data('auth/login', {'username': self.username, 'password': new_password})
# FINALLY update user's password and attempt login with new password
self.user['password'] = new_password
def test_invalid_public_profile(self):
# GIVEN a logged in user
self.given_user_is_logged_in()
# Create a program -> make sure it is not public
program = {'code': 'hello world', 'name': 'program 1', 'level': 1, 'shared': False}
program_id = self.post_data('programs', program)['id']
# WHEN attempting to create a public profile with invalid bodies
invalid_bodies = [
'',
[],
{},
{'image': 123456},
{'image': '123'},
{'image': '123', 'personal_text': 123},
{'image': '123', 'personal_text': 123},
{'image': '123', 'personal_text': 123, 'favourite_program': 123},
{'image': '123', 'personal_text': 'Welcome to my profile!', 'favourite_program': 123},
{'image': '5', 'personal_text': 'Welcome to my profile!', 'favourite_program': 123},
{'image': '5', 'personal_text': 'Welcome to my profile!', 'favourite_program': "abcdefghi"},
{'image': '5', 'personal_text': 'Welcome to my profile!', 'favourite_program': program_id},
]
for invalid_body in invalid_bodies:
# THEN receive an invalid response code from the server
self.post_data('auth/public_profile', invalid_body, expect_http_code=400)
def test_public_profile_without_favourite(self):
# GIVEN a logged in user
self.given_user_is_logged_in()
public_profile = {'image': '9', 'personal_text': 'welcome to my profile!'}
# WHEN creating a new public profile
# THEN receive an OK response code from the server
self.post_data('auth/public_profile', public_profile, expect_http_code=200)
def test_public_profile_with_favourite(self):
# GIVEN a logged in user
self.given_user_is_logged_in()
# Create a program that is public -> can be set as favourite on the public profile
program = {'code': 'hello world', 'name': 'program 1', 'level': 1, 'shared': True}
program_id = self.post_data('programs', program)['id']
public_profile = {
'image': '9',
'personal_text': 'welcome to my profile!',
'favourite_program': program_id}
# WHEN creating a new public profile with favourite program
# THEN receive an OK response code from the server
self.post_data('auth/public_profile', public_profile, expect_http_code=200)
def test_destroy_public_profile(self):
# GIVEN a logged in user
self.given_user_is_logged_in()
public_profile = {'image': '9', 'personal_text': 'welcome to my profile!'}
# WHEN creating a new public profile with favourite program
# THEN receive an OK response code from the server
self.post_data('auth/public_profile', public_profile, expect_http_code=200)
# WHEN destroying the public profile
# THEN receive an OK response from the server
self.post_data('auth/destroy_public', public_profile, expect_http_code=200)
class TestProgram(AuthHelper):
def test_invalid_get_programs(self):
# GIVEN a logged in user
self.given_user_is_logged_in()
# WHEN retrieving own programs but without sending a cookie
# THEN receive a forbidden response code from the server
self.get_data('programs/list', expect_http_code=403, no_cookie=True)
def test_get_programs(self):
# GIVEN a logged in user
self.given_user_is_logged_in()
# WHEN retrieving own programs sending a cookie
# THEN receive an OK response code from the server
body = self.get_data('programs/list')
# THEN verify that the server sent a body that is an object of the shape `{programs:[...]}`.
self.assertIsInstance(body, dict)
self.assertIsInstance(body['programs'], list)
def test_invalid_create_program(self):
# GIVEN a logged in user
self.given_user_is_logged_in()
# WHEN attempting to create an invalid program
invalid_bodies = [
'',
[],
{},
{'code': 1},
{'code': ['1']},
{'code': 'hello world'},
{'code': 'hello world', 'name': 1},
{'code': 'hello world', 'name': 'program 1'},
{'code': 'hello world', 'name': 'program 1', 'level': '1'},
{'code': 'hello world', 'name': 'program 1', 'level': 1, 'adventure_name': 1},