-
Notifications
You must be signed in to change notification settings - Fork 2
/
run_tests.py
1642 lines (1377 loc) · 72.4 KB
/
run_tests.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
"""
Run integration tests against backend api endpoints.
Deleting from db is currently not supported, objects added to db in different
should be taken into account.
"""
import asyncio
import json
import logging
import os
import re
import urllib
import xml.etree.ElementTree as ET
from datetime import datetime
from pathlib import Path
from uuid import uuid4
import aiofiles
import aiohttp
from aiohttp import FormData
from motor.motor_asyncio import AsyncIOMotorClient
# === Global vars ===
FORMAT = "[%(asctime)s][%(name)s][%(process)d %(processName)s][%(levelname)-8s](L:%(lineno)s) %(funcName)s: %(message)s"
logging.basicConfig(format=FORMAT, datefmt="%Y-%m-%d %H:%M:%S")
LOG = logging.getLogger(__name__)
LOG.setLevel(logging.DEBUG)
testfiles_root = Path(__file__).parent.parent / "test_files"
test_xml_files = [
("study", "SRP000539.xml"),
("sample", "SRS001433.xml"),
("run", "ERR000076.xml"),
("experiment", "ERX000119.xml"),
("experiment", "paired.xml"),
("experiment", "sample_description.xml"),
("analysis", "ERZ266973.xml"),
("analysis", "processed_reads_analysis.xml"),
("analysis", "reference_alignment_analysis.xml"),
("analysis", "reference_sequence_analysis.xml"),
("analysis", "sequence_assembly_analysis.xml"),
("analysis", "sequence_variation_analysis.xml"),
("dac", "dac.xml"),
("policy", "policy.xml"),
("dataset", "dataset.xml"),
]
test_json_files = [
("study", "SRP000539.json", "SRP000539.json"),
("sample", "SRS001433.json", "SRS001433.json"),
("run", "ERR000076.json", "ERR000076.json"),
("experiment", "ERX000119.json", "ERX000119.json"),
("analysis", "ERZ266973.json", "ERZ266973.json"),
]
base_url = os.getenv("BASE_URL", "http://localhost:5430")
mock_auth_url = os.getenv("OIDC_URL_TEST", "http://localhost:8000")
objects_url = f"{base_url}/objects"
drafts_url = f"{base_url}/drafts"
templates_url = f"{base_url}/templates"
folders_url = f"{base_url}/folders"
users_url = f"{base_url}/users"
submit_url = f"{base_url}/submit"
publish_url = f"{base_url}/publish"
# to form direct contact to db with create_folder()
DATABASE = os.getenv("MONGO_DATABASE", "default")
AUTHDB = os.getenv("MONGO_AUTHDB", "admin")
HOST = os.getenv("MONGO_HOST", "localhost:27017")
TLS = os.getenv("MONGO_SSL", False)
user_id = "current"
test_user_given = "Given"
test_user_family = "Family"
test_user = "[email protected]"
other_test_user_given = "Mock"
other_test_user_family = "Family"
other_test_user = "[email protected]"
# === Helper functions ===
async def login(sess, sub, given, family):
"""Mock login."""
params = {
"sub": sub,
"family": family,
"given": given,
}
# Prepare response
url = f"{mock_auth_url}/setmock?{urllib.parse.urlencode(params)}"
async with sess.get(f"{url}"):
LOG.debug("Setting mock user")
async with sess.get(f"{base_url}/aai"):
LOG.debug("Doing mock user login")
async def create_request_data(schema, filename):
"""Create request data from pairs of schemas and filenames.
:param schema: name of the schema (folder) used for testing
:param filename: name of the file used for testing.
"""
request_data = FormData()
path_to_file = testfiles_root / schema / filename
path = path_to_file.as_posix()
async with aiofiles.open(path, mode="r") as f:
c_type = "text/xml" if filename[-3:] == "xml" else "text/csv"
request_data.add_field(schema.upper(), await f.read(), filename=filename, content_type=c_type)
return request_data
async def create_multi_file_request_data(filepairs):
"""Create request data with multiple files.
:param filepairs: tuple containing pairs of schemas and filenames used for testing
"""
request_data = FormData()
for schema, filename in filepairs:
path_to_file = testfiles_root / schema / filename
path = path_to_file.as_posix()
async with aiofiles.open(path, mode="r") as f:
request_data.add_field(
schema.upper(),
await f.read(),
filename=filename,
content_type="text/xml",
)
return request_data
async def create_request_json_data(schema, filename):
"""Create request data from pairs of schemas and filenames.
:param schema: name of the schema (folder) used for testing
:param filename: name of the file used for testing.
"""
path_to_file = testfiles_root / schema / filename
path = path_to_file.as_posix()
async with aiofiles.open(path, mode="r") as f:
request_data = await f.read()
return request_data
async def post_object(sess, schema, folder_id, filename):
"""Post one metadata object within session, returns accessionId.
:param sess: HTTP session in which request call is made
:param schema: name of the schema (folder) used for testing
:param filename: name of the file used for testing.
"""
request_data = await create_request_data(schema, filename)
async with sess.post(f"{objects_url}/{schema}", params={"folder": folder_id}, data=request_data) as resp:
LOG.debug(f"Adding new object to {schema}, via XML/CSV file {filename}")
assert resp.status == 201, f"HTTP Status code error, got {resp.status}"
ans = await resp.json()
return ans if isinstance(ans, list) else ans["accessionId"], schema
async def post_object_expect_status(sess, schema, folder_id, filename, status):
"""Post one metadata object within session, returns accessionId.
:param sess: HTTP session in which request call is made
:param schema: name of the schema (folder) used for testing
:param filename: name of the file used for testing.
"""
request_data = await create_request_data(schema, filename)
async with sess.post(f"{objects_url}/{schema}", params={"folder": folder_id}, data=request_data) as resp:
LOG.debug(f"Adding new object to {schema}, via XML/CSV file {filename} and expecting status: {status}")
assert resp.status == status, f"HTTP Status code error, got {resp.status}"
if status < 400:
ans = await resp.json()
return ans if isinstance(ans, list) else ans["accessionId"], schema
async def post_object_json(sess, schema, folder_id, filename):
"""Post & put one metadata object within session, returns accessionId.
:param sess: HTTP session in which request call is made
:param schema: name of the schema (folder) used for testing
:param filename: name of the file used for testing.
"""
request_data = await create_request_json_data(schema, filename)
async with sess.post(f"{objects_url}/{schema}", params={"folder": folder_id}, data=request_data) as resp:
LOG.debug(f"Adding new object to {schema}, via JSON file {filename}")
assert resp.status == 201, f"HTTP Status code error, got {resp.status}"
ans = await resp.json()
return ans["accessionId"]
async def delete_object(sess, schema, accession_id):
"""Delete metadata object within session.
:param sess: HTTP session in which request call is made
:param schema: name of the schema (folder) used for testing
:param accession_id: id of the object
"""
async with sess.delete(f"{objects_url}/{schema}/{accession_id}") as resp:
LOG.debug(f"Deleting object {accession_id} from {schema}")
assert resp.status == 204, f"HTTP Status code error, got {resp.status}"
async def post_draft(sess, schema, folder_id, filename):
"""Post one draft metadata object within session, returns accessionId.
:param sess: HTTP session in which request call is made
:param schema: name of the schema (folder) used for testing
:param filename: name of the file used for testing.
"""
request_data = await create_request_data(schema, filename)
async with sess.post(f"{drafts_url}/{schema}", params={"folder": folder_id}, data=request_data) as resp:
LOG.debug(f"Adding new draft object to {schema}, via XML file {filename}")
assert resp.status == 201, f"HTTP Status code error, got {resp.status}"
ans = await resp.json()
return ans["accessionId"]
async def post_draft_json(sess, schema, folder_id, filename):
"""Post & put one metadata object within session, returns accessionId.
:param sess: HTTP session in which request call is made
:param schema: name of the schema (folder) used for testing
:param filename: name of the file used for testing.
"""
request_data = await create_request_json_data(schema, filename)
async with sess.post(f"{drafts_url}/{schema}", params={"folder": folder_id}, data=request_data) as resp:
LOG.debug(f"Adding new draft object to {schema}, via JSON file {filename}")
assert resp.status == 201, f"HTTP Status code error, got {resp.status}"
ans = await resp.json()
return ans["accessionId"]
async def get_draft(sess, schema, draft_id, expected_status=200):
"""Get and return a drafted metadata object.
:param sess: HTTP session in which request call is made
:param schema: name of the schema (folder) used for testing
:param draft_id: id of the draft
"""
async with sess.get(f"{drafts_url}/{schema}/{draft_id}") as resp:
LOG.debug(f"Checking that {draft_id} JSON exists")
assert resp.status == expected_status, f"HTTP Status code error, got {resp.status}"
ans = await resp.json()
return json.dumps(ans)
async def put_draft(sess, schema, draft_id, update_filename):
"""Put one metadata object within session, returns accessionId.
:param sess: HTTP session in which request call is made
:param schema: name of the schema (folder) used for testing
:param draft_id: id of the draft
:param update_filename: name of the file used to use for updating data.
"""
request_data = await create_request_json_data(schema, update_filename)
async with sess.put(f"{drafts_url}/{schema}/{draft_id}", data=request_data) as resp:
LOG.debug(f"Replace draft object in {schema}")
assert resp.status == 200, f"HTTP Status code error, got {resp.status}"
ans_put = await resp.json()
assert ans_put["accessionId"] == draft_id, "accession ID error"
return ans_put["accessionId"]
async def put_object_json(sess, schema, accession_id, update_filename):
"""Put one metadata object within session, returns accessionId.
:param sess: HTTP session in which request call is made
:param schema: name of the schema (folder) used for testing
:param draft_id: id of the draft
:param update_filename: name of the file used to use for updating data.
"""
request_data = await create_request_json_data(schema, update_filename)
async with sess.put(f"{objects_url}/{schema}/{accession_id}", data=request_data) as resp:
LOG.debug(f"Try to replace object in {schema}")
assert resp.status == 415, f"HTTP Status code error, got {resp.status}"
async def put_object_xml(sess, schema, accession_id, update_filename):
"""Put one metadata object within session, returns accessionId.
:param sess: HTTP session in which request call is made
:param schema: name of the schema (folder) used for testing
:param draft_id: id of the draft
:param update_filename: name of the file used to use for updating data.
"""
request_data = await create_request_data(schema, update_filename)
async with sess.put(f"{objects_url}/{schema}/{accession_id}", data=request_data) as resp:
LOG.debug(f"Replace object with XML data in {schema}")
assert resp.status == 200, f"HTTP Status code error, got {resp.status}"
ans_put = await resp.json()
assert ans_put["accessionId"] == accession_id, "accession ID error"
return ans_put["accessionId"]
async def patch_draft(sess, schema, draft_id, update_filename):
"""Patch one metadata object within session, return accessionId.
:param sess: HTTP session in which request call is made
:param schema: name of the schema (folder) used for testing
:param draft_id: id of the draft
:param update_filename: name of the file used to use for updating data.
"""
request_data = await create_request_json_data(schema, update_filename)
async with sess.patch(f"{drafts_url}/{schema}/{draft_id}", data=request_data) as resp:
LOG.debug(f"Update draft object in {schema}")
assert resp.status == 200, f"HTTP Status code error, got {resp.status}"
ans_put = await resp.json()
assert ans_put["accessionId"] == draft_id, "accession ID error"
return ans_put["accessionId"]
async def delete_draft(sess, schema, draft_id):
"""Delete metadata object within session.
:param sess: HTTP session in which request call is made
:param schema: name of the schema (folder) used for testing
:param draft_id: id of the draft
"""
async with sess.delete(f"{drafts_url}/{schema}/{draft_id}") as resp:
LOG.debug(f"Deleting draft object {draft_id} from {schema}")
assert resp.status == 204, f"HTTP Status code error, got {resp.status}"
async def post_template_json(sess, schema, filename):
"""Post one metadata object within session, returns accessionId.
:param sess: HTTP session in which request call is made
:param schema: name of the schema (folder) used for testing
:param filename: name of the file used for testing.
"""
request_data = await create_request_json_data(schema, filename)
async with sess.post(f"{templates_url}/{schema}", data=request_data) as resp:
LOG.debug(f"Adding new template object to {schema}, via JSON file {filename}")
assert resp.status == 201, f"HTTP Status code error, got {resp.status}"
ans = await resp.json()
if isinstance(ans, list):
return ans
else:
return ans["accessionId"]
async def get_template(sess, schema, template_id):
"""Get and return a drafted metadata object.
:param sess: HTTP session in which request call is made
:param schema: name of the schema (folder) used for testing
:param template_id: id of the draft
"""
async with sess.get(f"{templates_url}/{schema}/{template_id}") as resp:
LOG.debug(f"Checking that {template_id} JSON exists")
assert resp.status == 200, f"HTTP Status code error, got {resp.status}"
ans = await resp.json()
return json.dumps(ans)
async def patch_template(sess, schema, template_id, update_filename):
"""Patch one metadata object within session, return accessionId.
:param sess: HTTP session in which request call is made
:param schema: name of the schema (folder) used for testing
:param template_id: id of the draft
:param update_filename: name of the file used to use for updating data.
"""
request_data = await create_request_json_data(schema, update_filename)
async with sess.patch(f"{templates_url}/{schema}/{template_id}", data=request_data) as resp:
LOG.debug(f"Update draft object in {schema}")
assert resp.status == 200, f"HTTP Status code error, got {resp.status}"
ans_put = await resp.json()
assert ans_put["accessionId"] == template_id, "accession ID error"
return ans_put["accessionId"]
async def delete_template(sess, schema, template_id):
"""Delete metadata object within session.
:param sess: HTTP session in which request call is made
:param schema: name of the schema (folder) used for testing
:param template_id: id of the draft
"""
async with sess.delete(f"{templates_url}/{schema}/{template_id}") as resp:
LOG.debug(f"Deleting template object {template_id} from {schema}")
assert resp.status == 204, f"HTTP Status code error, got {resp.status}"
async def post_folder(sess, data):
"""Post one object folder within session, returns folderId.
:param sess: HTTP session in which request call is made
:param data: data used to update the folder
"""
async with sess.post(f"{folders_url}", data=json.dumps(data)) as resp:
LOG.debug("Adding new folder")
ans = await resp.json()
assert resp.status == 201, f"HTTP Status code error {resp.status} {ans}"
return ans["folderId"]
async def patch_folder(sess, folder_id, json_patch):
"""Patch one object folder within session, return folderId.
:param sess: HTTP session in which request call is made
:param folder_id: id of the folder
:param json_patch: JSON Patch object to use in PATCH call
"""
async with sess.patch(f"{folders_url}/{folder_id}", data=json.dumps(json_patch)) as resp:
LOG.debug(f"Updating folder {folder_id}")
assert resp.status == 200, f"HTTP Status code error, got {resp.status}"
ans_patch = await resp.json()
assert ans_patch["folderId"] == folder_id, "folder ID error"
return ans_patch["folderId"]
async def publish_folder(sess, folder_id):
"""Publish one object folder within session, return folderId.
:param sess: HTTP session in which request call is made
:param folder_id: id of the folder
"""
async with sess.patch(f"{publish_url}/{folder_id}") as resp:
LOG.debug(f"Publishing folder {folder_id}")
assert resp.status == 200, f"HTTP Status code error, got {resp.status}"
ans = await resp.json()
assert ans["folderId"] == folder_id, "folder ID error"
return ans["folderId"]
async def delete_folder(sess, folder_id):
"""Delete object folder within session.
:param sess: HTTP session in which request call is made
:param folder_id: id of the folder
"""
async with sess.delete(f"{folders_url}/{folder_id}") as resp:
LOG.debug(f"Deleting folder {folder_id}")
assert resp.status == 204, f"HTTP Status code error, got {resp.status}"
async def delete_folder_publish(sess, folder_id):
"""Delete object folder within session.
:param sess: HTTP session in which request call is made
:param folder_id: id of the folder
"""
async with sess.delete(f"{folders_url}/{folder_id}") as resp:
LOG.debug(f"Deleting folder {folder_id}")
assert resp.status == 401, f"HTTP Status code error, got {resp.status}"
async def create_folder(data, user):
"""Create new object folder to database.
:param data: Data as dict to be saved to database
:param user: User id to which data is assigned
:returns: Folder id for the folder inserted to database
"""
LOG.info("Creating new folder")
url = f"mongodb://{AUTHDB}:{AUTHDB}@{HOST}/{DATABASE}?authSource=admin"
db_client = AsyncIOMotorClient(url, connectTimeoutMS=1000, serverSelectionTimeoutMS=1000)
database = db_client[DATABASE]
folder_id = uuid4().hex
data["folderId"] = folder_id
data["text_name"] = " ".join(re.split("[\\W_]", data["name"]))
data["drafts"] = []
data["metadataObjects"] = []
try:
await database["folder"].insert_one(data)
find_by_id = {"userId": user}
append_op = {"$push": {"folders": {"$each": [folder_id], "$position": 0}}}
await database["user"].find_one_and_update(
find_by_id, append_op, projection={"_id": False}, return_document=True
)
return folder_id
except Exception as e:
LOG.error(f"Folder creation failed due to {str(e)}")
async def patch_user(sess, user_id, real_user_id, json_patch):
"""Patch one user object within session, return userId.
:param sess: HTTP session in which request call is made
:param user_id: id of the user (current)
:param real_user_id: id of the user in the database
:param json_patch: JSON Patch object to use in PATCH call
"""
async with sess.patch(f"{users_url}/current", data=json.dumps(json_patch)) as resp:
LOG.debug(f"Updating user {real_user_id}")
assert resp.status == 200, f"HTTP Status code error, got {resp.status}"
ans_patch = await resp.json()
assert ans_patch["userId"] == real_user_id, "user ID error"
return ans_patch["userId"]
async def delete_user(sess, user_id):
"""Delete user object within session.
:param sess: HTTP session in which request call is made
:param user_id: id of the user (current)
"""
async with sess.delete(f"{users_url}/current") as resp:
LOG.debug(f"Deleting user {user_id}")
# we expect 404 as there is no frontend
assert str(resp.url) == f"{base_url}/", "redirect url user delete differs"
assert resp.status == 404, f"HTTP Status code error, got {resp.status}"
def extract_folders_object(res, accession_id, draft):
"""Extract object from folder metadataObjects with provided accessionId.
:param res: JSON parsed responce from folder query request
:param accession_id: accession ID of reviwed object
:returns: dict of object entry in folder
"""
object = "drafts" if draft else "metadataObjects"
actual_res = next(obj for obj in res[object] if obj["accessionId"] == accession_id)
return actual_res
async def check_folders_object_patch(sess, folder_id, schema, accession_id, title, filename, draft=False):
"""Check that draft is added correctly to folder.
Get draft or metadata object from the folder and assert with data
returned from object endpoint itself.
:param sess: HTTP session in which request call is made
:param folder_id: id of the folder
:param schema: name of the schema (folder) used for testing
:param accession_id: accession ID of reviwed object
:param title: title of reviwed object
:param filename: name of the file used for inserting data
:param draft: indication of object draft status, default False
"""
sub_type = "Form" if filename.split(".")[-1] == "json" else filename.split(".")[-1].upper()
async with sess.get(f"{folders_url}/{folder_id}") as resp:
res = await resp.json()
try:
actual = extract_folders_object(res, accession_id, draft)
expected = {
"accessionId": accession_id,
"schema": schema if not draft else f"draft-{schema}",
"tags": {
"submissionType": sub_type,
"displayTitle": title,
"fileName": filename,
},
}
if sub_type == "Form":
del expected["tags"]["fileName"]
assert actual == expected, "actual end expected data did not match"
except StopIteration:
pass
return schema
# === Integration tests ===
async def test_crud_works(sess, schema, filename, folder_id):
"""Test REST api POST, GET and DELETE reqs.
Tries to create new object, gets accession id and checks if correct
resource is returned with that id. Finally deletes the object and checks it
was deleted.
:param sess: HTTP session in which request call is made
:param schema: name of the schema (folder) used for testing
:param filename: name of the file used for testing
:param folder_id: id of the folder used to group submission
"""
accession_id = await post_object(sess, schema, folder_id, filename)
async with sess.get(f"{objects_url}/{schema}/{accession_id[0]}") as resp:
LOG.debug(f"Checking that {accession_id[0]} JSON is in {schema}")
assert resp.status == 200, f"HTTP Status code error, got {resp.status}"
res = await resp.json()
title = res["descriptor"].get("studyTitle", "") if schema == "study" else res.get("title", "")
await check_folders_object_patch(sess, folder_id, schema, accession_id[0], title, filename)
async with sess.get(f"{objects_url}/{schema}/{accession_id[0]}?format=xml") as resp:
LOG.debug(f"Checking that {accession_id[0]} XML is in {schema}")
assert resp.status == 200, f"HTTP Status code error, got {resp.status}"
await delete_object(sess, schema, accession_id[0])
async with sess.get(f"{objects_url}/{schema}/{accession_id[0]}") as resp:
LOG.debug(f"Checking that JSON object {accession_id[0]} was deleted")
assert resp.status == 404, f"HTTP Status code error, got {resp.status}"
async with sess.get(f"{objects_url}/{schema}/{accession_id[0]}?format=xml") as resp:
LOG.debug(f"Checking that XML object {accession_id[0]} was deleted")
assert resp.status == 404, f"HTTP Status code error, got {resp.status}"
async with sess.get(f"{folders_url}/{folder_id}") as resp:
LOG.debug(f"Checking that object {accession_id[0]} was deleted from folder {folder_id}")
res = await resp.json()
expected_true = not any(d["accessionId"] == accession_id[0] for d in res["metadataObjects"])
assert expected_true, f"object {accession_id[0]} still exists"
async def test_csv(sess, folder_id):
"""Test CRUD for a submitted CSV file.
Test tries with good csv file first for sample object, after which we try with empty file.
After this we try with study object which is not allowed.
:param sess: HTTP session in which request call is made
:param schema: name of the schema (folder) used for testing
:param filename: name of the file used for testing
:param folder_id: id of the folder used to group submission
"""
_schema = "sample"
_filename = "EGAformat.csv"
accession_id = await post_object(sess, _schema, folder_id, _filename)
# there are 3 rows and we expected to get 3rd
assert len(accession_id[0]) == 3, f"expected nb of CSV entries does not match, we got: {len(accession_id)}"
_first_csv_row_id = accession_id[0][0]["accessionId"]
async with sess.get(f"{objects_url}/{_schema}/{_first_csv_row_id}") as resp:
LOG.debug(f"Checking that {_first_csv_row_id} JSON is in {_schema}")
assert resp.status == 200, f"HTTP Status code error, got {resp.status}"
res = await resp.json()
title = res.get("title", "")
await check_folders_object_patch(sess, folder_id, _schema, accession_id, title, _filename)
await delete_object(sess, _schema, _first_csv_row_id)
async with sess.get(f"{objects_url}/{_schema}/{_first_csv_row_id}") as resp:
LOG.debug(f"Checking that JSON object {_first_csv_row_id} was deleted")
assert resp.status == 404, f"HTTP Status code error, got {resp.status}"
async with sess.get(f"{folders_url}/{folder_id}") as resp:
LOG.debug(f"Checking that object {_first_csv_row_id} was deleted from folder {folder_id}")
res = await resp.json()
expected_true = not any(d["accessionId"] == _first_csv_row_id for d in res["metadataObjects"])
assert expected_true, f"object {_first_csv_row_id} still exists"
_filename = "empty.csv"
# status should be 400
await post_object_expect_status(sess, _schema, folder_id, _filename, 400)
_filename = "EGA_sample_w_issue.csv"
# status should be 201 but we expect 3 rows, as the CSV has 4 rows one of which is empty
accession_id = await post_object_expect_status(sess, _schema, folder_id, _filename, 201)
assert len(accession_id[0]) == 3, f"expected nb of CSV entries does not match, we got: {len(accession_id)}"
async def test_put_objects(sess, folder_id):
"""Test PUT reqs.
Tries to create new object, gets accession id and checks if correct
resource is returned with that id. Try to use PUT with JSON and expect failure,
try to use PUT with XML and expect success.
:param sess: HTTP session in which request call is made
:param folder_id: id of the folder used to group submission
"""
accession_id = await post_object(sess, "study", folder_id, "SRP000539.xml")
await put_object_json(sess, "study", accession_id[0], "SRP000539.json")
await put_object_xml(sess, "study", accession_id[0], "SRP000539_put.xml")
await check_folders_object_patch(
sess,
folder_id,
"study",
accession_id,
"Highly integrated epigenome maps in Arabidopsis - whole genome shotgun bisulfite sequencing",
"SRP000539_put.xml",
)
async def test_crud_drafts_works(sess, schema, orginal_file, update_file, folder_id):
"""Test drafts REST api POST, PUT and DELETE reqs.
Tries to create new draft object, gets accession id and checks if correct
resource is returned with that id. Finally deletes the object and checks it
was deleted.
:param sess: HTTP session in which request call is made
:param schema: name of the schema (folder) used for testing
:param orginal_file: name of the file used for creating object.
:param update_file: name of the file used for updating object.
:param folder_id: id of the folder used to group submission objects
"""
draft_id = await post_draft_json(sess, schema, folder_id, orginal_file)
async with sess.get(f"{drafts_url}/{schema}/{draft_id}") as resp:
assert resp.status == 200, f"HTTP Status code error, got {resp.status}"
res = await resp.json()
title = res["descriptor"]["studyTitle"] if schema == "study" else res.get("title", "")
await check_folders_object_patch(sess, folder_id, draft_id, schema, title, orginal_file, draft=True)
accession_id = await put_draft(sess, schema, draft_id, update_file)
async with sess.get(f"{drafts_url}/{schema}/{accession_id}") as resp:
LOG.debug(f"Checking that {accession_id} JSON is in {schema}")
assert resp.status == 200, f"HTTP Status code error, got {resp.status}"
res = await resp.json()
title = res["descriptor"]["studyTitle"] if schema == "study" else res.get("title", "")
await check_folders_object_patch(sess, folder_id, schema, accession_id, title, update_file, draft=True)
await delete_draft(sess, schema, accession_id)
async with sess.get(f"{drafts_url}/{schema}/{accession_id}") as resp:
LOG.debug(f"Checking that JSON object {accession_id} was deleted")
assert resp.status == 404, f"HTTP Status code error, got {resp.status}"
async with sess.get(f"{folders_url}/{folder_id}") as resp:
LOG.debug(f"Checking that JSON object {accession_id} was deleted from folder {folder_id}")
res = await resp.json()
expected_true = not any(d["accessionId"] == accession_id for d in res["drafts"])
assert expected_true, f"draft object {accession_id} still exists"
async def test_patch_drafts_works(sess, schema, orginal_file, update_file, folder_id):
"""Test REST api POST, PATCH and DELETE reqs.
Tries to create put and patch object, gets accession id and
checks if correct resource is returned with that id.
Finally deletes the object and checks it was deleted.
:param sess: HTTP session in which request call is made
:param schema: name of the schema (folder) used for testing
:param orginal_file: name of the file used for creating object.
:param update_file: name of the file used for updating object.
:param folder_id: id of the folder used to group submission objects
"""
draft_id = await post_draft_json(sess, schema, folder_id, orginal_file)
accession_id = await patch_draft(sess, schema, draft_id, update_file)
async with sess.get(f"{drafts_url}/{schema}/{accession_id}") as resp:
LOG.debug(f"Checking that {accession_id} JSON is in {schema}")
res = await resp.json()
title = res["descriptor"]["studyTitle"] if schema == "study" else res.get("title", None)
assert res["centerName"] == "GEOM", "object centerName content mismatch"
assert res["alias"] == "GSE10968", "object alias content mismatch"
assert resp.status == 200, f"HTTP Status code error, got {resp.status}"
await check_folders_object_patch(sess, folder_id, schema, accession_id, title, update_file, draft=True)
await delete_draft(sess, schema, accession_id)
async with sess.get(f"{drafts_url}/{schema}/{accession_id}") as resp:
LOG.debug(f"Checking that JSON object {accession_id} was deleted")
assert resp.status == 404, f"HTTP Status code error, got {resp.status}"
async def test_querying_works(sess, folder_id):
"""Test query endpoint with working and failing query.
:param sess: HTTP session in which request call is made
:param folder_id: id of the folder used to group submission objects
"""
files = await asyncio.gather(
*[post_object(sess, schema, folder_id, filename) for schema, filename in test_xml_files]
)
queries = {
"study": [
("studyTitle", "integrated"),
("studyType", "Other"),
("studyAbstract", "arabidopsis thaliana"),
("studyAttributes", "prjna107265"),
("studyAttributes", "parent_bioproject"),
],
"sample": [
("title", "HapMap sample"),
("description", "human hapmap individual"),
("centerName", "hapmap"),
("sampleName", "homo sapiens"),
("scientificName", "homo sapiens"),
("sampleName", 9606),
],
"run": [
("fileType", "srf"),
("experimentReference", "g1k-bgi-na18542"),
("experimentReference", "erx000037"),
],
"experiment": [("studyReference", "1000Genomes project pilot")],
"analysis": [
("fileType", "other"),
("studyReference", "HipSci___RNAseq___"),
("sampleReference", "HPSI0114i-eipl_3"),
],
}
async def do_one_query(schema, key, value, expected_status):
async with sess.get(f"{objects_url}/{schema}?{key}={value}") as resp:
assert resp.status == expected_status, f"HTTP Status code error, got {resp.status}"
for schema, schema_queries in queries.items():
LOG.debug(f"Querying {schema} collection with working params")
await asyncio.gather(*[do_one_query(schema, key, value, 200) for key, value in schema_queries])
LOG.debug("Querying {schema} collection with non-working params")
invalid = "yoloswaggings"
await asyncio.gather(*[do_one_query(schema, key, invalid, 404) for key, _ in schema_queries])
await asyncio.gather(*[delete_object(sess, schema, accession_id) for accession_id, schema in files])
async def test_getting_all_objects_from_schema_works(sess, folder_id):
"""Check that /objects/study returns objects with correct pagination.
:param sess: HTTP session in which request call is made
:param folder_id: id of the folder used to group submission objects
"""
# Add objects
files = await asyncio.gather(*[post_object(sess, "study", folder_id, "SRP000539.xml") for _ in range(13)])
# Test default values
async with sess.get(f"{objects_url}/study") as resp:
assert resp.status == 200
ans = await resp.json()
assert ans["page"]["page"] == 1
assert ans["page"]["size"] == 10
assert ans["page"]["totalPages"] == 2
assert ans["page"]["totalObjects"] == 14
assert len(ans["objects"]) == 10
# Test with custom pagination values
async with sess.get(f"{objects_url}/study?page=2&per_page=3") as resp:
assert resp.status == 200
ans = await resp.json()
assert ans["page"]["page"] == 2
assert ans["page"]["size"] == 3
assert ans["page"]["totalPages"] == 5
assert ans["page"]["totalObjects"] == 14
assert len(ans["objects"]) == 3
# Test with wrong pagination values
async with sess.get(f"{objects_url}/study?page=-1") as resp:
assert resp.status == 400
async with sess.get(f"{objects_url}/study?per_page=0") as resp:
assert resp.status == 400
# Delete objects
await asyncio.gather(*[delete_object(sess, "study", accession_id) for accession_id, _ in files])
async def test_crud_folders_works(sess):
"""Test folders REST api POST, GET, PATCH, PUBLISH and DELETE reqs.
:param sess: HTTP session in which request call is made
"""
# Create new folder and check its creation succeeded
folder_data = {"name": "Mock Folder", "description": "Mock Base folder to folder ops"}
folder_id = await post_folder(sess, folder_data)
async with sess.get(f"{folders_url}/{folder_id}") as resp:
LOG.debug(f"Checking that folder {folder_id} was created")
assert resp.status == 200, f"HTTP Status code error, got {resp.status}"
# Create draft from test XML file and patch the draft into the newly created folder
draft_id = await post_draft(sess, "sample", folder_id, "SRS001433.xml")
async with sess.get(f"{folders_url}/{folder_id}") as resp:
LOG.debug(f"Checking that folder {folder_id} was patched")
res = await resp.json()
assert res["folderId"] == folder_id, "expected folder id does not match"
assert res["name"] == folder_data["name"], "expected folder name does not match"
assert res["description"] == folder_data["description"], "folder description content mismatch"
assert res["published"] is False, "folder is published, expected False"
assert res["drafts"] == [
{
"accessionId": draft_id,
"schema": "draft-sample",
"tags": {
"submissionType": "XML",
"displayTitle": "HapMap sample from Homo sapiens",
"fileName": "SRS001433.xml",
},
}
], "folder drafts content mismatch"
assert res["metadataObjects"] == [], "there are objects in folder, expected empty"
# Get the draft from the collection within this session and post it to objects collection
draft_data = await get_draft(sess, "sample", draft_id)
async with sess.post(f"{objects_url}/sample", params={"folder": folder_id}, data=draft_data) as resp:
LOG.debug("Adding draft to actual objects")
assert resp.status == 201, f"HTTP Status code error, got {resp.status}"
ans = await resp.json()
assert ans["accessionId"] != draft_id, "draft id does not match expected"
accession_id = ans["accessionId"]
async with sess.get(f"{folders_url}/{folder_id}") as resp:
LOG.debug(f"Checking that folder {folder_id} was patched")
res = await resp.json()
assert res["folderId"] == folder_id, "expected folder id does not match"
assert res["published"] is False, "folder is published, expected False"
assert "datePublished" not in res.keys()
assert res["drafts"] == [
{
"accessionId": draft_id,
"schema": "draft-sample",
"tags": {
"submissionType": "XML",
"displayTitle": "HapMap sample from Homo sapiens",
"fileName": "SRS001433.xml",
},
}
], "folder drafts content mismatch"
assert res["metadataObjects"] == [
{
"accessionId": accession_id,
"schema": "sample",
"tags": {"submissionType": "Form", "displayTitle": "HapMap sample from Homo sapiens"},
}
], "folder metadataObjects content mismatch"
# Publish the folder
folder_id = await publish_folder(sess, folder_id)
await get_draft(sess, "sample", draft_id, 404) # checking the draft was deleted after publication
async with sess.get(f"{folders_url}/{folder_id}") as resp:
LOG.debug(f"Checking that folder {folder_id} was patched")
res = await resp.json()
assert res["folderId"] == folder_id, "expected folder id does not match"
assert res["published"] is True, "folder is not published, expected True"
assert "datePublished" in res.keys()
assert "extraInfo" in res.keys()
assert res["drafts"] == [], "there are drafts in folder, expected empty"
assert res["metadataObjects"] == [
{
"accessionId": accession_id,
"schema": "sample",
"tags": {"submissionType": "Form", "displayTitle": "HapMap sample from Homo sapiens"},
}
], "folder metadataObjects content mismatch"
# Delete folder
await delete_folder_publish(sess, folder_id)
async with sess.get(f"{drafts_url}/sample/{draft_id}") as resp:
LOG.debug(f"Checking that JSON object {accession_id} was deleted")
assert resp.status == 404, f"HTTP Status code error, got {resp.status}"
async def test_crud_folders_works_no_publish(sess):
"""Test folders REST api POST, GET, PATCH, PUBLISH and DELETE reqs.
:param sess: HTTP session in which request call is made
"""
# Create new folder and check its creation succeeded
folder_data = {"name": "Mock Unpublished folder", "description": "test umpublished folder"}
folder_id = await post_folder(sess, folder_data)
async with sess.get(f"{folders_url}/{folder_id}") as resp:
LOG.debug(f"Checking that folder {folder_id} was created")
assert resp.status == 200, f"HTTP Status code error, got {resp.status}"
# Create draft from test XML file and patch the draft into the newly created folder
draft_id = await post_draft(sess, "sample", folder_id, "SRS001433.xml")
async with sess.get(f"{folders_url}/{folder_id}") as resp:
LOG.debug(f"Checking that folder {folder_id} was patched")
res = await resp.json()
assert res["folderId"] == folder_id, "expected folder id does not match"
assert res["name"] == folder_data["name"], "expected folder name does not match"
assert res["description"] == folder_data["description"], "folder description content mismatch"
assert res["published"] is False, "folder is published, expected False"
assert res["drafts"] == [
{
"accessionId": draft_id,
"schema": "draft-sample",
"tags": {
"submissionType": "XML",
"displayTitle": "HapMap sample from Homo sapiens",
"fileName": "SRS001433.xml",
},
}
], "folder drafts content mismatch"
assert res["metadataObjects"] == [], "there are objects in folder, expected empty"
# Get the draft from the collection within this session and post it to objects collection
draft = await get_draft(sess, "sample", draft_id)
async with sess.post(f"{objects_url}/sample", params={"folder": folder_id}, data=draft) as resp:
LOG.debug("Adding draft to actual objects")
assert resp.status == 201, f"HTTP Status code error, got {resp.status}"
ans = await resp.json()
assert ans["accessionId"] != draft_id, "draft id does not match expected"
accession_id = ans["accessionId"]
async with sess.get(f"{folders_url}/{folder_id}") as resp:
LOG.debug(f"Checking that folder {folder_id} was patched")
res = await resp.json()
assert res["folderId"] == folder_id, "expected folder id does not match"
assert res["published"] is False, "folder is published, expected False"
assert res["drafts"] == [
{
"accessionId": draft_id,
"schema": "draft-sample",
"tags": {
"submissionType": "XML",
"displayTitle": "HapMap sample from Homo sapiens",
"fileName": "SRS001433.xml",
},
}
], "folder drafts content mismatch"
assert res["metadataObjects"] == [
{
"accessionId": accession_id,
"schema": "sample",
"tags": {"submissionType": "Form", "displayTitle": "HapMap sample from Homo sapiens"},
}
], "folder metadataObjects content mismatch"
# Delete folder
await delete_folder(sess, folder_id)
async with sess.get(f"{folders_url}/{folder_id}") as resp:
LOG.debug(f"Checking that folder {folder_id} was deleted")
assert resp.status == 404, f"HTTP Status code error, got {resp.status}"
async with sess.get(f"{users_url}/current") as resp:
LOG.debug(f"Checking that folder {folder_id} was deleted from current user")
res = await resp.json()
expected_true = not any(d == accession_id for d in res["folders"])
assert expected_true, "folder still exists at user"