-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathtest_integration.py
1987 lines (1753 loc) · 75.2 KB
/
test_integration.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
import uuid
from unittest.mock import patch
import pytest
import werkzeug
from werkzeug.exceptions import Unauthorized
from urllib.parse import urlparse, parse_qs
from microsetta_private_api.repo.consent_repo import ConsentRepo
from microsetta_private_api.model.consent import ConsentDocument
import microsetta_private_api.server
from microsetta_private_api.localization import LANG_SUPPORT, \
NEW_PARTICIPANT_KEY, EN_US, EN_GB
from microsetta_private_api.api.tests.utils import check_response
from microsetta_private_api.repo.transaction import Transaction
from microsetta_private_api.repo.account_repo import AccountRepo
from microsetta_private_api.model.account import Account
from microsetta_private_api.repo.source_repo import SourceRepo
from microsetta_private_api.repo.survey_answers_repo import SurveyAnswersRepo
from microsetta_private_api.model.source import \
Source, HumanInfo, NonHumanInfo
from microsetta_private_api.model.address import Address
from microsetta_private_api.util.util import json_converter, fromisotime
from microsetta_private_api.util import vioscreen
from microsetta_private_api.config_manager import SERVER_CONFIG
import datetime
import json
from unittest import TestCase, skipIf
from microsetta_private_api.LEGACY.locale_data import american_gut, british_gut
import copy
import microsetta_private_api.api
from microsetta_private_api.repo.survey_template_repo import SurveyTemplateRepo
ACCT_ID = "aaaaaaaa-bbbb-cccc-dddd-eeeeffffffff"
NOT_ACCT_ID = "12341234-1234-1234-1234-123412341234"
HUMAN_ID = "b0b0b0b0-b0b0-b0b0-b0b0-b0b0b0b0b0b0"
BOBO_FAVORITE_SURVEY_TEMPLATE = 1
DOGGY_ID = "dddddddd-dddd-dddd-dddd-dddddddddddd"
PLANTY_ID = "eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee"
SUPPLIED_KIT_ID = "FooFooFoo"
KIT_ID = '77777777-8888-9999-aaaa-bbbbcccccccc'
MOCK_SAMPLE_ID = '99999999-aaaa-aaaa-aaaa-bbbbcccccccc'
BARCODE = '777777777'
# Had to change from [email protected] after I ran api/ui to create
# a [email protected] address in my test db.
FAKE_EMAIL = "[email protected]"
MOCK_HEADERS = {"Authorization": "Bearer boogabooga"}
MOCK_HEADERS_2 = {"Authorization": "Bearer woogawooga"}
MOCK_HEADERS_3 = {"Authorization": "Bearer toogatooga"}
DUMMY_CONSENT_POST_URL = "http://test.com"
DUMMY_ACCT = {
"id": "ecabc635-3df8-49ee-ae19-db3db03c1111",
"email": "[email protected]",
"first_name": "demo",
"last_name": "demo",
"address": {"street": "demo",
"street2": "",
"city": "demo",
"state": "IN",
"post_code": "46227",
"country_code": "US"
},
"language": "en_US"
}
CONSENT_DOC_ID = "b8245ca9-e5ba-4f8f-a84a-887c0d6a2281"
CONSENT_DOC = {"consent_type": "adult_data",
"locale": "en_US",
"consent": "Adult Data Consent",
"reconsent": 'true',
"version": 9999
}
def mock_verify_func(token):
if token == "boogabooga":
return {
"email": "[email protected]",
'email_verified': True,
"iss": "https://MOCKUNITTEST.com",
"sub": "1234ThisIsNotARealSub",
}
elif token == "woogawooga":
return {
"email": FAKE_EMAIL,
'email_verified': True,
"iss": "https://MOCKUNITTEST.com",
"sub": "ThisIsAlsoNotARealSub",
}
elif token == "toogatooga":
return {
"email": "[email protected]",
'email_verified': True,
"iss": "https://demotest.com",
"sub": "DemoSub",
}
else:
raise Unauthorized("Neither boogabooga nor woogawooga")
@pytest.fixture(scope="class")
def client(request):
app = microsetta_private_api.server.build_app()
app.app.testing = True
with app.app.test_client() as client:
request.cls.client = client
with patch("microsetta_private_api.api."
"verify_jwt") as mock_verify, \
patch("microsetta_private_api.api._sample.qclient"), \
patch("microsetta_private_api.admin.admin_impl.qclient"), \
patch("microsetta_private_api.repo.qiita_repo.qclient"):
mock_verify.side_effect = mock_verify_func
yield client
def fuzz(val):
""" A fuzzer for json data """
if isinstance(val, int):
return val + 7
if isinstance(val, str):
return "FUZ" + val + "ZY"
if isinstance(val, list):
return ["Q(*.*)Q"] + [fuzz(x) for x in val] + ["P(*.*)p"]
if isinstance(val, dict):
fuzzy = {x: fuzz(y) for x, y in val.items()}
return fuzzy
def fuzz_field(field, model):
if field['type'] == "input" or field['type'] == "textArea":
model[field['id']] = 'bo'
if field['type'] == "select":
model[field['id']] = field['values'][0]
if field['type'] == 'checklist':
model[field['id']] = [field['values'][0]]
if field['type'] == "radios":
model[field['id']] = field['values'][0]
def fuzz_form(form):
""" Fills in a vue form with junk data """
model = {}
if form['fields'] is not None:
for field in form['fields']:
fuzz_field(field, model)
if form['groups'] is not None:
for group in form['groups']:
if group['fields'] is not None:
for field in group['fields']:
fuzz_field(field, model)
return model
@pytest.mark.usefixtures("client")
class IntegrationTests(TestCase):
def setUp(self):
IntegrationTests.setup_test_data()
app = microsetta_private_api.server.build_app()
self.client = app.app.test_client()
# This isn't perfect, due to possibility of exceptions being thrown
# is there some better pattern I can use to split up what should be
# a 'with' call?
self.client.__enter__()
def tearDown(self):
# This isn't perfect, due to possibility of exceptions being thrown
# is there some better pattern I can use to split up what should be
# a 'with' call?
self.client.__exit__(None, None, None)
IntegrationTests.teardown_test_data()
@staticmethod
def setup_test_data():
LANG_SUPPORT[EN_US][NEW_PARTICIPANT_KEY] = copy.deepcopy(
american_gut._NEW_PARTICIPANT)
LANG_SUPPORT[EN_US][NEW_PARTICIPANT_KEY]['SEL_AGE_RANGE'] = "Murica!"
LANG_SUPPORT[EN_GB][NEW_PARTICIPANT_KEY] = copy.deepcopy(
british_gut._NEW_PARTICIPANT)
LANG_SUPPORT[EN_GB][NEW_PARTICIPANT_KEY]['SEL_AGE_RANGE'] = \
"QQBritannia"
IntegrationTests.teardown_test_data()
with Transaction() as t:
acct_repo = AccountRepo(t)
source_repo = SourceRepo(t)
# Set up test account with sources
acc = Account(ACCT_ID,
"standard",
"https://MOCKUNITTEST.com",
"1234ThisIsNotARealSub",
"Dan",
"H",
Address(
"123 Dan Lane",
"Danville",
"CA",
12345,
"US",
""
),
32.8798916,
-117.2363115,
False,
"en_US",
True)
acct_repo.create_account(acc)
source_repo.create_source(Source(
HUMAN_ID,
ACCT_ID,
Source.SOURCE_TYPE_HUMAN,
"Bo",
HumanInfo(False, None, None,
False, datetime.datetime.utcnow(), None,
"Mr. Obtainer",
"18-plus")
))
source_repo.create_source(Source(
DOGGY_ID,
ACCT_ID,
Source.SOURCE_TYPE_ANIMAL,
"Doggy",
NonHumanInfo("Doggy The Dog")))
source_repo.create_source(Source(
PLANTY_ID,
ACCT_ID,
Source.SOURCE_TYPE_ENVIRONMENT,
"Planty",
NonHumanInfo("The green one")))
_create_mock_kit(t)
with t.cursor() as cur:
# american and british are ALWAYS the same!
# Need to mock a row where they differ, which will be on
# question 107.
cur.execute("SELECT american, british FROM survey_question "
"WHERE survey_question_id = 107")
row = cur.fetchone()
# If this fails, it most likely means the teardown failed
# last time the tests were run. But it could also mean
# someone changed survey question 107!!!
assert row[0] == "Gender:"
assert row[1] == "Gender:"
cur.execute("UPDATE survey_question "
"SET "
"american = 'Gender:', "
"british = 'Gandalf:' "
"WHERE survey_question_id = 107")
cur.execute("UPDATE survey_response SET "
"british = 'Wizard' "
"WHERE "
"american = 'Male'")
t.commit()
@staticmethod
def teardown_test_data():
with Transaction() as t:
with t.cursor() as cur:
# TODO: This restoration plan is terrible! We need a better
# way to mock out the database!!
cur.execute("UPDATE survey_question "
"SET "
"american = 'Gender:', "
"british = 'Gender:' "
"WHERE survey_question_id = 107")
cur.execute("UPDATE survey_response SET "
"british = 'Male' "
"WHERE "
"american = 'Male'")
t.commit()
with Transaction() as t:
acct_repo = AccountRepo(t)
source_repo = SourceRepo(t)
_remove_mock_kit(t)
# since myfoodrepo is source not sample based,
# we cannot simply use the "remove_mock_kit"
# machinery. however, we still need to clean up
# dangling FKs, so let's do so
cur = t.cursor()
cur.execute("DELETE FROM myfoodrepo_registry "
"WHERE account_id=%s",
(ACCT_ID,))
cur.execute("DELETE FROM vioscreen_registry "
"WHERE account_id=%s",
(ACCT_ID,))
survey_answers_repo = SurveyAnswersRepo(t)
for source in source_repo.get_sources_in_account(
ACCT_ID,
allow_revoked=True
):
answers = survey_answers_repo.list_answered_surveys(ACCT_ID,
source.id)
for survey_id in answers:
survey_answers_repo.delete_answered_survey(ACCT_ID,
survey_id)
source_repo.delete_source(ACCT_ID, source.id)
acct_repo.delete_account(ACCT_ID)
t.commit()
def test_get_sources(self):
resp = self.client.get(
'/api/accounts/%s/sources?language_tag=en_US' % ACCT_ID,
headers=MOCK_HEADERS)
check_response(resp)
sources = json.loads(resp.data)
self.assertEqual(
len([x for x in sources if x['source_name'] == 'Bo']),
1,
"Expected one source named Bo")
self.assertEqual(
len([x for x in sources if x['source_name'] == 'Doggy']),
1,
"Expected 1 source named Doggy")
self.assertEqual(
len([x for x in sources if x['source_name'] == 'Planty']),
1,
"Expected 1 source named Planty")
def test_put_source(self):
resp = self.client.get(
'/api/accounts/%s/sources?language_tag=en_US' % ACCT_ID,
headers=MOCK_HEADERS
)
check_response(resp)
sources = json.loads(resp.data)
self.assertGreaterEqual(len(sources), 3)
to_edit = sources[2]
source_id = to_edit["source_id"]
fuzzy = fuzz(to_edit)
fuzzy["source_type"] = to_edit["source_type"]
fuzzy.pop("source_id")
resp = self.client.put(
'/api/accounts/%s/sources/%s?language_tag=en_US' %
(ACCT_ID, source_id),
content_type='application/json',
data=json.dumps(fuzzy),
headers=MOCK_HEADERS
)
check_response(resp)
fuzzy_resp = json.loads(resp.data)
self.assertEqual(fuzzy["source_name"], fuzzy_resp["source_name"])
self.assertEqual(fuzzy["source_description"],
fuzzy_resp["source_description"])
to_edit.pop("source_id")
resp = self.client.put(
'/api/accounts/%s/sources/%s?language_tag=en_US' %
(ACCT_ID, source_id),
content_type='application/json',
data=json.dumps(to_edit),
headers=MOCK_HEADERS
)
check_response(resp)
edit_resp = json.loads(resp.data)
self.assertEqual(to_edit["source_name"], edit_resp["source_name"])
self.assertEqual(to_edit["source_description"],
edit_resp["source_description"])
def test_surveys(self):
resp = self.client.get(
'/api/accounts/%s/sources?language_tag=en_US' % ACCT_ID,
headers=MOCK_HEADERS
)
check_response(resp)
sources = json.loads(resp.data)
bobo = [x for x in sources if x['source_name'] == 'Bo'][0]
doggy = [x for x in sources if x['source_name'] == 'Doggy'][0]
env = [x for x in sources if x['source_name'] == 'Planty'][0]
resp = self.client.get(
'/api/accounts/%s/sources/%s/survey_templates?language_tag=en_US' %
(ACCT_ID, bobo['source_id']),
headers=MOCK_HEADERS
)
bobo_surveys = json.loads(resp.data)
resp = self.client.get(
'/api/accounts/%s/sources/%s/survey_templates?language_tag=en_US' %
(ACCT_ID, doggy['source_id']),
headers=MOCK_HEADERS
)
doggy_surveys = json.loads(resp.data)
resp = self.client.get(
'/api/accounts/%s/sources/%s/survey_templates?language_tag=en_US' %
(ACCT_ID, env['source_id']),
headers=MOCK_HEADERS
)
env_surveys = json.loads(resp.data)
# Survey status should not be in templates
self.assertNotIn("survey_status", bobo_surveys[0])
self.assertListEqual([x["survey_template_id"] for x in bobo_surveys],
[SurveyTemplateRepo.VIOSCREEN_ID,
SurveyTemplateRepo.POLYPHENOL_FFQ_ID,
SurveyTemplateRepo.SPAIN_FFQ_ID,
SurveyTemplateRepo.BASIC_INFO_ID,
SurveyTemplateRepo.AT_HOME_ID,
SurveyTemplateRepo.LIFESTYLE_ID,
SurveyTemplateRepo.GUT_ID,
SurveyTemplateRepo.GENERAL_HEALTH_ID,
SurveyTemplateRepo.HEALTH_DIAG_ID,
SurveyTemplateRepo.ALLERGIES_ID,
SurveyTemplateRepo.DIET_ID,
SurveyTemplateRepo.DETAILED_DIET_ID,
SurveyTemplateRepo.OTHER_ID])
self.assertListEqual([x["survey_template_id"] for x in doggy_surveys],
[2])
self.assertListEqual([x["survey_template_id"] for x in env_surveys],
[])
def _bobo_to_claim_a_sample(self):
resp = self.client.get(
'/api/accounts/%s/sources?language_tag=en_US' % ACCT_ID,
headers=MOCK_HEADERS
)
check_response(resp)
sources = json.loads(resp.data)
bobo = [x for x in sources if x['source_name'] == 'Bo'][0]
# claim a sample
resp = self.client.get(
'/api/kits/?language_tag=en_US&kit_name=%s' % SUPPLIED_KIT_ID,
headers=MOCK_HEADERS
)
check_response(resp)
unused_samples = json.loads(resp.data)
sample_id = unused_samples[0]['sample_id']
resp = self.client.post(
'/api/accounts/%s/sources/%s/samples?language_tag=en_US' %
(ACCT_ID, bobo['source_id']),
content_type='application/json',
data=json.dumps(
{
"sample_id": sample_id
}),
headers=MOCK_HEADERS
)
check_response(resp)
return bobo
def test_bobo_takes_vioscreen(self):
bobo = self._bobo_to_claim_a_sample()
# take vioscreen
resp = self.client.get(
'/api/accounts/%s/sources/%s/survey_templates/10001'
'?language_tag=en_US&vioscreen_ext_sample_id=%s'
'&survey_redirect_url=http://foo.bar' %
(ACCT_ID, bobo['source_id'], MOCK_SAMPLE_ID),
headers=MOCK_HEADERS
)
check_response(resp)
# "answer" the vioscreen survey. first, we're going to deconstruct
# the submitted key to obtain the survey ID. second, we need to
# reconstruct a key to simulate a payload we would receive from
# vioscreen. In the simulated key, we'll include status=3 which for
# vioscreen indicates a finished survey.
data = json.loads(resp.data)
url = data['survey_template_text']['url']
submitted_arguments = parse_qs(urlparse(url).query)
keydata = vioscreen.decode_key(submitted_arguments['Key'][0])
vio_info = {}
for keyval in keydata.decode("utf-8").split("&"):
key, val = keyval.split("=")
vio_info[key] = val
regcode = submitted_arguments['RegCode'][0]
completed_key = vioscreen.encrypt_key(vio_info['Username'],
vio_info['CultureCode'],
'http://foo.bar',
1,
vio_info['DOB'],
None,
None,
regcode,
["status=3", ])
resp = self.client.post(
'/api/accounts/%s/sources/%s/surveys'
'?language_tag=en_US' %
(ACCT_ID, bobo['source_id']),
content_type='application/json',
data=json.dumps(
{
"survey_template_id": SurveyTemplateRepo.VIOSCREEN_ID,
"survey_text": {'key': completed_key.decode('utf-8')}
}),
headers=MOCK_HEADERS
)
check_response(resp, 201)
resp = self.client.delete(
'/api/accounts/%s/sources/%s/samples/%s?language_tag=en_US' %
(ACCT_ID, bobo['source_id'], MOCK_SAMPLE_ID),
headers=MOCK_HEADERS
)
check_response(resp)
@skipIf(SERVER_CONFIG['myfoodrepo_url'] in ('', 'mfr_url_placeholder'),
"MFR secrets not provided")
def test_bobo_takes_myfoodrepo_with_slots(self):
bobo = self._bobo_to_claim_a_sample()
# take myfoodrepo
resp = self.client.get(
'/api/accounts/%s/sources/%s/survey_templates/10002'
'?language_tag=en_US'
'&survey_redirect_url=http://foo.bar' %
(ACCT_ID, bobo['source_id']),
headers=MOCK_HEADERS
)
check_response(resp)
data = json.loads(resp.data)
exp_start = SERVER_CONFIG['myfoodrepo_user_url']
url = data['survey_template_text']['url']
self.assertTrue(url.startswith(exp_start))
# we don't yet know how MFR wants subject ID encoded
# verify we err if we attempt to answer the survey. an "answer" here is
# undefined
resp = self.client.post(
'/api/accounts/%s/sources/%s/surveys'
'?language_tag=en_US' %
(ACCT_ID, bobo['source_id']),
content_type='application/json',
data=json.dumps(
{
"survey_template_id": SurveyTemplateRepo.MYFOODREPO_ID,
"survey_text": {'key': 'stuff'}
}),
headers=MOCK_HEADERS
)
check_response(resp, 404)
@skipIf(SERVER_CONFIG['myfoodrepo_url'] in ('', 'mfr_url_placeholder'),
"MFR secrets not provided")
def test_bobo_takes_myfoodrepo_without_slots(self):
bobo = self._bobo_to_claim_a_sample()
# modify the database to max out slots
with Transaction() as t:
slots = SERVER_CONFIG['myfoodrepo_slots']
cur = t.cursor()
cur.execute("""INSERT INTO ag.myfoodrepo_registry
(account_id, source_id)
SELECT account_id, id as source_id
FROM ag.source
WHERE account_id != %s
LIMIT %s""",
(ACCT_ID, slots))
t.commit()
# take myfoodrepo
resp = self.client.get(
'/api/accounts/%s/sources/%s/survey_templates/10002'
'?language_tag=en_US'
'&survey_redirect_url=http://foo.bar' %
(ACCT_ID, bobo['source_id']),
headers=MOCK_HEADERS
)
# we throw a 404 as a slot is "not found"
check_response(resp, 404)
data = json.loads(resp.data)
self.assertEqual(data['detail'], ("Sorry, but the annotators are "
"all allocated"))
# ...and clean up to be polite
with Transaction() as t:
cur = t.cursor()
cur.execute("""DELETE FROM ag.myfoodrepo_registry
WHERE myfoodrepo_id IS NULL""")
t.commit()
@skipIf(SERVER_CONFIG['polyphenol_ffq_url'] in ('', 'pffq_placeholder'),
"Polyphenol FFQ secrets not provided")
def test_bobo_takes_polyphenol_ffq(self):
bobo = self._bobo_to_claim_a_sample()
# take Polyphenol FFQ
resp = self.client.get(
'/api/accounts/%s/sources/%s/survey_templates/10003'
'?language_tag=en_US' %
(ACCT_ID, bobo['source_id']),
headers=MOCK_HEADERS
)
check_response(resp)
data = json.loads(resp.data)
exp_start = SERVER_CONFIG['polyphenol_ffq_url']
url = data['survey_template_text']['url']
self.assertTrue(url.startswith(exp_start))
# verify we err if we attempt to answer the survey. an "answer" here is
# undefined
resp = self.client.post(
'/api/accounts/%s/sources/%s/surveys'
'?language_tag=en_US' %
(ACCT_ID, bobo['source_id']),
content_type='application/json',
data=json.dumps(
{
"survey_template_id": SurveyTemplateRepo.POLYPHENOL_FFQ_ID,
"survey_text": {'key': 'stuff'}
}),
headers=MOCK_HEADERS
)
check_response(resp, 404)
@skipIf(SERVER_CONFIG['spain_ffq_url'] in ('', 'sffq_placeholder'),
"Spain FFQ secrets not provided")
def test_bobo_takes_spain_ffq(self):
bobo = self._bobo_to_claim_a_sample()
# take Spain FFQ
resp = self.client.get(
'/api/accounts/%s/sources/%s/survey_templates/10004'
'?language_tag=es_ES' %
(ACCT_ID, bobo['source_id']),
headers=MOCK_HEADERS
)
check_response(resp)
data = json.loads(resp.data)
exp_start = SERVER_CONFIG['spain_ffq_url']
url = data['survey_template_text']['url']
self.assertTrue(url.startswith(exp_start))
# verify we err if we attempt to answer the survey. an "answer" here is
# undefined
resp = self.client.post(
'/api/accounts/%s/sources/%s/surveys'
'?language_tag=en_US' %
(ACCT_ID, bobo['source_id']),
content_type='application/json',
data=json.dumps(
{
"survey_template_id": SurveyTemplateRepo.SPAIN_FFQ_ID,
"survey_text": {'key': 'stuff'}
}),
headers=MOCK_HEADERS
)
check_response(resp, 404)
def test_bobo_takes_all_local_surveys(self):
"""
Check that a user can login to an account,
list sources,
pick a source,
list surveys for that source,
for each local survey,
retrieve that survey
submit answers to that survey
"""
resp = self.client.get(
'/api/accounts/%s/sources?language_tag=en_US' % ACCT_ID,
headers=MOCK_HEADERS
)
check_response(resp)
sources = json.loads(resp.data)
bobo = [x for x in sources if x['source_name'] == 'Bo'][0]
resp = self.client.get(
'/api/accounts/%s/sources/%s/survey_templates?language_tag=en_US' %
(ACCT_ID, bobo['source_id']),
headers=MOCK_HEADERS
)
bobo_surveys = json.loads(resp.data)
for bobo_survey in bobo_surveys:
chosen_survey = bobo_survey["survey_template_id"]
# 10001, 10002, 10003, and 10004 are non-local surveys
# surveys 1-7 are no longer present, and reformulated into 10-21.
if chosen_survey in (1, 2, 3, 4, 5, 6, 7,
SurveyTemplateRepo.VIOSCREEN_ID,
SurveyTemplateRepo.MYFOODREPO_ID,
SurveyTemplateRepo.POLYPHENOL_FFQ_ID,
SurveyTemplateRepo.SPAIN_FFQ_ID,
SurveyTemplateRepo.BASIC_INFO_ID,
SurveyTemplateRepo.AT_HOME_ID,
SurveyTemplateRepo.LIFESTYLE_ID,
SurveyTemplateRepo.GUT_ID,
SurveyTemplateRepo.GENERAL_HEALTH_ID,
SurveyTemplateRepo.HEALTH_DIAG_ID,
SurveyTemplateRepo.ALLERGIES_ID,
SurveyTemplateRepo.DIET_ID,
SurveyTemplateRepo.DETAILED_DIET_ID,
SurveyTemplateRepo.MIGRAINE_ID,
SurveyTemplateRepo.SURFERS_ID,
SurveyTemplateRepo.COVID19_ID):
continue
resp = self.client.get(
'/api/accounts/%s/sources/%s/survey_templates/%s'
'?language_tag=en_US' %
(ACCT_ID, bobo['source_id'], chosen_survey),
headers=MOCK_HEADERS
)
check_response(resp)
model = fuzz_form(json.loads(resp.data)["survey_template_text"])
resp = self.client.post(
'/api/accounts/%s/sources/%s/surveys?language_tag=en_US'
% (ACCT_ID, bobo['source_id']),
content_type='application/json',
data=json.dumps(
{
'survey_template_id': chosen_survey,
'survey_text': model
}),
headers=MOCK_HEADERS
)
check_response(resp, 201)
loc = resp.headers.get("Location")
url = werkzeug.urls.url_parse(loc)
survey_id = url.path.split('/')[-1]
# TODO: Need a sanity check, is returned Location supposed to
# specify query parameters?
resp = self.client.get(loc + "?language_tag=en_US",
headers=MOCK_HEADERS
)
check_response(resp)
retrieved_survey = json.loads(resp.data)
# Retrieved surveys should have a survey_status field, though it is
# None for everything but vioscreen.
self.assertIn("survey_status", retrieved_survey)
self.assertDictEqual(retrieved_survey["survey_text"], model)
# Clean up after the new survey
with Transaction() as t:
repo = SurveyAnswersRepo(t)
found = repo.delete_answered_survey(ACCT_ID, survey_id)
self.assertTrue(found, "Couldn't find survey to delete, oops!")
t.commit()
def test_create_new_account(self):
# Clean up before the test in case we already have a janedoe
with Transaction() as t:
AccountRepo(t).delete_account_by_email(FAKE_EMAIL)
t.commit()
""" Test: Create a new account using a kit id """
acct_json = json.dumps(
{
"address": {
"city": "Springfield",
"country_code": "US",
"post_code": "12345",
"state": "CA",
"street": "123 Main St. E.",
"street2": "Apt. 2"
},
"email": FAKE_EMAIL,
"first_name": "Jane",
"last_name": "Doe",
"language": "en_US",
"consent_privacy_terms": True
})
# Registering with the authrocket associated with the mock account
# should fail
response = self.client.post(
'/api/accounts?language_tag=en_US',
content_type='application/json',
data=acct_json,
headers=MOCK_HEADERS
)
check_response(response, 422)
# Registering with a different authrocket should succeed
response = self.client.post(
'/api/accounts?language_tag=en_US',
content_type='application/json',
data=acct_json,
headers=MOCK_HEADERS_2
)
check_response(response)
# TODO: Is it weird that we return the new object AND its location?
# And should give us the account with ID and the location of it
loc = response.headers.get("Location")
url = werkzeug.urls.url_parse(loc)
acct_id_from_loc = url.path.split('/')[-1]
new_acct = json.loads(response.data)
acct_id_from_obj = new_acct['account_id']
self.assertIsNotNone(acct_id_from_loc,
"Couldn't retrieve acct from Location header")
self.assertEqual(acct_id_from_loc, acct_id_from_obj,
"Different account ids in location header and json "
"response")
# Registering again should fail with duplicate email 422
response = self.client.post(
'/api/accounts?language_tag=en_US',
content_type='application/json',
data=acct_json,
headers=MOCK_HEADERS_2
)
check_response(response, 422)
# Clean up after this test so we don't leave the account around
with Transaction() as t:
AccountRepo(t).delete_account_by_email(FAKE_EMAIL)
t.commit()
def test_edit_account_info(self):
""" Test: Can we edit account information """
response = self.client.get(
'/api/accounts/%s?language_tag=en_US' % (ACCT_ID,),
headers=MOCK_HEADERS)
check_response(response)
acc = json.loads(response.data)
regular_data = \
{
"account_id": "aaaaaaaa-bbbb-cccc-dddd-eeeeffffffff",
"account_type": "standard",
"address": {
"street": "123 Dan Lane",
"street2": "",
"city": "Danville",
"state": "CA",
"post_code": "12345",
"country_code": "US"
},
"email": "[email protected]",
"first_name": "Dan",
"last_name": "H",
"language": "en_US",
"consent_privacy_terms": True
}
# Hard to guess these two, so let's pop em out
acc.pop("creation_time")
acc.pop("update_time")
acc.pop("latitude")
acc.pop("longitude")
acc.pop("cannot_geocode")
acc.pop('kit_name')
self.assertDictEqual(acc, regular_data, "Check Initial Account Match")
regular_data.pop("account_id")
# Don't fuzz the email or kit_name -- changing the email in the
# accounts table without changing the email in the authorization causes
# authorization errors (as it should)
the_email = regular_data["email"]
fuzzy_data = fuzz(regular_data)
fuzzy_data['email'] = the_email
fuzzy_data['language'] = regular_data["language"]
# submit an invalid account type
fuzzy_data['account_type'] = "Voldemort"
print("---\nYou should see a validation error in unittest:")
response = self.client.put(
'/api/accounts/%s?language_tag=en_US' % (ACCT_ID,),
content_type='application/json',
data=json.dumps(fuzzy_data),
headers=MOCK_HEADERS
)
print("---")
# Check that malicious user can't write any field they want
check_response(response, 400)
# Check that data can be written once request is not malformed
fuzzy_data.pop('consent_privacy_terms')
fuzzy_data.pop('account_type')
response = self.client.put(
'/api/accounts/%s?language_tag=en_US' % (ACCT_ID,),
content_type='application/json',
data=json.dumps(fuzzy_data),
headers=MOCK_HEADERS
)
check_response(response)
acc = json.loads(response.data)
fuzzy_data['account_type'] = 'standard'
fuzzy_data["account_id"] = "aaaaaaaa-bbbb-cccc-dddd-eeeeffffffff"
acc.pop('creation_time')
acc.pop('update_time')
acc.pop("latitude")
acc.pop("longitude")
acc.pop("cannot_geocode")
acc.pop('kit_name')
acc.pop('consent_privacy_terms')
self.assertDictEqual(fuzzy_data, acc, "Check Fuzz Account Match")
# Attempt to restore back to old data.
regular_data.pop('account_type')
regular_data.pop('consent_privacy_terms')
response = self.client.put(
'/api/accounts/%s?language_tag=en_US' % (ACCT_ID,),
content_type='application/json',
data=json.dumps(regular_data),
headers=MOCK_HEADERS
)
check_response(response)
acc = json.loads(response.data)
acc.pop('creation_time')
acc.pop('update_time')
acc.pop("latitude")
acc.pop("longitude")
acc.pop("cannot_geocode")
acc.pop('kit_name')
regular_data['account_type'] = 'standard'
regular_data["account_id"] = "aaaaaaaa-bbbb-cccc-dddd-eeeeffffffff"
regular_data['consent_privacy_terms'] = True
self.assertDictEqual(regular_data, acc, "Check restore to regular")
def test_add_sample_from_kit(self):
""" We list the samples in a kit, grab an unassociated one,
and then associate that sample with our account
"""
response = self.client.get(
'/api/kits/?language_tag=en_US&kit_name=%s' % SUPPLIED_KIT_ID,
headers=MOCK_HEADERS)
check_response(response)
unused_samples = json.loads(response.data)
sample_id = unused_samples[0]['sample_id']
response = self.client.post(
'/api/accounts/%s/sources/%s/samples?language_tag=en_US' %
(ACCT_ID, DOGGY_ID),
content_type='application/json',
data=json.dumps(
{
"sample_id": sample_id
}),
headers=MOCK_HEADERS
)
check_response(response)
# Check that we can now see this sample in the list
response = self.client.get(
'/api/accounts/%s/sources/%s/samples?language_tag=en_US' %
(ACCT_ID, DOGGY_ID),
headers=MOCK_HEADERS
)
check_response(response)
dog_samples = json.loads(response.data)
self.assertIn(sample_id, [x["sample_id"] for x in dog_samples])
# Check that we can now see this sample individually
response = self.client.get(
'/api/accounts/%s/sources/%s/samples/%s?language_tag=en_US' %
(ACCT_ID, DOGGY_ID, sample_id),
headers=MOCK_HEADERS
)
check_response(response)
# Check that we can't see this sample from outside the account/source
response = self.client.get(
'/api/accounts/%s/sources/%s/samples/%s?language_tag=en_US' %
(NOT_ACCT_ID, DOGGY_ID, sample_id),
headers=MOCK_HEADERS
)
check_response(response, 404)
response = self.client.get(
'/api/accounts/%s/sources/%s/samples/%s?language_tag=en_US' %
(ACCT_ID, HUMAN_ID, sample_id),
headers=MOCK_HEADERS
)
check_response(response, 404)
def test_create_non_human_sources(self):
# TODO: Looks like the 201 for sources are specified to
# both return a Location header and the newly created object. This
# seems inconsistent maybe? Consistent with Account, inconsistent
# with survey_answers and maybe source+sample associations? What's
# right?
kitty = {
"source_type": "animal",
"source_name": "Fluffy",