-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtest_score_set.py
More file actions
3940 lines (3269 loc) · 176 KB
/
test_score_set.py
File metadata and controls
3940 lines (3269 loc) · 176 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# ruff: noqa: E402
import csv
import json
import re
from copy import deepcopy
from datetime import date
from io import StringIO
from unittest.mock import patch
import jsonschema
import pytest
from humps import camelize
from sqlalchemy import select
arq = pytest.importorskip("arq")
cdot = pytest.importorskip("cdot")
fastapi = pytest.importorskip("fastapi")
from mavedb.lib.exceptions import NonexistentOrcidUserError
from mavedb.lib.validation.urn_re import MAVEDB_EXPERIMENT_URN_RE, MAVEDB_SCORE_SET_URN_RE, MAVEDB_TMP_URN_RE
from mavedb.models.enums.processing_state import ProcessingState
from mavedb.models.enums.target_category import TargetCategory
from mavedb.models.experiment import Experiment as ExperimentDbModel
from mavedb.models.score_set import ScoreSet as ScoreSetDbModel
from mavedb.models.variant import Variant as VariantDbModel
from mavedb.view_models.orcid import OrcidUser
from mavedb.view_models.score_set import ScoreSet, ScoreSetCreate
from tests.helpers.constants import (
EXTRA_LICENSE,
EXTRA_USER,
SAVED_DOI_IDENTIFIER,
SAVED_EXTRA_CONTRIBUTOR,
SAVED_MINIMAL_DATASET_COLUMNS,
SAVED_PUBMED_PUBLICATION,
SAVED_SHORT_EXTRA_LICENSE,
TEST_BIORXIV_IDENTIFIER,
TEST_BRNICH_SCORE_CALIBRATION_CLASS_BASED,
TEST_BRNICH_SCORE_CALIBRATION_RANGE_BASED,
TEST_CROSSREF_IDENTIFIER,
TEST_EXPERIMENT_WITH_KEYWORD,
TEST_GNOMAD_DATA_VERSION,
TEST_INACTIVE_LICENSE,
TEST_MAPPED_VARIANT_WITH_HGVS_G_EXPRESSION,
TEST_MAPPED_VARIANT_WITH_HGVS_P_EXPRESSION,
TEST_MINIMAL_ACC_SCORESET,
TEST_MINIMAL_ACC_SCORESET_RESPONSE,
TEST_MINIMAL_SEQ_SCORESET,
TEST_MINIMAL_SEQ_SCORESET_RESPONSE,
TEST_ORCID_ID,
TEST_PATHOGENICITY_SCORE_CALIBRATION,
TEST_PUBMED_IDENTIFIER,
TEST_SAVED_BRNICH_SCORE_CALIBRATION_RANGE_BASED,
TEST_SAVED_CLINVAR_CONTROL,
TEST_SAVED_GENERIC_CLINICAL_CONTROL,
TEST_SAVED_GNOMAD_VARIANT,
TEST_SAVED_TAXONOMY,
TEST_USER,
VALID_CLINGEN_CA_ID,
)
from tests.helpers.dependency_overrider import DependencyOverrider
from tests.helpers.util.common import (
deepcamelize,
parse_ndjson_response,
update_expected_response_for_created_resources,
)
from tests.helpers.util.contributor import add_contributor
from tests.helpers.util.experiment import create_experiment
from tests.helpers.util.license import change_to_inactive_license
from tests.helpers.util.score_calibration import (
create_publish_and_promote_score_calibration,
create_test_score_calibration_in_score_set_via_client,
)
from tests.helpers.util.score_set import (
create_seq_score_set,
create_seq_score_set_with_mapped_variants,
create_seq_score_set_with_variants,
link_clinical_controls_to_mapped_variants,
link_gnomad_variants_to_mapped_variants,
publish_score_set,
)
from tests.helpers.util.user import change_ownership
from tests.helpers.util.variant import (
clear_first_mapped_variant_post_mapped,
create_mapped_variants_for_score_set,
mock_worker_variant_insertion,
)
########################################################################################################################
# Score set schemas
########################################################################################################################
def test_TEST_MINIMAL_SEQ_SCORESET_is_valid():
jsonschema.validate(instance=TEST_MINIMAL_SEQ_SCORESET, schema=ScoreSetCreate.model_json_schema())
def test_TEST_MINIMAL_ACC_SCORESET_is_valid():
jsonschema.validate(instance=TEST_MINIMAL_ACC_SCORESET, schema=ScoreSetCreate.model_json_schema())
########################################################################################################################
# Score set creation
########################################################################################################################
@pytest.mark.parametrize(
"mock_publication_fetch",
[
(
[
{"dbName": "PubMed", "identifier": f"{TEST_PUBMED_IDENTIFIER}"},
{"dbName": "bioRxiv", "identifier": f"{TEST_BIORXIV_IDENTIFIER}"},
]
)
],
indirect=["mock_publication_fetch"],
)
def test_create_minimal_score_set(client, mock_publication_fetch, setup_router_db):
experiment = create_experiment(client)
score_set_post_payload = deepcopy(TEST_MINIMAL_SEQ_SCORESET)
score_set_post_payload["experimentUrn"] = experiment["urn"]
response = client.post("/api/v1/score-sets/", json=score_set_post_payload)
assert response.status_code == 200
response_data = response.json()
jsonschema.validate(instance=response_data, schema=ScoreSet.model_json_schema())
assert isinstance(MAVEDB_TMP_URN_RE.fullmatch(response_data["urn"]), re.Match)
expected_response = update_expected_response_for_created_resources(
deepcopy(TEST_MINIMAL_SEQ_SCORESET_RESPONSE), experiment, response_data
)
expected_response["experiment"].update({"numScoreSets": 1})
assert sorted(expected_response.keys()) == sorted(response_data.keys())
for key in expected_response:
assert (key, expected_response[key]) == (key, response_data[key])
response = client.get(f"/api/v1/score-sets/{response_data['urn']}")
assert response.status_code == 200
@pytest.mark.parametrize(
"mock_publication_fetch",
[
(
[
{"dbName": "PubMed", "identifier": f"{TEST_PUBMED_IDENTIFIER}"},
{"dbName": "bioRxiv", "identifier": f"{TEST_BIORXIV_IDENTIFIER}"},
]
)
],
indirect=["mock_publication_fetch"],
)
def test_create_score_set_with_contributor(client, mock_publication_fetch, setup_router_db):
experiment = create_experiment(client)
score_set = deepcopy(TEST_MINIMAL_SEQ_SCORESET)
score_set["experimentUrn"] = experiment["urn"]
score_set.update({"contributors": [{"orcid_id": TEST_ORCID_ID}]})
with patch(
"mavedb.lib.orcid.fetch_orcid_user",
lambda orcid_id: OrcidUser(orcid_id=orcid_id, given_name="ORCID", family_name="User"),
):
response = client.post("/api/v1/score-sets/", json=score_set)
assert response.status_code == 200
response_data = response.json()
jsonschema.validate(instance=response_data, schema=ScoreSet.model_json_schema())
assert isinstance(MAVEDB_TMP_URN_RE.fullmatch(response_data["urn"]), re.Match)
expected_response = update_expected_response_for_created_resources(
deepcopy(TEST_MINIMAL_SEQ_SCORESET_RESPONSE), experiment, response_data
)
expected_response["contributors"] = [
{
"recordType": "Contributor",
"orcidId": TEST_ORCID_ID,
"givenName": "ORCID",
"familyName": "User",
}
]
expected_response["experiment"].update({"numScoreSets": 1})
assert sorted(expected_response.keys()) == sorted(response_data.keys())
for key in expected_response:
assert (key, expected_response[key]) == (key, response_data[key])
response = client.get(f"/api/v1/score-sets/{response_data['urn']}")
assert response.status_code == 200
@pytest.mark.parametrize(
"mock_publication_fetch",
[
[
{"dbName": "PubMed", "identifier": f"{TEST_PUBMED_IDENTIFIER}"},
{"dbName": "bioRxiv", "identifier": f"{TEST_BIORXIV_IDENTIFIER}"},
]
],
indirect=["mock_publication_fetch"],
)
def test_create_score_set_with_score_calibration(client, mock_publication_fetch, setup_router_db):
experiment = create_experiment(client)
score_set = deepcopy(TEST_MINIMAL_SEQ_SCORESET)
score_set["experimentUrn"] = experiment["urn"]
score_set.update(
{
"scoreCalibrations": [deepcamelize(TEST_BRNICH_SCORE_CALIBRATION_RANGE_BASED)],
}
)
response = client.post("/api/v1/score-sets/", json=score_set)
assert response.status_code == 200
response_data = response.json()
jsonschema.validate(instance=response_data, schema=ScoreSet.model_json_schema())
assert isinstance(MAVEDB_TMP_URN_RE.fullmatch(response_data["urn"]), re.Match)
expected_response = update_expected_response_for_created_resources(
deepcopy(TEST_MINIMAL_SEQ_SCORESET_RESPONSE), experiment, response_data
)
expected_response["experiment"].update({"numScoreSets": 1})
expected_calibration = deepcopy(TEST_SAVED_BRNICH_SCORE_CALIBRATION_RANGE_BASED)
expected_calibration["urn"] = response_data["scoreCalibrations"][0]["urn"]
expected_calibration["private"] = True
expected_calibration["primary"] = False
expected_calibration["investigatorProvided"] = True
# Match functional classifications by a stable identifier (label).
response_fcs_by_label = {
fc["label"]: fc for fc in response_data["scoreCalibrations"][0]["functionalClassifications"]
}
for expected_fc in expected_calibration["functionalClassifications"]:
label = expected_fc["label"]
if label in response_fcs_by_label:
expected_fc["id"] = response_fcs_by_label[label]["id"]
expected_response["scoreCalibrations"] = [expected_calibration]
assert sorted(expected_response.keys()) == sorted(response_data.keys())
for key in expected_response:
assert (key, expected_response[key]) == (key, response_data[key])
response = client.get(f"/api/v1/score-sets/{response_data['urn']}")
assert response.status_code == 200
@pytest.mark.parametrize(
"mock_publication_fetch",
[
(
[
{"dbName": "PubMed", "identifier": f"{TEST_PUBMED_IDENTIFIER}"},
{"dbName": "bioRxiv", "identifier": f"{TEST_BIORXIV_IDENTIFIER}"},
]
)
],
indirect=["mock_publication_fetch"],
)
def test_cannot_create_score_set_with_class_based_calibration(client, mock_publication_fetch, setup_router_db):
experiment = create_experiment(client)
score_set = deepcopy(TEST_MINIMAL_SEQ_SCORESET)
score_set["experimentUrn"] = experiment["urn"]
score_set.update(
{
"scoreCalibrations": [deepcamelize(TEST_BRNICH_SCORE_CALIBRATION_CLASS_BASED)],
}
)
response = client.post("/api/v1/score-sets/", json=score_set)
assert response.status_code == 409
response_data = response.json()
assert "Class-based calibrations are not supported on score set creation" in response_data["detail"]
@pytest.mark.parametrize(
"mock_publication_fetch",
[
(
[
{"dbName": "PubMed", "identifier": f"{TEST_PUBMED_IDENTIFIER}"},
{"dbName": "bioRxiv", "identifier": f"{TEST_BIORXIV_IDENTIFIER}"},
]
)
],
indirect=["mock_publication_fetch"],
)
def test_cannot_create_score_set_with_nonexistent_contributor(client, mock_publication_fetch, setup_router_db):
experiment = create_experiment(client)
score_set = deepcopy(TEST_MINIMAL_SEQ_SCORESET)
score_set["experimentUrn"] = experiment["urn"]
score_set.update({"contributors": [{"orcid_id": TEST_ORCID_ID}]})
with patch(
"mavedb.lib.orcid.fetch_orcid_user",
side_effect=NonexistentOrcidUserError(f"No ORCID user was found for ORCID ID {TEST_ORCID_ID}."),
):
response = client.post("/api/v1/score-sets/", json=score_set)
assert response.status_code == 404
response_data = response.json()
assert "No ORCID user was found for ORCID ID 1111-1111-1111-1111." in response_data["detail"]
@pytest.mark.parametrize(
"mock_publication_fetch",
[
(
[
{"dbName": "PubMed", "identifier": f"{TEST_PUBMED_IDENTIFIER}"},
{"dbName": "bioRxiv", "identifier": f"{TEST_BIORXIV_IDENTIFIER}"},
]
)
],
indirect=["mock_publication_fetch"],
)
def test_cannot_create_score_set_without_email(client, mock_publication_fetch, setup_router_db):
experiment = create_experiment(client)
score_set_post_payload = deepcopy(TEST_MINIMAL_SEQ_SCORESET)
score_set_post_payload["experimentUrn"] = experiment["urn"]
client.put("api/v1/users/me", json={"email": None})
response = client.post("/api/v1/score-sets/", json=score_set_post_payload)
assert response.status_code == 403
response_data = response.json()
assert response_data["detail"] in "There must be an email address associated with your account to use this feature."
@pytest.mark.parametrize(
"mock_publication_fetch",
[
(
[
{"dbName": "PubMed", "identifier": f"{TEST_PUBMED_IDENTIFIER}"},
{"dbName": "bioRxiv", "identifier": f"{TEST_BIORXIV_IDENTIFIER}"},
]
)
],
indirect=["mock_publication_fetch"],
)
def test_cannot_create_score_set_with_invalid_target_gene_category(client, mock_publication_fetch, setup_router_db):
experiment = create_experiment(client)
score_set_post_payload = deepcopy(TEST_MINIMAL_SEQ_SCORESET)
score_set_post_payload["experimentUrn"] = experiment["urn"]
score_set_post_payload["targetGenes"][0]["category"] = "some_invalid_target_category"
response = client.post("/api/v1/score-sets/", json=score_set_post_payload)
assert response.status_code == 422
response_data = response.json()
assert "Input should be" in response_data["detail"][0]["msg"]
assert all(field in response_data["detail"][0]["msg"] for field in TargetCategory._member_names_)
########################################################################################################################
# Score set updating
########################################################################################################################
@pytest.mark.parametrize(
"attribute,updated_data,expected_response_data",
[
("title", "Updated Title", "Updated Title"),
("method_text", "Updated Method Text", "Updated Method Text"),
("abstract_text", "Updated Abstract Text", "Updated Abstract Text"),
("short_description", "Updated Abstract Text", "Updated Abstract Text"),
("extra_metadata", {"updated": "metadata"}, {"updated": "metadata"}),
("data_usage_policy", "data_usage_policy", "data_usage_policy"),
("contributors", [{"orcid_id": EXTRA_USER["username"]}], [SAVED_EXTRA_CONTRIBUTOR]),
("primary_publication_identifiers", [{"identifier": TEST_PUBMED_IDENTIFIER}], [SAVED_PUBMED_PUBLICATION]),
("secondary_publication_identifiers", [{"identifier": TEST_PUBMED_IDENTIFIER}], [SAVED_PUBMED_PUBLICATION]),
("doi_identifiers", [{"identifier": TEST_CROSSREF_IDENTIFIER}], [SAVED_DOI_IDENTIFIER]),
("license_id", EXTRA_LICENSE["id"], SAVED_SHORT_EXTRA_LICENSE),
("target_genes", TEST_MINIMAL_ACC_SCORESET["targetGenes"], TEST_MINIMAL_ACC_SCORESET_RESPONSE["targetGenes"]),
],
)
@pytest.mark.parametrize(
"mock_publication_fetch",
[({"dbName": "PubMed", "identifier": f"{TEST_PUBMED_IDENTIFIER}"})],
indirect=["mock_publication_fetch"],
)
def test_can_update_score_set_data_before_publication(
client, setup_router_db, attribute, updated_data, expected_response_data, mock_publication_fetch
):
experiment = create_experiment(client)
score_set = create_seq_score_set(client, experiment["urn"])
expected_response = update_expected_response_for_created_resources(
deepcopy(TEST_MINIMAL_SEQ_SCORESET_RESPONSE), experiment, score_set
)
expected_response["experiment"].update({"numScoreSets": 1})
response = client.get(f"/api/v1/score-sets/{score_set['urn']}")
assert response.status_code == 200
response_data = response.json()
assert sorted(expected_response.keys()) == sorted(response_data.keys())
for key in expected_response:
assert (key, expected_response[key]) == (key, response_data[key])
score_set_update_payload = deepcopy(TEST_MINIMAL_SEQ_SCORESET)
score_set_update_payload.update({camelize(attribute): updated_data})
response = client.put(f"/api/v1/score-sets/{score_set['urn']}", json=score_set_update_payload)
assert response.status_code == 200
response = client.get(f"/api/v1/score-sets/{score_set['urn']}")
assert response.status_code == 200
response_data = response.json()
# Although the client provides the license id, the response includes the full license.
if attribute == "license_id":
attribute = "license"
assert expected_response_data == response_data[camelize(attribute)]
@pytest.mark.parametrize(
"attribute,updated_data,expected_response_data",
[
("title", "Updated Title", "Updated Title"),
("method_text", "Updated Method Text", "Updated Method Text"),
("abstract_text", "Updated Abstract Text", "Updated Abstract Text"),
("short_description", "Updated Abstract Text", "Updated Abstract Text"),
("extra_metadata", {"updated": "metadata"}, {"updated": "metadata"}),
("data_usage_policy", "data_usage_policy", "data_usage_policy"),
("contributors", [{"orcid_id": EXTRA_USER["username"]}], [SAVED_EXTRA_CONTRIBUTOR]),
("primary_publication_identifiers", [{"identifier": TEST_PUBMED_IDENTIFIER}], [SAVED_PUBMED_PUBLICATION]),
("secondary_publication_identifiers", [{"identifier": TEST_PUBMED_IDENTIFIER}], [SAVED_PUBMED_PUBLICATION]),
("doi_identifiers", [{"identifier": TEST_CROSSREF_IDENTIFIER}], [SAVED_DOI_IDENTIFIER]),
("license_id", EXTRA_LICENSE["id"], SAVED_SHORT_EXTRA_LICENSE),
("target_genes", TEST_MINIMAL_ACC_SCORESET["targetGenes"], TEST_MINIMAL_ACC_SCORESET_RESPONSE["targetGenes"]),
],
)
@pytest.mark.parametrize(
"mock_publication_fetch",
[({"dbName": "PubMed", "identifier": f"{TEST_PUBMED_IDENTIFIER}"})],
indirect=["mock_publication_fetch"],
)
def test_can_patch_score_set_data_before_publication(
client, setup_router_db, attribute, updated_data, expected_response_data, mock_publication_fetch
):
experiment = create_experiment(client)
score_set = create_seq_score_set(client, experiment["urn"])
expected_response = update_expected_response_for_created_resources(
deepcopy(TEST_MINIMAL_SEQ_SCORESET_RESPONSE), experiment, score_set
)
expected_response["experiment"].update({"numScoreSets": 1})
response = client.get(f"/api/v1/score-sets/{score_set['urn']}")
assert response.status_code == 200
response_data = response.json()
assert sorted(expected_response.keys()) == sorted(response_data.keys())
for key in expected_response:
assert (key, expected_response[key]) == (key, response_data[key])
data = {}
if isinstance(updated_data, (dict, list)):
form_value = json.dumps(updated_data)
else:
form_value = str(updated_data)
data[attribute] = form_value
response = client.patch(f"/api/v1/score-sets-with-variants/{score_set['urn']}", data=data)
assert response.status_code == 200
response = client.get(f"/api/v1/score-sets/{score_set['urn']}")
assert response.status_code == 200
response_data = response.json()
# Although the client provides the license id, the response includes the full license.
if attribute == "license_id":
attribute = "license"
assert expected_response_data == response_data[camelize(attribute)]
@pytest.mark.parametrize(
"form_field,filename,mime_type",
[
("scores_file", "scores.csv", "text/csv"),
("counts_file", "counts.csv", "text/csv"),
("score_columns_metadata_file", "score_columns_metadata.json", "application/json"),
("count_columns_metadata_file", "count_columns_metadata.json", "application/json"),
],
)
@pytest.mark.parametrize(
"mock_publication_fetch",
[({"dbName": "PubMed", "identifier": f"{TEST_PUBMED_IDENTIFIER}"})],
indirect=["mock_publication_fetch"],
)
def test_can_patch_score_set_data_with_files_before_publication(
client, setup_router_db, form_field, filename, mime_type, data_files, mock_publication_fetch
):
experiment = create_experiment(client)
score_set = create_seq_score_set(client, experiment["urn"])
expected_response = update_expected_response_for_created_resources(
deepcopy(TEST_MINIMAL_SEQ_SCORESET_RESPONSE), experiment, score_set
)
expected_response["experiment"].update({"numScoreSets": 1})
if form_field == "counts_file" or form_field == "scores_file":
data_file_path = data_files / filename
files = {form_field: (filename, open(data_file_path, "rb"), mime_type)}
with patch.object(arq.ArqRedis, "enqueue_job", return_value=None) as worker_queue:
response = client.patch(f"/api/v1/score-sets-with-variants/{score_set['urn']}", files=files)
worker_queue.assert_called_once()
assert response.status_code == 200
elif form_field == "score_columns_metadata_file" or form_field == "count_columns_metadata_file":
data_file_path = data_files / filename
with open(data_file_path, "rb") as f:
data = json.load(f)
response = client.patch(f"/api/v1/score-sets-with-variants/{score_set['urn']}", data=data)
assert response.status_code == 200
@pytest.mark.parametrize(
"attribute,updated_data,expected_response_data",
[
("title", "Updated Title", "Updated Title"),
("method_text", "Updated Method Text", "Updated Method Text"),
("abstract_text", "Updated Abstract Text", "Updated Abstract Text"),
("short_description", "Updated Abstract Text", "Updated Abstract Text"),
("extra_metadata", {"updated": "metadata"}, {"updated": "metadata"}),
("data_usage_policy", "data_usage_policy", "data_usage_policy"),
("contributors", [{"orcid_id": EXTRA_USER["username"]}], [SAVED_EXTRA_CONTRIBUTOR]),
("primary_publication_identifiers", [{"identifier": TEST_PUBMED_IDENTIFIER}], [SAVED_PUBMED_PUBLICATION]),
("secondary_publication_identifiers", [{"identifier": TEST_PUBMED_IDENTIFIER}], [SAVED_PUBMED_PUBLICATION]),
("doi_identifiers", [{"identifier": TEST_CROSSREF_IDENTIFIER}], [SAVED_DOI_IDENTIFIER]),
("license_id", EXTRA_LICENSE["id"], SAVED_SHORT_EXTRA_LICENSE),
("dataset_columns", None, SAVED_MINIMAL_DATASET_COLUMNS),
],
)
@pytest.mark.parametrize(
"mock_publication_fetch",
[({"dbName": "PubMed", "identifier": f"{TEST_PUBMED_IDENTIFIER}"})],
indirect=["mock_publication_fetch"],
)
def test_can_update_score_set_supporting_data_after_publication(
session,
data_provider,
client,
setup_router_db,
attribute,
updated_data,
expected_response_data,
mock_publication_fetch,
data_files,
):
experiment = create_experiment(client)
score_set = create_seq_score_set(client, experiment["urn"])
score_set = mock_worker_variant_insertion(client, session, data_provider, score_set, data_files / "scores.csv")
with patch.object(arq.ArqRedis, "enqueue_job", return_value=None) as worker_queue:
published_score_set = publish_score_set(client, score_set["urn"])
worker_queue.assert_called_once()
published_urn = published_score_set["urn"]
response = client.get(f"/api/v1/score-sets/{published_urn}")
assert response.status_code == 200
response_data = response.json()
expected_response = update_expected_response_for_created_resources(
deepcopy(TEST_MINIMAL_SEQ_SCORESET_RESPONSE), response_data["experiment"], response_data
)
expected_response["experiment"].update({"publishedDate": date.today().isoformat()})
expected_response.update(
{
"urn": published_urn,
"publishedDate": date.today().isoformat(),
"numVariants": 3,
"private": False,
"datasetColumns": SAVED_MINIMAL_DATASET_COLUMNS,
"processingState": ProcessingState.success.name,
}
)
expected_response["experiment"].update({"numScoreSets": 1})
assert sorted(expected_response.keys()) == sorted(response_data.keys())
for key in expected_response:
assert (key, expected_response[key]) == (key, response_data[key])
score_set_update_payload = deepcopy(TEST_MINIMAL_SEQ_SCORESET)
score_set_update_payload.update({camelize(attribute): updated_data})
response = client.put(f"/api/v1/score-sets/{published_urn}", json=score_set_update_payload)
assert response.status_code == 200
response = client.get(f"/api/v1/score-sets/{published_urn}")
assert response.status_code == 200
response_data = response.json()
# Although the client provides the license id, the response includes the full license.
if attribute == "license_id":
attribute = "license"
assert expected_response_data == response_data[camelize(attribute)]
@pytest.mark.parametrize(
"attribute,updated_data,expected_response_data",
[
("target_genes", TEST_MINIMAL_ACC_SCORESET["targetGenes"], TEST_MINIMAL_SEQ_SCORESET_RESPONSE["targetGenes"]),
("dataset_columns", {"countColumns": [], "scoreColumns": ["score"]}, SAVED_MINIMAL_DATASET_COLUMNS),
],
)
@pytest.mark.parametrize(
"mock_publication_fetch",
[({"dbName": "PubMed", "identifier": f"{TEST_PUBMED_IDENTIFIER}"})],
indirect=["mock_publication_fetch"],
)
def test_cannot_update_score_set_target_data_after_publication(
client,
setup_router_db,
attribute,
expected_response_data,
updated_data,
session,
data_provider,
data_files,
mock_publication_fetch,
):
experiment = create_experiment(client)
score_set = create_seq_score_set(client, experiment["urn"])
score_set = mock_worker_variant_insertion(client, session, data_provider, score_set, data_files / "scores.csv")
with patch.object(arq.ArqRedis, "enqueue_job", return_value=None) as worker_queue:
published_score_set = publish_score_set(client, score_set["urn"])
worker_queue.assert_called_once()
published_urn = published_score_set["urn"]
response = client.get(f"/api/v1/score-sets/{published_urn}")
assert response.status_code == 200
response_data = response.json()
expected_response = update_expected_response_for_created_resources(
deepcopy(TEST_MINIMAL_SEQ_SCORESET_RESPONSE), response_data["experiment"], response_data
)
expected_response["experiment"].update({"publishedDate": date.today().isoformat()})
expected_response.update(
{
"urn": published_urn,
"publishedDate": date.today().isoformat(),
"numVariants": 3,
"private": False,
"datasetColumns": SAVED_MINIMAL_DATASET_COLUMNS,
"processingState": ProcessingState.success.name,
}
)
expected_response["experiment"].update({"numScoreSets": 1})
assert sorted(expected_response.keys()) == sorted(response_data.keys())
for key in expected_response:
assert (key, expected_response[key]) == (key, response_data[key])
score_set_update_payload = deepcopy(TEST_MINIMAL_SEQ_SCORESET)
score_set_update_payload.update(
{
camelize(attribute): updated_data,
}
)
response = client.put(f"/api/v1/score-sets/{published_urn}", json=score_set_update_payload)
assert response.status_code == 200
response = client.get(f"/api/v1/score-sets/{published_urn}")
assert response.status_code == 200
response_data = response.json()
if expected_response_data:
assert expected_response_data == response_data[camelize(attribute)]
else:
assert camelize(attribute) not in response_data.keys()
def test_cannot_update_score_set_with_nonexistent_contributor(
client,
setup_router_db,
):
experiment = create_experiment(client)
score_set = create_seq_score_set(client, experiment["urn"])
score_set_update_payload = deepcopy(TEST_MINIMAL_SEQ_SCORESET)
score_set_update_payload.update({"contributors": [{"orcid_id": TEST_ORCID_ID}]})
with patch(
"mavedb.lib.orcid.fetch_orcid_user",
side_effect=NonexistentOrcidUserError(f"No ORCID user was found for ORCID ID {TEST_ORCID_ID}."),
):
response = client.put(f"/api/v1/score-sets/{score_set['urn']}", json=score_set_update_payload)
assert response.status_code == 404
response_data = response.json()
assert "No ORCID user was found for ORCID ID 1111-1111-1111-1111." in response_data["detail"]
########################################################################################################################
# Score set fetching
########################################################################################################################
def test_get_own_private_score_set(client, setup_router_db):
experiment = create_experiment(client)
score_set = create_seq_score_set(client, experiment["urn"])
expected_response = update_expected_response_for_created_resources(
deepcopy(TEST_MINIMAL_SEQ_SCORESET_RESPONSE), experiment, score_set
)
expected_response["experiment"].update({"numScoreSets": 1})
response = client.get(f"/api/v1/score-sets/{score_set['urn']}")
assert response.status_code == 200
response_data = response.json()
assert sorted(expected_response.keys()) == sorted(response_data.keys())
for key in expected_response:
assert (key, expected_response[key]) == (key, response_data[key])
def test_cannot_get_other_user_private_score_set(session, client, setup_router_db):
experiment = create_experiment(client)
score_set = create_seq_score_set(client, experiment["urn"])
change_ownership(session, score_set["urn"], ScoreSetDbModel)
response = client.get(f"/api/v1/score-sets/{score_set['urn']}")
assert response.status_code == 404
response_data = response.json()
assert f"score set with URN '{score_set['urn']}' not found" in response_data["detail"]
def test_anonymous_user_cannot_get_user_private_score_set(session, client, setup_router_db, anonymous_app_overrides):
experiment = create_experiment(client)
score_set = create_seq_score_set(client, experiment["urn"])
change_ownership(session, score_set["urn"], ScoreSetDbModel)
with DependencyOverrider(anonymous_app_overrides):
response = client.get(f"/api/v1/score-sets/{score_set['urn']}")
assert response.status_code == 404
response_data = response.json()
assert f"score set with URN '{score_set['urn']}' not found" in response_data["detail"]
def test_can_add_contributor_in_both_experiment_and_score_set(session, client, setup_router_db):
experiment = create_experiment(client)
score_set = create_seq_score_set(client, experiment["urn"])
change_ownership(session, score_set["urn"], ScoreSetDbModel)
change_ownership(session, experiment["urn"], ExperimentDbModel)
add_contributor(
session,
score_set["urn"],
ScoreSetDbModel,
TEST_USER["username"],
TEST_USER["first_name"],
TEST_USER["last_name"],
)
add_contributor(
session,
experiment["urn"],
ExperimentDbModel,
TEST_USER["username"],
TEST_USER["first_name"],
TEST_USER["last_name"],
)
score_set_response = client.get(f"/api/v1/score-sets/{score_set['urn']}")
assert score_set_response.status_code == 200
ss_response_data = score_set_response.json()
assert len(ss_response_data["contributors"]) == 1
assert any(c["orcidId"] == TEST_USER["username"] for c in ss_response_data["contributors"])
experiment_response = client.get(f"/api/v1/experiments/{experiment['urn']}")
assert experiment_response.status_code == 200
exp_response_data = experiment_response.json()
assert len(exp_response_data["contributors"]) == 1
assert any(c["orcidId"] == TEST_USER["username"] for c in exp_response_data["contributors"])
def test_contributor_can_get_other_users_private_score_set(session, client, setup_router_db):
experiment = create_experiment(client)
score_set = create_seq_score_set(client, experiment["urn"])
change_ownership(session, score_set["urn"], ScoreSetDbModel)
add_contributor(
session,
score_set["urn"],
ScoreSetDbModel,
TEST_USER["username"],
TEST_USER["first_name"],
TEST_USER["last_name"],
)
expected_response = update_expected_response_for_created_resources(
deepcopy(TEST_MINIMAL_SEQ_SCORESET_RESPONSE), experiment, score_set
)
expected_response["contributors"] = [
{
"recordType": "Contributor",
"orcidId": TEST_USER["username"],
"givenName": TEST_USER["first_name"],
"familyName": TEST_USER["last_name"],
}
]
expected_response["createdBy"] = {
"recordType": "User",
"orcidId": EXTRA_USER["username"],
"firstName": EXTRA_USER["first_name"],
"lastName": EXTRA_USER["last_name"],
}
expected_response["modifiedBy"] = {
"recordType": "User",
"orcidId": EXTRA_USER["username"],
"firstName": EXTRA_USER["first_name"],
"lastName": EXTRA_USER["last_name"],
}
expected_response["experiment"].update({"numScoreSets": 1})
response = client.get(f"/api/v1/score-sets/{score_set['urn']}")
assert response.status_code == 200
response_data = response.json()
assert sorted(expected_response.keys()) == sorted(response_data.keys())
for key in expected_response:
assert (key, expected_response[key]) == (key, response_data[key])
def test_admin_can_get_other_user_private_score_set(session, client, admin_app_overrides, setup_router_db):
experiment = create_experiment(client)
score_set = create_seq_score_set(client, experiment["urn"])
expected_response = update_expected_response_for_created_resources(
deepcopy(TEST_MINIMAL_SEQ_SCORESET_RESPONSE), experiment, score_set
)
expected_response["experiment"].update({"numScoreSets": 1})
with DependencyOverrider(admin_app_overrides):
response = client.get(f"/api/v1/score-sets/{score_set['urn']}")
assert response.status_code == 200
response_data = response.json()
assert sorted(expected_response.keys()) == sorted(response_data.keys())
for key in expected_response:
assert (key, expected_response[key]) == (key, response_data[key])
@pytest.mark.parametrize(
"mock_publication_fetch",
[
(
[
{"dbName": "PubMed", "identifier": f"{TEST_PUBMED_IDENTIFIER}"},
{"dbName": "bioRxiv", "identifier": f"{TEST_BIORXIV_IDENTIFIER}"},
]
)
],
indirect=["mock_publication_fetch"],
)
def test_extra_user_can_only_view_published_score_calibrations_in_score_set(
client, setup_router_db, extra_user_app_overrides, mock_publication_fetch, session, data_provider, data_files
):
experiment = create_experiment(client)
score_set = create_seq_score_set(client, experiment["urn"])
score_set = mock_worker_variant_insertion(client, session, data_provider, score_set, data_files / "scores.csv")
with patch.object(arq.ArqRedis, "enqueue_job", return_value=None) as worker_queue:
published_score_set = publish_score_set(client, score_set["urn"])
worker_queue.assert_called_once()
create_test_score_calibration_in_score_set_via_client(
client, published_score_set["urn"], deepcamelize(TEST_BRNICH_SCORE_CALIBRATION_RANGE_BASED)
)
public_calibration = create_publish_and_promote_score_calibration(
client,
published_score_set["urn"],
deepcamelize(TEST_BRNICH_SCORE_CALIBRATION_RANGE_BASED),
)
with DependencyOverrider(extra_user_app_overrides):
response = client.get(f"/api/v1/score-sets/{published_score_set['urn']}")
assert response.status_code == 200
response_data = response.json()
assert len(response_data["scoreCalibrations"]) == 1
assert response_data["scoreCalibrations"][0]["urn"] == public_calibration["urn"]
@pytest.mark.parametrize(
"mock_publication_fetch",
[
(
[
{"dbName": "PubMed", "identifier": f"{TEST_PUBMED_IDENTIFIER}"},
{"dbName": "bioRxiv", "identifier": f"{TEST_BIORXIV_IDENTIFIER}"},
]
)
],
indirect=["mock_publication_fetch"],
)
def test_creating_user_can_view_all_score_calibrations_in_score_set(client, setup_router_db, mock_publication_fetch):
experiment = create_experiment(client)
score_set = create_seq_score_set(client, experiment["urn"])
private_calibration = create_test_score_calibration_in_score_set_via_client(
client, score_set["urn"], deepcamelize(TEST_BRNICH_SCORE_CALIBRATION_RANGE_BASED)
)
public_calibration = create_publish_and_promote_score_calibration(
client,
score_set["urn"],
deepcamelize(TEST_BRNICH_SCORE_CALIBRATION_RANGE_BASED),
)
response = client.get(f"/api/v1/score-sets/{score_set['urn']}")
assert response.status_code == 200
response_data = response.json()
assert len(response_data["scoreCalibrations"]) == 2
urns = [calibration["urn"] for calibration in response_data["scoreCalibrations"]]
assert private_calibration["urn"] in urns
assert public_calibration["urn"] in urns
########################################################################################################################
# Adding scores to score set
########################################################################################################################
def test_add_score_set_variants_scores_only_endpoint(client, setup_router_db, data_files):
experiment = create_experiment(client)
score_set = create_seq_score_set(client, experiment["urn"])
scores_csv_path = data_files / "scores.csv"
with (
open(scores_csv_path, "rb") as scores_file,
patch.object(arq.ArqRedis, "enqueue_job", return_value=None) as queue,
):
response = client.post(
f"/api/v1/score-sets/{score_set['urn']}/variants/data",
files={"scores_file": (scores_csv_path.name, scores_file, "text/csv")},
)
queue.assert_called_once()
assert response.status_code == 200
response_data = response.json()
jsonschema.validate(instance=response_data, schema=ScoreSet.model_json_schema())
# We test the worker process that actually adds the variant data separately. Here, we take it as
# fact that it would have succeeded.
score_set.update({"processingState": "processing"})
assert score_set == response_data
def test_add_score_set_variants_scores_and_counts_endpoint(session, client, setup_router_db, data_files):
experiment = create_experiment(client)
score_set = create_seq_score_set(client, experiment["urn"])
scores_csv_path = data_files / "scores.csv"
counts_csv_path = data_files / "counts.csv"
with (
open(scores_csv_path, "rb") as scores_file,
open(counts_csv_path, "rb") as counts_file,
patch.object(arq.ArqRedis, "enqueue_job", return_value=None) as queue,
):
response = client.post(
f"/api/v1/score-sets/{score_set['urn']}/variants/data",
files={
"scores_file": (scores_csv_path.name, scores_file, "text/csv"),
"counts_file": (counts_csv_path.name, counts_file, "text/csv"),
},
)
queue.assert_called_once()
assert response.status_code == 200
response_data = response.json()
jsonschema.validate(instance=response_data, schema=ScoreSet.model_json_schema())
# We test the worker process that actually adds the variant data separately. Here, we take it as
# fact that it would have succeeded.
score_set.update({"processingState": "processing"})
assert score_set == response_data
def test_add_score_set_variants_scores_counts_and_column_metadata_endpoint(
session, client, setup_router_db, data_files
):
experiment = create_experiment(client)
score_set = create_seq_score_set(client, experiment["urn"])
scores_csv_path = data_files / "scores.csv"
counts_csv_path = data_files / "counts.csv"
score_columns_metadata_path = data_files / "score_columns_metadata.json"
count_columns_metadata_path = data_files / "count_columns_metadata.json"
with (
open(scores_csv_path, "rb") as scores_file,
open(counts_csv_path, "rb") as counts_file,
open(score_columns_metadata_path, "rb") as score_columns_metadata_file,
open(count_columns_metadata_path, "rb") as count_columns_metadata_file,
patch.object(arq.ArqRedis, "enqueue_job", return_value=None) as queue,
):
score_columns_metadata = json.load(score_columns_metadata_file)
count_columns_metadata = json.load(count_columns_metadata_file)
response = client.post(
f"/api/v1/score-sets/{score_set['urn']}/variants/data",
files={
"scores_file": (scores_csv_path.name, scores_file, "text/csv"),
"counts_file": (counts_csv_path.name, counts_file, "text/csv"),
},
data={
"score_columns_metadata": json.dumps(score_columns_metadata),
"count_columns_metadata": json.dumps(count_columns_metadata),
},
)
queue.assert_called_once()
assert response.status_code == 200
response_data = response.json()