forked from aws/sagemaker-python-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_jumpstart_utils.py
More file actions
1818 lines (1479 loc) · 76.9 KB
/
test_jumpstart_utils.py
File metadata and controls
1818 lines (1479 loc) · 76.9 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
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
import pytest
from unittest.mock import Mock, patch, MagicMock
from typing import Dict, List, Optional
from packaging.version import Version
import sagemaker
from sagemaker.core.jumpstart import utils, enums, constants
from sagemaker.core.jumpstart.types import (
JumpStartVersionedModelId,
JumpStartModelHeader,
JumpStartModelSpecs,
JumpStartBenchmarkStat,
DeploymentConfigMetadata,
)
from sagemaker.core.jumpstart.models import HubContentDocument
from sagemaker.core.helper.pipeline_variable import PipelineVariable
class TestIsPipelineVariable:
"""Test cases for is_pipeline_variable function"""
def test_is_pipeline_variable_false_string(self):
"""Test with string"""
assert utils.is_pipeline_variable("test") is False
def test_is_pipeline_variable_false_int(self):
"""Test with integer"""
assert utils.is_pipeline_variable(123) is False
def test_is_pipeline_variable_false_none(self):
"""Test with None"""
assert utils.is_pipeline_variable(None) is False
def test_is_pipeline_variable_false_dict(self):
"""Test with dictionary"""
assert utils.is_pipeline_variable({"key": "value"}) is False
class TestGetEulaUrl:
"""Test cases for get_eula_url function"""
@patch("sagemaker.core.jumpstart.utils.Session")
def test_get_eula_url_no_hosting_eula_uri(self, mock_session_class):
"""Test when document has no HostingEulaUri"""
document = Mock(spec=HubContentDocument)
document.HostingEulaUri = None
result = utils.get_eula_url(document)
assert result == ""
@patch("sagemaker.core.jumpstart.utils.Session")
def test_get_eula_url_empty_hosting_eula_uri(self, mock_session_class):
"""Test when document has empty HostingEulaUri"""
document = Mock(spec=HubContentDocument)
document.HostingEulaUri = ""
result = utils.get_eula_url(document)
assert result == ""
def test_get_eula_url_with_valid_uri(self):
"""Test with valid S3 URI"""
document = Mock(spec=HubContentDocument)
document.HostingEulaUri = "s3://test-bucket/path/to/eula.txt"
mock_session = Mock()
mock_session.boto_region_name = "us-west-2"
mock_botocore_session = Mock()
mock_endpoint_resolver = Mock()
mock_endpoint_resolver.get_partition_for_region.return_value = "aws"
mock_endpoint_resolver.get_partition_dns_suffix.return_value = "amazonaws.com"
mock_botocore_session.get_component.return_value = mock_endpoint_resolver
mock_session.boto_session._session = mock_botocore_session
result = utils.get_eula_url(document, mock_session)
assert result == "https://test-bucket.s3.us-west-2.amazonaws.com/path/to/eula.txt"
def test_get_eula_url_with_nested_path(self):
"""Test with nested S3 path"""
document = Mock(spec=HubContentDocument)
document.HostingEulaUri = "s3://my-bucket/deep/nested/path/eula.pdf"
mock_session = Mock()
mock_session.boto_region_name = "eu-west-1"
mock_botocore_session = Mock()
mock_endpoint_resolver = Mock()
mock_endpoint_resolver.get_partition_for_region.return_value = "aws"
mock_endpoint_resolver.get_partition_dns_suffix.return_value = "amazonaws.com"
mock_botocore_session.get_component.return_value = mock_endpoint_resolver
mock_session.boto_session._session = mock_botocore_session
result = utils.get_eula_url(document, mock_session)
assert result == "https://my-bucket.s3.eu-west-1.amazonaws.com/deep/nested/path/eula.pdf"
class TestGetJumpstartLaunchedRegionsMessage:
"""Test cases for get_jumpstart_launched_regions_message function"""
def test_get_jumpstart_launched_regions_message_empty(self):
"""Test with empty region set"""
with patch.object(constants, "JUMPSTART_REGION_NAME_SET", set()):
result = utils.get_jumpstart_launched_regions_message()
assert "JumpStart is not available in any region" in result
def test_get_jumpstart_launched_regions_message_single_region(self):
"""Test with single region"""
with patch.object(constants, "JUMPSTART_REGION_NAME_SET", {"us-west-2"}):
result = utils.get_jumpstart_launched_regions_message()
assert "us-west-2" in result
def test_get_jumpstart_launched_regions_message_multiple_regions(self):
"""Test with multiple regions"""
with patch.object(
constants, "JUMPSTART_REGION_NAME_SET", {"us-west-2", "us-east-1", "eu-west-1"}
):
result = utils.get_jumpstart_launched_regions_message()
assert "us-west-2" in result or "us-east-1" in result or "eu-west-1" in result
class TestGetFormattedManifest:
"""Test cases for get_formatted_manifest function"""
def test_get_formatted_manifest_empty(self):
"""Test with empty manifest"""
result = utils.get_formatted_manifest([])
assert result == {}
def test_get_formatted_manifest_single_model(self):
"""Test with single model"""
manifest = [
{
"model_id": "test-model",
"version": "1.0.0",
"min_version": "2.0.0",
"spec_key": "test-spec-key",
}
]
result = utils.get_formatted_manifest(manifest)
assert len(result) == 1
key = JumpStartVersionedModelId("test-model", "1.0.0")
assert key in result
assert result[key].model_id == "test-model"
assert result[key].version == "1.0.0"
def test_get_formatted_manifest_multiple_models(self):
"""Test with multiple models"""
manifest = [
{"model_id": "model-1", "version": "1.0.0", "min_version": "2.0.0", "spec_key": "key1"},
{"model_id": "model-2", "version": "2.0.0", "min_version": "2.0.0", "spec_key": "key2"},
]
result = utils.get_formatted_manifest(manifest)
assert len(result) == 2
assert JumpStartVersionedModelId("model-1", "1.0.0") in result
assert JumpStartVersionedModelId("model-2", "2.0.0") in result
class TestGetSagemakerVersion:
"""Test cases for get_sagemaker_version function"""
def test_get_sagemaker_version_returns_string(self):
"""Test that get_sagemaker_version returns a string"""
result = utils.get_sagemaker_version()
assert isinstance(result, str)
assert len(result) > 0
def test_get_sagemaker_version_format(self):
"""Test that version has expected format"""
result = utils.get_sagemaker_version()
# Should be in format like "2.123.0" or similar
parts = result.split(".")
assert len(parts) >= 2
class TestParseSagemakerVersion:
"""Test cases for parse_sagemaker_version function"""
def test_parse_sagemaker_version_returns_string(self):
"""Test that parse_sagemaker_version returns a string"""
result = utils.parse_sagemaker_version()
assert isinstance(result, str)
# Should be in format like "2.123.0" or similar
parts = result.split(".")
assert len(parts) >= 2
class TestIsJumpstartModelInput:
"""Test cases for is_jumpstart_model_input function"""
def test_is_jumpstart_model_input_both_none(self):
"""Test with both None"""
assert utils.is_jumpstart_model_input(None, None) is False
def test_is_jumpstart_model_input_both_provided(self):
"""Test with both provided"""
assert utils.is_jumpstart_model_input("test-model", "1.0.0") is True
def test_is_jumpstart_model_input_model_id_only_raises(self):
"""Test with model_id only raises ValueError"""
with pytest.raises(ValueError):
utils.is_jumpstart_model_input("test-model", None)
def test_is_jumpstart_model_input_version_only_raises(self):
"""Test with version only raises ValueError"""
with pytest.raises(ValueError):
utils.is_jumpstart_model_input(None, "1.0.0")
class TestIsJumpstartModelUri:
"""Test cases for is_jumpstart_model_uri function"""
def test_is_jumpstart_model_uri_none(self):
"""Test with None"""
assert utils.is_jumpstart_model_uri(None) is False
def test_is_jumpstart_model_uri_empty(self):
"""Test with empty string"""
assert utils.is_jumpstart_model_uri("") is False
def test_is_jumpstart_model_uri_not_s3(self):
"""Test with non-S3 URI"""
uri = "https://example.com/model.tar.gz"
assert utils.is_jumpstart_model_uri(uri) is False
class TestTagKeyInArray:
"""Test cases for tag_key_in_array function"""
def test_tag_key_in_array_found(self):
"""Test when tag key is found"""
tags = [{"Key": "model_id", "Value": "test"}, {"Key": "version", "Value": "1.0"}]
assert utils.tag_key_in_array("model_id", tags) is True
def test_tag_key_in_array_not_found(self):
"""Test when tag key is not found"""
tags = [{"Key": "model_id", "Value": "test"}]
assert utils.tag_key_in_array("version", tags) is False
def test_tag_key_in_array_empty(self):
"""Test with empty array"""
assert utils.tag_key_in_array("model_id", []) is False
def test_tag_key_in_array_case_sensitive(self):
"""Test case sensitivity"""
tags = [{"Key": "model_id", "Value": "test"}]
assert utils.tag_key_in_array("Model_Id", tags) is False
class TestGetTagValue:
"""Test cases for get_tag_value function"""
def test_get_tag_value_found(self):
"""Test when tag is found"""
tags = [{"Key": "model_id", "Value": "test-model"}, {"Key": "version", "Value": "1.0"}]
assert utils.get_tag_value("model_id", tags) == "test-model"
def test_get_tag_value_not_found(self):
"""Test when tag is not found"""
tags = [{"Key": "model_id", "Value": "test"}]
with pytest.raises(KeyError):
utils.get_tag_value("version", tags)
def test_get_tag_value_empty_array(self):
"""Test with empty array"""
with pytest.raises(KeyError):
utils.get_tag_value("model_id", [])
def test_get_tag_value_multiple_same_key_raises(self):
"""Test with multiple tags with same key raises KeyError"""
tags = [{"Key": "model_id", "Value": "first"}, {"Key": "model_id", "Value": "second"}]
with pytest.raises(KeyError):
utils.get_tag_value("model_id", tags)
class TestAddSingleJumpstartTag:
"""Test cases for add_single_jumpstart_tag function"""
def test_add_single_jumpstart_tag_to_none(self):
"""Test adding tag to None"""
result = utils.add_single_jumpstart_tag("test-value", enums.JumpStartTag.MODEL_ID, None)
assert len(result) == 1
assert result[0]["Key"] == enums.JumpStartTag.MODEL_ID.value
assert result[0]["Value"] == "test-value"
def test_add_single_jumpstart_tag_to_empty_list(self):
"""Test adding tag to empty list"""
result = utils.add_single_jumpstart_tag("test-value", enums.JumpStartTag.MODEL_ID, [])
assert len(result) == 1
assert result[0]["Key"] == enums.JumpStartTag.MODEL_ID.value
def test_add_single_jumpstart_tag_to_existing_tags(self):
"""Test adding tag to existing tags"""
existing_tags = [{"Key": "existing", "Value": "value"}]
result = utils.add_single_jumpstart_tag(
"test-value", enums.JumpStartTag.MODEL_ID, existing_tags
)
assert len(result) == 2
assert result[1]["Key"] == enums.JumpStartTag.MODEL_ID.value
def test_add_single_jumpstart_tag_with_existing_same_key(self):
"""Test adding tag when same key already exists"""
existing_tags = [{"Key": enums.JumpStartTag.MODEL_ID.value, "Value": "old-value"}]
result = utils.add_single_jumpstart_tag(
"new-value", enums.JumpStartTag.MODEL_ID, existing_tags
)
# Function doesn't add duplicate keys
assert len(result) == 1
assert result[0]["Value"] == "old-value"
class TestGetJumpstartBaseNameIfJumpstartModel:
"""Test cases for get_jumpstart_base_name_if_jumpstart_model function"""
@patch("sagemaker.core.jumpstart.utils.is_jumpstart_model_uri")
def test_get_jumpstart_base_name_no_uris(self, mock_is_jumpstart):
"""Test with no URIs"""
result = utils.get_jumpstart_base_name_if_jumpstart_model()
assert result is None
@patch("sagemaker.core.jumpstart.utils.is_jumpstart_model_uri")
def test_get_jumpstart_base_name_not_jumpstart(self, mock_is_jumpstart):
"""Test with non-JumpStart URIs"""
mock_is_jumpstart.return_value = False
result = utils.get_jumpstart_base_name_if_jumpstart_model("s3://my-bucket/model.tar.gz")
assert result is None
@patch("sagemaker.core.jumpstart.utils.is_jumpstart_model_uri")
def test_get_jumpstart_base_name_valid_jumpstart(self, mock_is_jumpstart):
"""Test with valid JumpStart URI"""
mock_is_jumpstart.return_value = True
uri = "s3://jumpstart-cache-prod-us-west-2/model.tar.gz"
result = utils.get_jumpstart_base_name_if_jumpstart_model(uri)
assert result == "sagemaker-jumpstart"
class TestUpdateDictIfKeyNotPresent:
"""Test cases for update_dict_if_key_not_present function"""
def test_update_dict_if_key_not_present_none_dict(self):
"""Test with None dictionary"""
result = utils.update_dict_if_key_not_present(None, "key", "value")
assert result == {"key": "value"}
def test_update_dict_if_key_not_present_empty_dict(self):
"""Test with empty dictionary"""
result = utils.update_dict_if_key_not_present({}, "key", "value")
assert result == {"key": "value"}
def test_update_dict_if_key_not_present_key_not_present(self):
"""Test when key is not present"""
original = {"existing": "value"}
result = utils.update_dict_if_key_not_present(original, "new_key", "new_value")
assert result == {"existing": "value", "new_key": "new_value"}
def test_update_dict_if_key_not_present_key_already_present(self):
"""Test when key is already present"""
original = {"key": "original_value"}
result = utils.update_dict_if_key_not_present(original, "key", "new_value")
assert result == {"key": "original_value"}
def test_update_dict_if_key_not_present_modifies_in_place(self):
"""Test that function modifies dict in place"""
original = {"existing": "value"}
result = utils.update_dict_if_key_not_present(original, "new_key", "new_value")
# Function modifies in place
assert original == {"existing": "value", "new_key": "new_value"}
assert result == original
class TestHasInstanceRateStat:
"""Test cases for has_instance_rate_stat function"""
def test_has_instance_rate_stat_empty(self):
"""Test with empty list"""
assert utils.has_instance_rate_stat([]) is False
class TestRemoveEnvVarFromEstimatorKwargsIfAcceptEulaPresent:
"""Test cases for remove_env_var_from_estimator_kwargs_if_accept_eula_present function"""
def test_remove_env_var_accept_eula_none(self):
"""Test when accept_eula is None"""
kwargs = {"environment": {"SageMakerGatedModelS3Uri": "s3://bucket/key", "OTHER": "value"}}
utils.remove_env_var_from_estimator_kwargs_if_accept_eula_present(kwargs, None)
assert "SageMakerGatedModelS3Uri" in kwargs["environment"]
class TestGetHubAccessConfig:
"""Test cases for get_hub_access_config function"""
def test_get_hub_access_config_none(self):
"""Test with None hub_content_arn"""
result = utils.get_hub_access_config(None)
assert result is None
def test_get_hub_access_config_valid_arn(self):
"""Test with valid hub_content_arn"""
arn = "arn:aws:sagemaker:us-west-2:123456789012:hub-content/test-hub/Model/test-model/1"
result = utils.get_hub_access_config(arn)
assert result is not None
assert isinstance(result, dict)
assert result["HubContentArn"] == arn
class TestGetModelAccessConfig:
"""Test cases for get_model_access_config function"""
def test_get_model_access_config_none(self):
"""Test with None accept_eula"""
result = utils.get_model_access_config(None)
assert result is None
def test_get_model_access_config_true(self):
"""Test with True accept_eula"""
result = utils.get_model_access_config(True)
assert result is not None
assert isinstance(result, dict)
assert result["AcceptEula"] is True
class TestGetJumpstartLaunchedRegionsMessageTwoRegions:
"""Test cases for two regions scenario"""
def test_get_jumpstart_launched_regions_message_two_regions(self):
"""Test with exactly two regions"""
with patch.object(constants, "JUMPSTART_REGION_NAME_SET", {"us-west-2", "us-east-1"}):
result = utils.get_jumpstart_launched_regions_message()
assert "us-west-2" in result and "us-east-1" in result
assert " and " in result
class TestGetJumpstartGatedContentBucket:
"""Test cases for get_jumpstart_gated_content_bucket function"""
@patch.object(
constants, "ENV_VARIABLE_JUMPSTART_GATED_CONTENT_BUCKET_OVERRIDE", "TEST_OVERRIDE"
)
@patch("os.environ", {"TEST_OVERRIDE": "override-bucket"})
def test_get_jumpstart_gated_content_bucket_with_override(self):
"""Test with environment variable override"""
with patch("sagemaker.core.jumpstart.accessors.JumpStartModelsAccessor") as mock_accessor:
mock_accessor.get_jumpstart_gated_content_bucket.return_value = None
result = utils.get_jumpstart_gated_content_bucket("us-west-2")
assert result == "override-bucket"
def test_get_jumpstart_gated_content_bucket_no_bucket(self):
"""Test when region has no gated content bucket"""
with patch.object(
constants,
"JUMPSTART_REGION_NAME_TO_LAUNCHED_REGION_DICT",
{"us-west-2": Mock(gated_content_bucket=None)},
):
with pytest.raises(ValueError, match="No private content bucket"):
utils.get_jumpstart_gated_content_bucket("us-west-2")
def test_get_jumpstart_gated_content_bucket_invalid_region(self):
"""Test with invalid region"""
with patch.object(constants, "JUMPSTART_REGION_NAME_TO_LAUNCHED_REGION_DICT", {}):
with pytest.raises(ValueError, match="Unable to get private content bucket"):
utils.get_jumpstart_gated_content_bucket("invalid-region")
class TestGetJumpstartContentBucket:
"""Test cases for get_jumpstart_content_bucket function"""
@patch.object(constants, "ENV_VARIABLE_JUMPSTART_CONTENT_BUCKET_OVERRIDE", "TEST_OVERRIDE")
@patch("os.environ", {"TEST_OVERRIDE": "override-bucket"})
def test_get_jumpstart_content_bucket_with_override(self):
"""Test with environment variable override"""
with patch("sagemaker.core.jumpstart.accessors.JumpStartModelsAccessor") as mock_accessor:
mock_accessor.get_jumpstart_content_bucket.return_value = None
result = utils.get_jumpstart_content_bucket("us-west-2")
assert result == "override-bucket"
def test_get_jumpstart_content_bucket_invalid_region(self):
"""Test with invalid region"""
with patch.object(constants, "JUMPSTART_REGION_NAME_TO_LAUNCHED_REGION_DICT", {}):
with pytest.raises(ValueError, match="Unable to get content bucket for Neo"):
utils.get_jumpstart_content_bucket("invalid-region")
class TestGetNeoContentBucket:
"""Test cases for get_neo_content_bucket function"""
@patch.object(constants, "ENV_VARIABLE_NEO_CONTENT_BUCKET_OVERRIDE", "TEST_NEO_OVERRIDE")
@patch("os.environ", {"TEST_NEO_OVERRIDE": "neo-override-bucket"})
@patch.object(constants, "JUMPSTART_LOGGER")
def test_get_neo_content_bucket_with_override(self, mock_logger):
"""Test with environment variable override"""
result = utils.get_neo_content_bucket("us-west-2")
assert result == "neo-override-bucket"
mock_logger.info.assert_called_once()
def test_get_neo_content_bucket_invalid_region(self):
"""Test with invalid region"""
with patch.object(constants, "JUMPSTART_REGION_NAME_TO_LAUNCHED_REGION_DICT", {}):
with pytest.raises(ValueError, match="Unable to get content bucket for Neo"):
utils.get_neo_content_bucket("invalid-region")
class TestParseSagemakerVersionEdgeCases:
"""Test cases for parse_sagemaker_version edge cases"""
def test_parse_sagemaker_version_with_four_periods(self):
"""Test version with 4 periods (dev version)"""
with patch.object(sagemaker, "__version__", "2.123.0.dev0", create=True):
result = utils.parse_sagemaker_version()
assert result == "2.123.0"
def test_parse_sagemaker_version_with_two_periods(self):
"""Test version with 2 periods"""
with patch.object(sagemaker, "__version__", "2.123.0", create=True):
result = utils.parse_sagemaker_version()
assert result == "2.123.0"
def test_parse_sagemaker_version_with_one_period(self):
"""Test version with 1 period raises error"""
with patch.object(sagemaker, "__version__", "2", create=True):
with pytest.raises(RuntimeError, match="Bad value for SageMaker version"):
utils.parse_sagemaker_version()
class TestIsJumpstartModelUriEdgeCases:
"""Test cases for is_jumpstart_model_uri edge cases"""
def test_is_jumpstart_model_uri_non_string(self):
"""Test with non-string input"""
assert utils.is_jumpstart_model_uri(123) is False
assert utils.is_jumpstart_model_uri([]) is False
assert utils.is_jumpstart_model_uri({}) is False
@patch("sagemaker.core.jumpstart.utils.parse_s3_url")
def test_is_jumpstart_model_uri_jumpstart_bucket(self, mock_parse):
"""Test with JumpStart bucket"""
mock_parse.return_value = ("jumpstart-cache-prod-us-west-2", "key")
with patch.object(
constants,
"JUMPSTART_GATED_AND_PUBLIC_BUCKET_NAME_SET",
{"jumpstart-cache-prod-us-west-2"},
):
result = utils.is_jumpstart_model_uri(
"s3://jumpstart-cache-prod-us-west-2/model.tar.gz"
)
assert result is True
class TestAddSingleJumpstartTagWithUri:
"""Test cases for add_single_jumpstart_tag with URI"""
@patch("sagemaker.core.jumpstart.utils.is_jumpstart_model_uri")
def test_add_single_jumpstart_tag_with_uri_true(self, mock_is_uri):
"""Test adding tag with is_uri=True"""
mock_is_uri.return_value = True
result = utils.add_single_jumpstart_tag(
"s3://bucket/key", enums.JumpStartTag.INFERENCE_MODEL_URI, None, is_uri=True
)
assert len(result) == 1
assert result[0]["Key"] == enums.JumpStartTag.INFERENCE_MODEL_URI.value
@patch("sagemaker.core.jumpstart.utils.is_jumpstart_model_uri")
def test_add_single_jumpstart_tag_skip_when_model_tags_exist(self, mock_is_uri):
"""Test skipping tag when model ID tag exists"""
mock_is_uri.return_value = True
existing_tags = [{"Key": enums.JumpStartTag.MODEL_ID.value, "Value": "test-model"}]
result = utils.add_single_jumpstart_tag(
"s3://bucket/key", enums.JumpStartTag.INFERENCE_MODEL_URI, existing_tags, is_uri=True
)
# Should not add new tag when model_id exists
assert len(result) == 1
class TestAddJumpstartModelInfoTags:
"""Test cases for add_jumpstart_model_info_tags function"""
def test_add_jumpstart_model_info_tags_none_inputs(self):
"""Test with None model_id or version"""
result = utils.add_jumpstart_model_info_tags([], None, "1.0.0")
assert result == []
def test_add_jumpstart_model_info_tags_wildcard_version(self):
"""Test with wildcard version"""
result = utils.add_jumpstart_model_info_tags([], "test-model", "*")
# Should add model_id but not version
assert any(tag["Key"] == enums.JumpStartTag.MODEL_ID.value for tag in result)
assert not any(tag["Key"] == enums.JumpStartTag.MODEL_VERSION.value for tag in result)
def test_add_jumpstart_model_info_tags_proprietary_model(self):
"""Test with proprietary model type"""
result = utils.add_jumpstart_model_info_tags(
[], "test-model", "1.0.0", model_type=enums.JumpStartModelType.PROPRIETARY
)
assert any(tag["Key"] == enums.JumpStartTag.MODEL_TYPE.value for tag in result)
def test_add_jumpstart_model_info_tags_with_inference_config(self):
"""Test with inference config name"""
result = utils.add_jumpstart_model_info_tags(
[],
"test-model",
"1.0.0",
config_name="test-config",
scope=enums.JumpStartScriptScope.INFERENCE,
)
assert any(tag["Key"] == enums.JumpStartTag.INFERENCE_CONFIG_NAME.value for tag in result)
def test_add_jumpstart_model_info_tags_with_training_config(self):
"""Test with training config name"""
result = utils.add_jumpstart_model_info_tags(
[],
"test-model",
"1.0.0",
config_name="test-config",
scope=enums.JumpStartScriptScope.TRAINING,
)
assert any(tag["Key"] == enums.JumpStartTag.TRAINING_CONFIG_NAME.value for tag in result)
class TestAddHubContentArnTags:
"""Test cases for add_hub_content_arn_tags function"""
def test_add_hub_content_arn_tags_valid(self):
"""Test adding hub content ARN tag"""
arn = "arn:aws:sagemaker:us-west-2:123456789012:hub-content/test"
result = utils.add_hub_content_arn_tags([], arn)
assert len(result) == 1
assert result[0]["Key"] == enums.JumpStartTag.HUB_CONTENT_ARN.value
assert result[0]["Value"] == arn
class TestAddBedrockStoreTags:
"""Test cases for add_bedrock_store_tags function"""
def test_add_bedrock_store_tags_valid(self):
"""Test adding bedrock compatibility tag"""
result = utils.add_bedrock_store_tags([], "bedrock-compatible")
assert len(result) == 1
assert result[0]["Key"] == enums.JumpStartTag.BEDROCK.value
assert result[0]["Value"] == "bedrock-compatible"
class TestAddJumpstartUriTags:
"""Test cases for add_jumpstart_uri_tags function"""
@patch("sagemaker.core.jumpstart.utils.is_pipeline_variable")
@patch("sagemaker.core.jumpstart.utils.is_jumpstart_model_uri")
def test_add_jumpstart_uri_tags_inference_model_dict(self, mock_is_js_uri, mock_is_pipeline):
"""Test with inference_model_uri as dict"""
mock_is_pipeline.return_value = False
mock_is_js_uri.return_value = True
model_uri_dict = {"S3DataSource": {"S3Uri": "s3://bucket/model.tar.gz"}}
result = utils.add_jumpstart_uri_tags(tags=None, inference_model_uri=model_uri_dict)
assert result is not None
assert len(result) == 1
@patch("sagemaker.core.jumpstart.utils.is_pipeline_variable")
def test_add_jumpstart_uri_tags_pipeline_variable_warning(self, mock_is_pipeline):
"""Test warning when URI is pipeline variable"""
mock_is_pipeline.return_value = True
with patch("logging.warning") as mock_warning:
result = utils.add_jumpstart_uri_tags(tags=None, inference_model_uri="pipeline_var")
mock_warning.assert_called()
@patch("sagemaker.core.jumpstart.utils.is_pipeline_variable")
@patch("sagemaker.core.jumpstart.utils.is_jumpstart_model_uri")
def test_add_jumpstart_uri_tags_all_uris(self, mock_is_js_uri, mock_is_pipeline):
"""Test with all URI types"""
mock_is_pipeline.return_value = False
mock_is_js_uri.return_value = True
result = utils.add_jumpstart_uri_tags(
tags=None,
inference_model_uri="s3://bucket/inference.tar.gz",
inference_script_uri="s3://bucket/inference_script.tar.gz",
training_model_uri="s3://bucket/training.tar.gz",
training_script_uri="s3://bucket/training_script.tar.gz",
)
assert len(result) == 4
class TestUpdateInferenceTagsWithJumpstartTrainingTags:
"""Test cases for update_inference_tags_with_jumpstart_training_tags function"""
def test_update_inference_tags_no_training_tags(self):
"""Test with no training tags"""
inference_tags = [{"Key": "test", "Value": "value"}]
result = utils.update_inference_tags_with_jumpstart_training_tags(inference_tags, None)
assert result == inference_tags
def test_update_inference_tags_with_jumpstart_training_tags(self):
"""Test updating inference tags from training tags"""
training_tags = [
{"Key": enums.JumpStartTag.MODEL_ID.value, "Value": "test-model"},
{"Key": enums.JumpStartTag.MODEL_VERSION.value, "Value": "1.0.0"},
]
result = utils.update_inference_tags_with_jumpstart_training_tags(None, training_tags)
assert len(result) == 2
assert result[0]["Key"] == enums.JumpStartTag.MODEL_ID.value
def test_update_inference_tags_skip_existing(self):
"""Test skipping tags that already exist in inference tags"""
inference_tags = [{"Key": enums.JumpStartTag.MODEL_ID.value, "Value": "existing"}]
training_tags = [{"Key": enums.JumpStartTag.MODEL_ID.value, "Value": "training"}]
result = utils.update_inference_tags_with_jumpstart_training_tags(
inference_tags, training_tags
)
assert len(result) == 1
assert result[0]["Value"] == "existing"
class TestGetEulaMessage:
"""Test cases for get_eula_message function"""
def test_get_eula_message_no_eula_key(self):
"""Test when model specs has no EULA key"""
model_specs = Mock(spec=JumpStartModelSpecs)
model_specs.hosting_eula_key = None
result = utils.get_eula_message(model_specs, "us-west-2")
assert result == ""
@patch("sagemaker.core.jumpstart.utils.get_jumpstart_content_bucket")
@patch("sagemaker.core.common_utils.get_domain_for_region")
def test_get_eula_message_with_eula_key(self, mock_domain, mock_bucket):
"""Test when model specs has EULA key"""
mock_bucket.return_value = "test-bucket"
mock_domain.return_value = "amazonaws.com"
model_specs = Mock(spec=JumpStartModelSpecs)
model_specs.hosting_eula_key = "eula/test.txt"
model_specs.model_id = "test-model"
result = utils.get_eula_message(model_specs, "us-west-2")
assert "test-model" in result
assert "eula/test.txt" in result
class TestEmitLogsBasedOnModelSpecs:
"""Test cases for emit_logs_based_on_model_specs function"""
@patch("sagemaker.core.jumpstart.accessors.JumpStartModelsAccessor._get_manifest")
@patch.object(constants, "JUMPSTART_LOGGER")
def test_emit_logs_deprecated_model(self, mock_logger, mock_manifest):
"""Test logging for deprecated model"""
mock_manifest.return_value = []
model_specs = Mock(spec=JumpStartModelSpecs)
model_specs.hosting_eula_key = None
model_specs.version = "1.0.0"
model_specs.model_id = "test-model"
model_specs.deprecated = True
model_specs.deprecated_message = "This model is deprecated"
model_specs.deprecate_warn_message = None
model_specs.usage_info_message = None
model_specs.inference_vulnerable = False
model_specs.training_vulnerable = False
utils.emit_logs_based_on_model_specs(model_specs, "us-west-2", Mock())
mock_logger.warning.assert_called()
@patch("sagemaker.core.jumpstart.accessors.JumpStartModelsAccessor._get_manifest")
@patch.object(constants, "JUMPSTART_LOGGER")
def test_emit_logs_vulnerable_model(self, mock_logger, mock_manifest):
"""Test logging for vulnerable model"""
mock_manifest.return_value = []
model_specs = Mock(spec=JumpStartModelSpecs)
model_specs.hosting_eula_key = None
model_specs.version = "1.0.0"
model_specs.model_id = "test-model"
model_specs.deprecated = False
model_specs.deprecate_warn_message = None
model_specs.usage_info_message = None
model_specs.inference_vulnerable = True
model_specs.training_vulnerable = False
utils.emit_logs_based_on_model_specs(model_specs, "us-west-2", Mock())
mock_logger.warning.assert_called()
@patch("sagemaker.core.jumpstart.accessors.JumpStartModelsAccessor._get_manifest")
@patch.object(constants, "JUMPSTART_LOGGER")
def test_emit_logs_usage_info(self, mock_logger, mock_manifest):
"""Test logging usage info message"""
mock_manifest.return_value = []
model_specs = Mock(spec=JumpStartModelSpecs)
model_specs.hosting_eula_key = None
model_specs.version = "1.0.0"
model_specs.model_id = "test-model"
model_specs.deprecated = False
model_specs.deprecate_warn_message = None
model_specs.usage_info_message = "Usage info"
model_specs.inference_vulnerable = False
model_specs.training_vulnerable = False
utils.emit_logs_based_on_model_specs(model_specs, "us-west-2", Mock())
assert mock_logger.info.called
class TestVerifyModelRegionAndReturnSpecs:
"""Test cases for verify_model_region_and_return_specs function"""
def test_verify_model_region_none_scope_raises(self):
"""Test with None scope raises ValueError"""
with pytest.raises(ValueError, match="Must specify `model_scope`"):
utils.verify_model_region_and_return_specs(
model_id="test-model", version="1.0.0", scope=None, region="us-west-2"
)
def test_verify_model_region_unsupported_scope_raises(self):
"""Test with unsupported scope raises NotImplementedError"""
with pytest.raises(NotImplementedError):
utils.verify_model_region_and_return_specs(
model_id="test-model", version="1.0.0", scope="unsupported", region="us-west-2"
)
@patch("sagemaker.core.jumpstart.accessors.JumpStartModelsAccessor.get_model_specs")
def test_verify_model_region_training_not_supported(self, mock_get_specs):
"""Test when training is not supported"""
model_specs = Mock(spec=JumpStartModelSpecs)
model_specs.training_supported = False
mock_get_specs.return_value = model_specs
with pytest.raises(ValueError, match="does not support training"):
utils.verify_model_region_and_return_specs(
model_id="test-model",
version="1.0.0",
scope=constants.JumpStartScriptScope.TRAINING.value,
region="us-west-2",
)
@patch("sagemaker.core.jumpstart.accessors.JumpStartModelsAccessor.get_model_specs")
def test_verify_model_region_deprecated_not_tolerated(self, mock_get_specs):
"""Test deprecated model raises when not tolerated"""
model_specs = Mock(spec=JumpStartModelSpecs)
model_specs.deprecated = True
model_specs.deprecated_message = "Deprecated"
mock_get_specs.return_value = model_specs
with pytest.raises(Exception):
utils.verify_model_region_and_return_specs(
model_id="test-model",
version="1.0.0",
scope=constants.JumpStartScriptScope.INFERENCE.value,
region="us-west-2",
tolerate_deprecated_model=False,
)
@patch("sagemaker.core.jumpstart.accessors.JumpStartModelsAccessor.get_model_specs")
def test_verify_model_region_vulnerable_inference_not_tolerated(self, mock_get_specs):
"""Test vulnerable inference model raises when not tolerated"""
model_specs = Mock(spec=JumpStartModelSpecs)
model_specs.deprecated = False
model_specs.inference_vulnerable = True
model_specs.inference_vulnerabilities = ["CVE-2023-1234"]
mock_get_specs.return_value = model_specs
with pytest.raises(Exception):
utils.verify_model_region_and_return_specs(
model_id="test-model",
version="1.0.0",
scope=constants.JumpStartScriptScope.INFERENCE.value,
region="us-west-2",
tolerate_vulnerable_model=False,
)
@patch("sagemaker.core.jumpstart.accessors.JumpStartModelsAccessor.get_model_specs")
def test_verify_model_region_vulnerable_training_not_tolerated(self, mock_get_specs):
"""Test vulnerable training model raises when not tolerated"""
model_specs = Mock(spec=JumpStartModelSpecs)
model_specs.deprecated = False
model_specs.training_supported = True
model_specs.training_vulnerable = True
model_specs.training_vulnerabilities = ["CVE-2023-5678"]
mock_get_specs.return_value = model_specs
with pytest.raises(Exception):
utils.verify_model_region_and_return_specs(
model_id="test-model",
version="1.0.0",
scope=constants.JumpStartScriptScope.TRAINING.value,
region="us-west-2",
tolerate_vulnerable_model=False,
)
@patch("sagemaker.core.jumpstart.accessors.JumpStartModelsAccessor.get_model_specs")
def test_verify_model_region_with_config_name(self, mock_get_specs):
"""Test with config name sets config"""
model_specs = Mock(spec=JumpStartModelSpecs)
model_specs.deprecated = False
model_specs.inference_vulnerable = False
model_specs.set_config = Mock()
mock_get_specs.return_value = model_specs
utils.verify_model_region_and_return_specs(
model_id="test-model",
version="1.0.0",
scope=constants.JumpStartScriptScope.INFERENCE.value,
region="us-west-2",
config_name="test-config",
)
model_specs.set_config.assert_called_once()
class TestResolveModelSagemakerConfigField:
"""Test cases for resolve_model_sagemaker_config_field function"""
@patch("sagemaker.core.jumpstart.utils.load_sagemaker_config")
@patch("sagemaker.core.common_utils.resolve_value_from_config")
def test_resolve_model_sagemaker_config_field_role(self, mock_resolve, mock_load_config):
"""Test resolving role field - user-provided role takes precedence"""
mock_resolve.return_value = "user-role"
mock_load_config.return_value = {"SchemaVersion": "1.0"}
mock_session = Mock()
mock_session.sagemaker_config = {"SchemaVersion": "1.0"}
result = utils.resolve_model_sagemaker_config_field("role", "user-role", mock_session)
assert result == "user-role"
@patch("sagemaker.core.jumpstart.utils.load_sagemaker_config")
@patch("sagemaker.core.common_utils.resolve_value_from_config")
def test_resolve_model_sagemaker_config_field_enable_network_isolation(
self, mock_resolve, mock_load_config
):
"""Test resolving enable_network_isolation field"""
mock_resolve.return_value = None
mock_load_config.return_value = {"SchemaVersion": "1.0"}
mock_session = Mock()
mock_session.sagemaker_config = {"SchemaVersion": "1.0"}
result = utils.resolve_model_sagemaker_config_field(
"enable_network_isolation", False, mock_session
)
assert result is False
@patch("sagemaker.core.jumpstart.utils.load_sagemaker_config")
@patch("sagemaker.core.common_utils.resolve_value_from_config")
def test_resolve_model_sagemaker_config_field_enable_network_isolation_none(
self, mock_resolve, mock_load_config
):
"""Test enable_network_isolation returns field_val when config is None"""
mock_resolve.return_value = None
mock_load_config.return_value = {"SchemaVersion": "1.0"}
mock_session = Mock()
mock_session.sagemaker_config = {"SchemaVersion": "1.0"}
result = utils.resolve_model_sagemaker_config_field(
"enable_network_isolation", True, mock_session
)
assert result is True
def test_resolve_model_sagemaker_config_field_other_field(self):
"""Test resolving other fields returns as is"""
mock_session = Mock()
mock_session.sagemaker_config = {"SchemaVersion": "1.0"}
result = utils.resolve_model_sagemaker_config_field("other_field", "value", mock_session)
assert result == "value"
class TestResolveEstimatorSagemakerConfigField:
"""Test cases for resolve_estimator_sagemaker_config_field function"""
@patch("sagemaker.core.jumpstart.utils.load_sagemaker_config")
@patch("sagemaker.core.common_utils.resolve_value_from_config")
def test_resolve_estimator_sagemaker_config_field_role(self, mock_resolve, mock_load_config):
"""Test resolving role field - user-provided role takes precedence"""
mock_resolve.return_value = "user-role"
mock_load_config.return_value = {"SchemaVersion": "1.0"}
mock_session = Mock()
mock_session.sagemaker_config = {"SchemaVersion": "1.0"}
result = utils.resolve_estimator_sagemaker_config_field("role", "user-role", mock_session)
assert result == "user-role"
@patch("sagemaker.core.jumpstart.utils.load_sagemaker_config")
@patch("sagemaker.core.common_utils.resolve_value_from_config")
def test_resolve_estimator_sagemaker_config_field_enable_network_isolation(
self, mock_resolve, mock_load_config
):
"""Test resolving enable_network_isolation field"""
mock_resolve.return_value = None
mock_load_config.return_value = {"SchemaVersion": "1.0"}
mock_session = Mock()
mock_session.sagemaker_config = {"SchemaVersion": "1.0"}
result = utils.resolve_estimator_sagemaker_config_field(
"enable_network_isolation", False, mock_session
)
assert result is False
@patch("sagemaker.core.jumpstart.utils.load_sagemaker_config")
@patch("sagemaker.core.common_utils.resolve_value_from_config")
def test_resolve_estimator_sagemaker_config_field_encrypt_inter_container(
self, mock_resolve, mock_load_config
):
"""Test resolving encrypt_inter_container_traffic field"""
mock_resolve.return_value = None
mock_load_config.return_value = {"SchemaVersion": "1.0"}
mock_session = Mock()