-
Notifications
You must be signed in to change notification settings - Fork 70
/
Copy pathunit_test_client.py
4268 lines (3714 loc) · 158 KB
/
unit_test_client.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
"""Unit tests for the Synapse client"""
import asyncio
import configparser
import datetime
import errno
import json
import logging
import os
import tempfile
import typing
import urllib.request as urllib_request
import uuid
from copy import deepcopy
from pathlib import Path
from unittest.mock import ANY, AsyncMock, MagicMock, Mock, call, create_autospec, patch
import httpx
import pytest
import requests
from pytest_mock import MockerFixture
import synapseclient
import synapseclient.core.utils as utils
from synapseclient import (
USER_AGENT,
Activity,
Annotations,
Column,
DockerRepository,
Entity,
EntityViewSchema,
File,
Folder,
Schema,
SubmissionViewSchema,
Synapse,
Team,
client,
)
from synapseclient.annotations import convert_old_annotation_json
from synapseclient.api import get_config_file
from synapseclient.client import DEFAULT_STORAGE_LOCATION_ID
from synapseclient.core import sts_transfer
from synapseclient.core.constants import concrete_types
from synapseclient.core.credentials import UserLoginArgs
from synapseclient.core.credentials.cred_data import SynapseAuthTokenCredentials
from synapseclient.core.credentials.credential_provider import (
SynapseCredentialsProviderChain,
)
from synapseclient.core.download import download_by_file_handle, download_from_url
from synapseclient.core.exceptions import (
SynapseAuthenticationError,
SynapseError,
SynapseFileNotFoundError,
SynapseHTTPError,
SynapseMd5MismatchError,
SynapseUnmetAccessRestrictions,
)
from synapseclient.core.logging_setup import (
DEBUG_LOGGER_NAME,
DEFAULT_LOGGER_NAME,
SILENT_LOGGER_NAME,
)
from synapseclient.core.models.dict_object import DictObject
from synapseclient.core.upload import upload_functions
from synapseclient.evaluation import Submission, SubmissionStatus
GET_FILE_HANDLE_FOR_DOWNLOAD = (
"synapseclient.core.download.download_functions.get_file_handle_for_download_async"
)
DOWNLOAD_BY_FILE_HANDLE = (
"synapseclient.core.download.download_functions.download_by_file_handle"
)
DOWNLOAD_FROM_URL = "synapseclient.core.download.download_functions.download_from_url"
FOO_KEY = "/tmp/fooKey"
class TestLogout:
@pytest.fixture(autouse=True, scope="function")
def init_syn(self, syn: Synapse) -> None:
self.syn = syn
@pytest.fixture(scope="function", autouse=True)
def setup_method(self) -> None:
self.username = "asdf"
self.credentials = SynapseAuthTokenCredentials(
token="ghjk", username=self.username
)
def test_logout_delete_credentials_from_syn(self) -> None:
self.syn.credentials = self.credentials
assert self.syn.credentials is not None
self.syn.logout()
assert self.syn.credentials is None
class TestLogin:
@pytest.fixture(autouse=True, scope="function")
def init_syn(self, syn: Synapse) -> None:
self.syn = syn
@pytest.fixture(scope="function", autouse=True)
def setup_method(self) -> None:
self.login_args = {"email": "AzureDiamond", "authToken": "hunter2"}
self.expected_user_args = UserLoginArgs(
auth_token="hunter2", username="AzureDiamond"
)
self.synapse_creds = SynapseAuthTokenCredentials(
token="hunter2",
displayname="Azure Diamond",
username="AzureDiamond",
)
self.mocked_credential_chain = create_autospec(SynapseCredentialsProviderChain)
self.mocked_credential_chain.get_credentials.return_value = self.synapse_creds
self.get_default_credential_chain_patcher = patch.object(
client,
"get_default_credential_chain",
return_value=self.mocked_credential_chain,
)
self.mocked_get_credential_chain = (
self.get_default_credential_chain_patcher.start()
)
def teardown_method(self) -> None:
self.get_default_credential_chain_patcher.stop()
def test_login_no_credentials(self) -> None:
self.mocked_credential_chain.get_credentials.return_value = None
# method under test
pytest.raises(SynapseAuthenticationError, self.syn.login, **self.login_args)
self.mocked_get_credential_chain.assert_called_once_with()
self.mocked_credential_chain.get_credentials.assert_called_once_with(
self.syn, self.expected_user_args
)
def test_login_credentials_returned(self) -> None:
# method under test
self.syn.login(silent=True, **self.login_args)
self.mocked_get_credential_chain.assert_called_once_with()
self.mocked_credential_chain.get_credentials.assert_called_once_with(
self.syn, self.expected_user_args
)
assert self.synapse_creds == self.syn.credentials
def test_login_silent_is_false(self) -> None:
with patch.object(self.syn, "logger") as mocked_logger:
# method under test
self.syn.login(silent=False, **self.login_args)
mocked_logger.info.assert_called_once()
@patch(GET_FILE_HANDLE_FOR_DOWNLOAD)
@patch(DOWNLOAD_BY_FILE_HANDLE)
class TestPrivateGetWithEntityBundle:
@pytest.fixture(autouse=True, scope="function")
def init_syn(self, syn: Synapse) -> None:
self.syn = syn
def test_get_with_entity_bundle_no_download(
self, download_file_mock: MagicMock, get_file_URL_and_metadata_mock: MagicMock
) -> None:
bundle = {
"entity": {
"id": "syn10101",
"etag": "f826b84e-b325-48d9-a658-3929bf687129",
"name": "anonymous",
"dataFileHandleId": "-1337",
"concreteType": "org.sagebionetworks.repo.model.FileEntity",
"parentId": "syn12345",
},
"fileHandles": [],
"annotations": {
"id": "syn10101",
"etag": "f826b84e-b325-48d9-a658-3929bf687129",
"annotations": {},
},
}
with patch.object(self.syn.logger, "warning") as mocked_warn:
entity_no_download = self.syn._getWithEntityBundle(entityBundle=bundle)
mocked_warn.assert_called_once()
assert entity_no_download.path is None
def test_get_with_entity_bundle(
self, download_file_mock: MagicMock, get_file_url_and_metadata_mock: MagicMock
) -> None:
# Note: one thing that remains unexplained is why the previous version of
# this test worked if you had a .cacheMap file of the form:
# {"/Users/chris/.synapseCache/663/-1337/anonymous": "2014-09-15T22:54:57.000Z",
# "/var/folders/ym/p7cr7rrx4z7fw36sxv04pqh00000gq/T/tmpJ4nz8U": "2014-09-15T23:27:25.000Z"}
# ...but failed if you didn't.
bundle = {
"entity": {
"id": "syn10101",
"etag": "f826b84e-b325-48d9-a658-3929bf687129",
"name": "anonymous",
"dataFileHandleId": "-1337",
"concreteType": "org.sagebionetworks.repo.model.FileEntity",
"parentId": "syn12345",
},
"fileHandles": [
{
"concreteType": "org.sagebionetworks.repo.model.file.S3FileHandle",
"fileName": "anonymous",
"contentType": "application/flapdoodle",
"contentMd5": "1698d26000d60816caab15169efcd23a",
"id": "-1337",
}
],
"annotations": {
"id": "syn10101",
"etag": "f826b84e-b325-48d9-a658-3929bf687129",
"annotations": {},
},
}
file_handle = bundle["fileHandles"][0]["id"]
cache_dir = self.syn.cache.get_cache_dir(file_handle)
# Make sure the .cacheMap file does not already exist
cache_map = os.path.join(cache_dir, ".cacheMap")
if os.path.exists(cache_map):
os.remove(cache_map)
def _download_file_handle(
file_handle_id: str,
synapse_id: str,
entity_type: str,
destination: str,
retries: int = 5,
synapse_client: Synapse = None,
):
# touch file at path
with open(destination, "a"):
os.utime(destination, None)
os.path.split(destination)
self.syn.cache.add(file_handle_id=file_handle, path=destination)
return destination
def _get_file_handle_download(
file_handle_id: str, synapse_id: str, entity_type: str = "FileHandle"
):
return {
"fileHandle": bundle["fileHandles"][0],
"fileHandleId": file_handle_id,
"preSignedURL": "http://example.com",
}
download_file_mock.side_effect = _download_file_handle
get_file_url_and_metadata_mock.side_effect = _get_file_handle_download
# 1. ----------------------------------------------------------------------
# download file to an alternate location
temp_dir1 = tempfile.mkdtemp()
e = self.syn._getWithEntityBundle(
entityBundle=bundle,
downloadLocation=temp_dir1,
ifcollision="overwrite.local",
)
assert e.name == bundle["entity"]["name"]
assert e.parentId == bundle["entity"]["parentId"]
assert utils.normalize_path(
os.path.abspath(os.path.dirname(e.path))
) == utils.normalize_path(temp_dir1)
assert bundle["fileHandles"][0]["fileName"] == os.path.basename(e.path)
assert utils.normalize_path(os.path.abspath(e.path)) == utils.normalize_path(
os.path.join(temp_dir1, bundle["fileHandles"][0]["fileName"])
)
# 2. ----------------------------------------------------------------------
# get without specifying downloadLocation
e = self.syn._getWithEntityBundle(
entityBundle=bundle, ifcollision="overwrite.local"
)
assert e.name == bundle["entity"]["name"]
assert e.parentId == bundle["entity"]["parentId"]
assert bundle["fileHandles"][0]["fileName"] in e.files
# 3. ----------------------------------------------------------------------
# download to another location
temp_dir2 = tempfile.mkdtemp()
assert temp_dir2 != temp_dir1
e = self.syn._getWithEntityBundle(
entityBundle=bundle,
downloadLocation=temp_dir2,
ifcollision="overwrite.local",
)
assert bundle["fileHandles"][0]["fileName"] in e.files
assert e.path is not None
assert utils.equal_paths(os.path.dirname(e.path), temp_dir2)
# 4. ----------------------------------------------------------------------
# test preservation of local state
url = "http://foo.com/secretstuff.txt"
# need to create a bundle with externalURL
externalURLBundle = dict(bundle)
externalURLBundle["fileHandles"][0]["externalURL"] = url
e = File(
name="anonymous", parentId="syn12345", synapseStore=False, externalURL=url
)
e.local_state({"zap": "pow"})
e = self.syn._getWithEntityBundle(entityBundle=externalURLBundle, entity=e)
assert e.local_state()["zap"] == "pow"
assert e.synapseStore is False
assert e.externalURL == url
# TODO: add more test cases for flag combination of this method
# TODO: separate into another test?
class TestDownloadFileHandle:
# TODO missing tests for the other ways of downloading a file handle should be backfilled...
@pytest.fixture(autouse=True, scope="function")
def init_syn(self, syn: Synapse) -> None:
self.syn = syn
@patch("synapseclient.core.download.download_functions.sts_transfer")
async def test_download_file_handle__retry_error(
self, mock_sts_transfer: MagicMock
) -> None:
mock_sts_transfer.is_boto_sts_transfer_enabled.return_value = False
file_handle_id = 1234
syn_id = "syn123"
disk_space_error = OSError()
disk_space_error.errno = errno.ENOSPC
retries = 5
for ex, expected_attempts in [
(SynapseMd5MismatchError("error"), 1),
(disk_space_error, 1),
(ValueError("foo"), retries),
]:
with patch(
GET_FILE_HANDLE_FOR_DOWNLOAD,
new_callable=AsyncMock,
) as mock_get_file_handle_download, patch(
DOWNLOAD_FROM_URL,
) as mock_download_from_URL:
mock_get_file_handle_download.return_value = {
"fileHandle": {
"id": file_handle_id,
"concreteType": concrete_types.S3_FILE_HANDLE,
"contentSize": 1,
},
"preSignedURL": "http://foo.com",
}
mock_download_from_URL.side_effect = ex
with pytest.raises(ex.__class__):
await download_by_file_handle(
file_handle_id=file_handle_id,
synapse_id=syn_id,
entity_type="FileEntity",
destination="/tmp/foo",
retries=retries,
synapse_client=self.syn,
)
assert mock_download_from_URL.call_count == expected_attempts
@patch("synapseclient.core.download.download_functions.S3ClientWrapper")
@patch("synapseclient.core.download.download_functions.sts_transfer")
@patch("synapseclient.core.download.download_functions.os")
async def test_download_file_handle__sts_boto(
self,
mock_os: MagicMock,
mock_sts_transfer: MagicMock,
mock_s3_client_wrapper: MagicMock,
) -> None:
"""Verify that we download S3 file handles using boto if the configuration specifies
# it and if the storage location supports STS"""
file_handle_id = 1234
entity_id_value = "syn_5678"
bucket_name = "fooBucket"
key = FOO_KEY
destination = "/tmp"
credentials = {
"aws_access_key_id": "foo",
"aws_secret_access_key": "bar",
"aws_session_token": "baz",
}
mock_sts_transfer.is_boto_sts_transfer_enabled.return_value = True
mock_sts_transfer.is_storage_location_sts_enabled_async = AsyncMock(
return_value=True
)
def mock_with_boto_sts_credentials(
fn, syn: Synapse, entity_id: str, permission: str
):
assert permission == "read_only"
assert entity_id == entity_id_value
return fn(credentials)
mock_sts_transfer.with_boto_sts_credentials = mock_with_boto_sts_credentials
expected_download_path = FOO_KEY
mock_s3_client_wrapper.download_file.return_value = expected_download_path
with patch(
GET_FILE_HANDLE_FOR_DOWNLOAD,
new_callable=AsyncMock,
) as mock_get_file_handle_download, patch.object(self.syn, "cache") as cache:
mock_get_file_handle_download.return_value = {
"fileHandle": {
"id": file_handle_id,
"bucketName": bucket_name,
"key": key,
"concreteType": concrete_types.S3_FILE_HANDLE,
"storageLocationId": 9876,
}
}
# this is another opt-in download method.
# for enabled storage locations sts should be preferred
multi_threaded = self.syn.multi_threaded
try:
self.syn.multi_threaded = True
download_path = await download_by_file_handle(
file_handle_id=file_handle_id,
synapse_id=entity_id_value,
entity_type="FileEntity",
destination=destination,
synapse_client=self.syn,
)
# restore to whatever it was before
finally:
self.syn.multi_threaded = multi_threaded
mock_os.makedirs.assert_called_once_with(
mock_os.path.dirname(destination), exist_ok=True
)
cache.add.assert_called_once_with(file_handle_id, download_path, None)
assert expected_download_path == download_path
mock_s3_client_wrapper.download_file.assert_called_once_with(
bucket="fooBucket",
endpoint_url=None,
remote_file_key=FOO_KEY,
download_file_path="/tmp",
credentials=credentials,
progress_bar=ANY,
transfer_config_kwargs={"max_concurrency": self.syn.max_threads},
)
async def test_download_file_ftp_link(self) -> None:
"""Verify downloading from an FTP Link entity"""
file_handle_id = 1234
entity_id = "syn5678"
url = "ftp://foo.com/bar"
destination = "/tmp"
expected_destination = os.path.abspath(destination)
with patch(
GET_FILE_HANDLE_FOR_DOWNLOAD,
new_callable=AsyncMock,
) as mock_get_file_handle_download, patch.object(
self.syn, "cache"
), patch.object(
urllib_request, "urlretrieve"
) as mock_url_retrieve, patch.object(
utils, "md5_for_file"
) as mock_md5_for_file, patch.object(
os, "makedirs"
), patch.object(
sts_transfer, "is_storage_location_sts_enabled_async", return_value=False
):
mock_get_file_handle_download.return_value = {
"fileHandle": {
"id": file_handle_id,
"concreteType": concrete_types.EXTERNAL_FILE_HANDLE,
"externalURL": url,
"storageLocationId": 9876,
},
"preSignedURL": url,
}
mock_md5_for_file.return_value = Mock(hexdigest=Mock(return_value="abc123"))
download_path = await download_by_file_handle(
file_handle_id=file_handle_id,
synapse_id=entity_id,
entity_type="FileEntity",
destination=destination,
synapse_client=self.syn,
)
mock_url_retrieve.assert_called_once_with(
url=url, filename=expected_destination, reporthook=ANY
)
assert download_path == expected_destination
async def test_download_from_url__synapse_auth(self, mocker: MagicMock) -> None:
"""Verify we pass along Synapse auth headers when downloading from a Synapse repo hosted url"""
uri = f"{self.syn.repoEndpoint}/repo/v1/entity/syn1234567/file"
in_destination = tempfile.NamedTemporaryFile(mode="w+", delete=False)
mock_credentials = mocker.patch.object(self.syn, "credentials")
response = MagicMock(spec=requests.Response)
response.status_code = 200
response.headers = {}
# TODO: When swapping out for the HTTPX client, we will need to update this test
# mock_get = mocker.patch.object(self.syn, "rest_get_async")
mock_get = mocker.patch.object(self.syn._requests_session, "get")
mock_get.return_value = response
out_destination = download_from_url(
url=uri,
entity_id="syn123",
file_handle_associate_type="FileEntity",
destination=in_destination.name,
synapse_client=self.syn,
)
assert mock_get.call_args[1]["auth"] is mock_credentials
assert os.path.normpath(out_destination) == os.path.normpath(
in_destination.name
)
in_destination.close()
os.unlink(in_destination.name)
async def test_download_from_url__external(self, mocker) -> None:
"""Verify we do not pass along Synapse auth headers to a file download that is a not Synapse repo hosted"""
uri = "https://not-synapse.org/foo/bar/baz"
in_destination = tempfile.NamedTemporaryFile(mode="w+", delete=False)
mocker.patch.object(self.syn, "credentials")
response = MagicMock(spec=requests.Response)
response.status_code = 200
response.headers = {}
# TODO: When swapping out for the HTTPX client, we will need to update this test
# mock_get = mocker.patch.object(self.syn, "rest_get_async")
mock_get = mocker.patch.object(self.syn._requests_session, "get")
mock_get.return_value = response
out_destination = download_from_url(
url=uri,
destination=in_destination.name,
entity_id="syn123",
file_handle_associate_type="FileEntity",
synapse_client=self.syn,
)
assert mock_get.call_args[1]["auth"] is None
assert os.path.normpath(out_destination) == os.path.normpath(
in_destination.name
)
in_destination.close()
os.unlink(in_destination.name)
@patch(GET_FILE_HANDLE_FOR_DOWNLOAD)
async def test_download_file_handle_preserve_exception_info(
self, mock_get_file_handle_download: MagicMock
) -> None:
file_handle_id = 1234
syn_id = "syn123"
def get_file_handle_download_side_effect(*args, **kwargs):
raise SynapseError(
f"Something wrong when downloading {syn_id} in try block!"
)
mock_get_file_handle_download.side_effect = get_file_handle_download_side_effect
with pytest.raises(SynapseError) as ex:
await download_by_file_handle(
file_handle_id=file_handle_id,
synapse_id=syn_id,
entity_type="FileEntity",
destination="/tmp/foo",
synapse_client=self.syn,
)
assert str(ex.value) == "Something wrong when downloading syn123 in try block!"
class TestPrivateSubmit:
@pytest.fixture(autouse=True, scope="function")
def init_syn(self, syn: Synapse) -> None:
self.syn = syn
@pytest.fixture(scope="function", autouse=True)
def setup_method(self) -> None:
self.etag = "etag"
self.eval_id = 1
self.eligibility_hash = 23
self.submission = {
"id": 123,
"evaluationId": 1,
"name": "entity_name",
"entityId": "syn43",
"versionNumber": 1,
"teamId": 888,
"contributors": [],
"submitterAlias": "awesome_submission",
}
self.patch_restPOST = patch.object(
self.syn, "restPOST", return_value=self.submission
)
self.mock_restPOST = self.patch_restPOST.start()
def teardown_method(self) -> None:
self.patch_restPOST.stop()
def test_invalid_submission(self) -> None:
pytest.raises(ValueError, self.syn._submit, None, self.etag, self.submission)
def test_invalid_etag(self) -> None:
pytest.raises(
ValueError, self.syn._submit, self.submission, None, self.submission
)
def test_without_eligibility_hash(self) -> None:
assert self.submission == self.syn._submit(self.submission, self.etag, None)
uri = "/evaluation/submission?etag={0}".format(self.etag)
self.mock_restPOST.assert_called_once_with(uri, json.dumps(self.submission))
def test_with_eligibitiy_hash(self) -> None:
assert self.submission == self.syn._submit(
self.submission, self.etag, self.eligibility_hash
)
uri = "/evaluation/submission?etag={0}&submissionEligibilityHash={1}".format(
self.etag, self.eligibility_hash
)
self.mock_restPOST.assert_called_once_with(uri, json.dumps(self.submission))
class TestSubmit:
@pytest.fixture(autouse=True, scope="function")
def init_syn(self, syn: Synapse) -> None:
self.syn = syn
@pytest.fixture(scope="function", autouse=True)
def setup_method(self) -> None:
self.eval_id = "9090"
self.contributors = None
self.entity = {
"versionNumber": 7,
"id": "syn1009",
"etag": "etag",
"name": "entity name",
}
self.docker = {"id": "syn1009", "etag": "etag", "repositoryName": "entity name"}
self.eval = {
"contentSource": self.entity["id"],
"createdOn": "2013-11-06T06:04:26.789Z",
"etag": "86485ea1-8c89-4f24-a0a4-2f63bc011091",
"id": self.eval_id,
"name": "test evaluation",
"ownerId": "1560252",
"status": "OPEN",
"submissionReceiptMessage": "Your submission has been received.!",
}
self.team = {"id": 5, "name": "Team Blue"}
self.submission = {
"id": 123,
"evaluationId": self.eval_id,
"name": self.entity["name"],
"entityId": self.entity["id"],
"versionNumber": self.entity["versionNumber"],
"teamId": utils.id_of(self.team["id"]),
"contributors": self.contributors,
"submitterAlias": self.team["name"],
}
self.eligibility_hash = 23
self.patch_private_submit = patch.object(
self.syn, "_submit", return_value=self.submission
)
self.patch_getEvaluation = patch.object(
self.syn, "getEvaluation", return_value=self.eval
)
self.patch_get = patch.object(self.syn, "get", return_value=self.entity)
self.patch_getTeam = patch.object(self.syn, "getTeam", return_value=self.team)
self.patch_get_contributors = patch.object(
self.syn,
"_get_contributors",
return_value=(self.contributors, self.eligibility_hash),
)
self.mock_private_submit = self.patch_private_submit.start()
self.mock_getEvaluation = self.patch_getEvaluation.start()
self.mock_get = self.patch_get.start()
self.mock_getTeam = self.patch_getTeam.start()
self.mock_get_contributors = self.patch_get_contributors.start()
def teardown_method(self) -> None:
self.patch_private_submit.stop()
self.patch_getEvaluation.stop()
self.patch_get.stop()
self.patch_getTeam.stop()
self.patch_get_contributors.stop()
def test_min_requirements(self) -> None:
assert self.submission == self.syn.submit(self.eval_id, self.entity)
expected_request_body = self.submission
expected_request_body.pop("id")
expected_request_body["teamId"] = None
expected_request_body["submitterAlias"] = None
expected_request_body["dockerDigest"] = None
expected_request_body["dockerRepositoryName"] = None
self.mock_private_submit.assert_called_once_with(
expected_request_body, self.entity["etag"], self.eligibility_hash
)
self.mock_get.assert_not_called()
self.mock_getTeam.assert_not_called()
self.mock_get_contributors.assert_called_once_with(self.eval_id, None)
def test_only_entity_id_provided(self) -> None:
assert self.submission == self.syn.submit(self.eval_id, self.entity["id"])
expected_request_body = self.submission
expected_request_body.pop("id")
expected_request_body["teamId"] = None
expected_request_body["submitterAlias"] = None
expected_request_body["dockerDigest"] = None
expected_request_body["dockerRepositoryName"] = None
self.mock_private_submit.assert_called_once_with(
expected_request_body, self.entity["etag"], self.eligibility_hash
)
self.mock_get.assert_called_once_with(self.entity["id"], downloadFile=False)
self.mock_getTeam.assert_not_called()
self.mock_get_contributors.assert_called_once_with(self.eval_id, None)
def test_team_is_given(self) -> None:
assert self.submission == self.syn.submit(
self.eval_id, self.entity, team=self.team["id"]
)
expected_request_body = self.submission
expected_request_body.pop("id")
expected_request_body["dockerDigest"] = None
expected_request_body["dockerRepositoryName"] = None
self.mock_private_submit.assert_called_once_with(
expected_request_body, self.entity["etag"], self.eligibility_hash
)
self.mock_get.assert_not_called()
self.mock_getTeam.assert_called_once_with(self.team["id"])
self.mock_get_contributors.assert_called_once_with(self.eval_id, self.team)
def test_team_not_eligible(self) -> None:
self.mock_get_contributors.side_effect = SynapseError()
pytest.raises(
SynapseError,
self.syn.submit,
self.eval_id,
self.entity,
team=self.team["id"],
)
self.mock_private_submit.assert_not_called()
self.mock_get.assert_not_called()
self.mock_getTeam.assert_called_once_with(self.team["id"])
self.mock_get_contributors.assert_called_once_with(self.eval_id, self.team)
def test_get_docker_digest_default(self) -> None:
latest_sha = "sha256:eeeeee"
docker_commits = [{"tag": "latest", "digest": latest_sha}]
with patch.object(
self.syn, "_GET_paginated", return_value=docker_commits
) as patch_syn_get_paginated:
digest = self.syn._get_docker_digest("syn1234")
patch_syn_get_paginated.assert_called_once_with("/entity/syn1234/dockerTag")
assert digest == latest_sha
def test_get_docker_digest_specifytag(self) -> None:
test_sha = "sha256:ffffff"
docker_commits = [{"tag": "test", "digest": test_sha}]
with patch.object(
self.syn, "_GET_paginated", return_value=docker_commits
) as patch_syn_get_paginated:
digest = self.syn._get_docker_digest("syn1234", docker_tag="test")
patch_syn_get_paginated.assert_called_once_with("/entity/syn1234/dockerTag")
assert digest == test_sha
def test_get_docker_digest_specifywrongtag(self) -> None:
test_sha = "sha256:ffffff"
docker_commits = [{"tag": "test", "digest": test_sha}]
with patch.object(
self.syn, "_GET_paginated", return_value=docker_commits
) as patch_syn_get_paginated:
pytest.raises(
ValueError, self.syn._get_docker_digest, "syn1234", docker_tag="foo"
)
patch_syn_get_paginated.assert_called_once_with("/entity/syn1234/dockerTag")
def test_submit_docker_nonetag(self) -> None:
docker_entity = DockerRepository("foo", parentId="syn1000001")
docker_entity.id = "syn123"
docker_entity.etag = "Fake etag"
pytest.raises(
ValueError, self.syn.submit, "9090", docker_entity, "George", dockerTag=None
)
def test_submit_docker(self) -> None:
docker_entity = DockerRepository("foo", parentId="syn1000001")
docker_entity.id = "syn123"
docker_entity.etag = "Fake etag"
docker_digest = "sha256:digest"
expected_submission = {
"id": 123,
"evaluationId": self.eval_id,
"name": None,
"entityId": docker_entity["id"],
"versionNumber": self.entity["versionNumber"],
"dockerDigest": docker_digest,
"dockerRepositoryName": docker_entity["repositoryName"],
"teamId": utils.id_of(self.team["id"]),
"contributors": self.contributors,
"submitterAlias": self.team["name"],
}
with patch.object(
self.syn, "get", return_value=docker_entity
) as patch_syn_get, patch.object(
self.syn, "_get_docker_digest", return_value=docker_digest
) as patch_get_digest, patch.object(
self.syn, "_submit", return_value=expected_submission
):
submission = self.syn.submit("9090", patch_syn_get, name="George")
patch_get_digest.assert_called_once_with(docker_entity, "latest")
assert submission == expected_submission
class TestPrivateGetContributor:
@pytest.fixture(autouse=True, scope="function")
def init_syn(self, syn: Synapse) -> None:
self.syn = syn
@pytest.fixture(scope="function", autouse=True)
def setup_method(self) -> None:
self.eval_id = 111
self.team_id = 123
self.team = Team(name="test", id=self.team_id)
self.hash = 3
self.member_eligible = {
"isEligible": True,
"isRegistered": True,
"isQuotaFilled": False,
"principalId": 222,
"hasConflictingSubmission": False,
}
self.member_not_registered = {
"isEligible": False,
"isRegistered": False,
"isQuotaFilled": False,
"principalId": 223,
"hasConflictingSubmission": False,
}
self.member_quota_filled = {
"isEligible": False,
"isRegistered": True,
"isQuotaFilled": True,
"principalId": 224,
"hasConflictingSubmission": False,
}
self.member_has_conflict = {
"isEligible": True,
"isRegistered": True,
"isQuotaFilled": False,
"principalId": 225,
"hasConflictingSubmission": True,
}
self.eligibility = {
"teamId": self.team_id,
"evaluationId": self.eval_id,
"teamEligibility": {
"isEligible": True,
"isRegistered": True,
"isQuotaFilled": False,
},
"membersEligibility": [
self.member_eligible,
self.member_not_registered,
self.member_quota_filled,
self.member_has_conflict,
],
"eligibilityStateHash": self.hash,
}
self.patch_restGET = patch.object(
self.syn, "restGET", return_value=self.eligibility
)
self.mock_restGET = self.patch_restGET.start()
def teardown_method(self) -> None:
self.patch_restGET.stop()
def test_none_team(self) -> None:
assert (None, None) == self.syn._get_contributors(self.eval_id, None)
self.mock_restGET.assert_not_called()
def test_none_eval_id(self) -> None:
assert (None, None) == self.syn._get_contributors(None, self.team)
self.mock_restGET.assert_not_called()
def test_not_registered(self) -> None:
self.eligibility["teamEligibility"]["isEligible"] = False
self.eligibility["teamEligibility"]["isRegistered"] = False
self.patch_restGET.return_value = self.eligibility
pytest.raises(SynapseError, self.syn._get_contributors, self.eval_id, self.team)
uri = "/evaluation/{evalId}/team/{id}/submissionEligibility".format(
evalId=self.eval_id, id=self.team_id
)
self.mock_restGET.assert_called_once_with(uri)
def test_quota_filled(self) -> None:
self.eligibility["teamEligibility"]["isEligible"] = False
self.eligibility["teamEligibility"]["isQuotaFilled"] = True
self.patch_restGET.return_value = self.eligibility
pytest.raises(SynapseError, self.syn._get_contributors, self.eval_id, self.team)
uri = "/evaluation/{evalId}/team/{id}/submissionEligibility".format(
evalId=self.eval_id, id=self.team_id
)
self.mock_restGET.assert_called_once_with(uri)
def test_empty_members(self) -> None:
self.eligibility["membersEligibility"] = []
self.patch_restGET.return_value = self.eligibility
assert (
[],
self.eligibility["eligibilityStateHash"],
) == self.syn._get_contributors(self.eval_id, self.team)
uri = "/evaluation/{evalId}/team/{id}/submissionEligibility".format(
evalId=self.eval_id, id=self.team_id
)
self.mock_restGET.assert_called_once_with(uri)
def test_happy_case(self) -> None:
contributors = [{"principalId": self.member_eligible["principalId"]}]
assert (
contributors,
self.eligibility["eligibilityStateHash"],
) == self.syn._get_contributors(self.eval_id, self.team)
uri = "/evaluation/{evalId}/team/{id}/submissionEligibility".format(
evalId=self.eval_id, id=self.team_id
)
self.mock_restGET.assert_called_once_with(uri)
def test_send_message(syn: Synapse) -> None:
messageBody = (
"In Xanadu did Kubla Khan\n"
"A stately pleasure-dome decree:\n"
"Where Alph, the sacred river, ran\n"
"Through caverns measureless to man\n"
"Down to a sunless sea.\n"
)
with patch(
"synapseclient.client.multipart_upload_string_async",
new_callable=AsyncMock,
return_value="7365905",
) as mock_upload_string, patch(
"synapseclient.client.Synapse.restPOST"
) as post_mock:
syn.sendMessage(
userIds=[1421212], messageSubject="Xanadu", messageBody=messageBody
)
msg = json.loads(post_mock.call_args_list[0][1]["body"])
assert msg["fileHandleId"] == "7365905", msg
assert msg["recipients"] == [1421212], msg
assert msg["subject"] == "Xanadu", msg
mock_upload_string.assert_called_once_with(
syn, messageBody, content_type="text/plain"
)
@patch("synapseclient.Synapse._getDefaultUploadDestination")
class TestPrivateUploadExternallyStoringProjects:
@pytest.fixture(autouse=True, scope="function")
def init_syn(self, syn: Synapse) -> None:
self.syn = syn
@pytest.mark.parametrize(
"external_type",
[
concrete_types.EXTERNAL_S3_UPLOAD_DESTINATION,
concrete_types.SYNAPSE_S3_UPLOAD_DESTINATION,
concrete_types.EXTERNAL_GCP_UPLOAD_DESTINATION,
],
)