-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathtest_common_utils.py
More file actions
2251 lines (1670 loc) · 77.3 KB
/
test_common_utils.py
File metadata and controls
2251 lines (1670 loc) · 77.3 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.
"""Unit tests for sagemaker.core.common_utils module."""
from __future__ import absolute_import
import pytest
import time
import tempfile
import os
import tarfile
from unittest.mock import Mock, patch, MagicMock
from botocore.exceptions import ClientError
from sagemaker.core.common_utils import (
name_from_image,
name_from_base,
unique_name_from_base_uuid4,
unique_name_from_base,
base_name_from_image,
base_from_name,
sagemaker_timestamp,
sagemaker_short_timestamp,
build_dict,
get_config_value,
get_nested_value,
set_nested_value,
get_short_version,
secondary_training_status_changed,
secondary_training_status_message,
create_tar_file,
_tmpdir,
sts_regional_endpoint,
retries,
retry_with_backoff,
aws_partition,
get_resource_name_from_arn,
pop_out_unused_kwarg,
to_string,
get_module,
resolve_value_from_config,
get_sagemaker_config_value,
)
class TestNameFromImage:
"""Test name_from_image function."""
def test_name_from_image_basic(self):
"""Test basic image name extraction."""
image = "123456789012.dkr.ecr.us-west-2.amazonaws.com/my-algorithm:latest"
result = name_from_image(image)
assert "my-algorithm" in result
assert len(result) <= 63
def test_name_from_image_with_max_length(self):
"""Test name generation respects max length."""
image = "very-long-algorithm-name-that-exceeds-limits"
result = name_from_image(image, max_length=30)
assert len(result) <= 30
def test_name_from_image_simple(self):
"""Test simple image name."""
image = "my-algorithm"
result = name_from_image(image)
assert "my-algorithm" in result
class TestNameFromBase:
"""Test name_from_base function."""
def test_name_from_base_default(self):
"""Test default timestamp appending."""
base = "my-job"
result = name_from_base(base)
assert result.startswith("my-job-")
assert len(result) <= 63
def test_name_from_base_short(self):
"""Test short timestamp."""
base = "my-job"
result = name_from_base(base, short=True)
assert result.startswith("my-job-")
assert len(result) < len(name_from_base(base, short=False))
def test_name_from_base_max_length(self):
"""Test max length constraint."""
base = "a" * 100
result = name_from_base(base, max_length=40)
assert len(result) <= 40
def test_name_from_base_empty(self):
"""Test with empty base."""
result = name_from_base("")
assert len(result) > 0
class TestUniqueNameFromBaseUuid4:
"""Test unique_name_from_base_uuid4 function."""
def test_unique_name_from_base_uuid4_basic(self):
"""Test UUID-based name generation."""
base = "my-resource"
result = unique_name_from_base_uuid4(base)
assert result.startswith("my-resource-")
assert len(result) <= 63
def test_unique_name_from_base_uuid4_uniqueness(self):
"""Test that generated names are unique."""
base = "my-resource"
result1 = unique_name_from_base_uuid4(base)
result2 = unique_name_from_base_uuid4(base)
assert result1 != result2
def test_unique_name_from_base_uuid4_max_length(self):
"""Test max length constraint."""
base = "x" * 100
result = unique_name_from_base_uuid4(base, max_length=50)
assert len(result) <= 50
class TestUniqueNameFromBase:
"""Test unique_name_from_base function."""
def test_unique_name_from_base_basic(self):
"""Test basic unique name generation."""
base = "my-job"
result = unique_name_from_base(base)
assert result.startswith("my-job-")
assert len(result) <= 63
def test_unique_name_from_base_uniqueness(self):
"""Test uniqueness of generated names."""
base = "my-job"
result1 = unique_name_from_base(base)
time.sleep(0.01) # Small delay to ensure different timestamp
result2 = unique_name_from_base(base)
assert result1 != result2
def test_unique_name_from_base_max_length(self):
"""Test max length constraint."""
base = "y" * 100
result = unique_name_from_base(base, max_length=45)
assert len(result) <= 45
class TestBaseNameFromImage:
"""Test base_name_from_image function."""
def test_base_name_from_image_with_registry(self):
"""Test extracting base name from full registry path."""
image = "123456789012.dkr.ecr.us-west-2.amazonaws.com/my-algorithm:latest"
result = base_name_from_image(image)
assert result == "my-algorithm"
def test_base_name_from_image_simple(self):
"""Test simple image name."""
image = "tensorflow"
result = base_name_from_image(image)
assert result == "tensorflow"
def test_base_name_from_image_with_tag(self):
"""Test image with tag."""
image = "my-image:v1.0"
result = base_name_from_image(image)
assert result == "my-image"
def test_base_name_from_image_with_default(self):
"""Test with default base name."""
result = base_name_from_image("", default_base_name="default")
assert result in ["", "default"]
class TestBaseFromName:
"""Test base_from_name function."""
def test_base_from_name_with_timestamp(self):
"""Test extracting base from name with timestamp."""
name = "my-job-2023-01-15-10-30-45-123"
result = base_from_name(name)
assert result == "my-job"
def test_base_from_name_with_short_timestamp(self):
"""Test extracting base from name with short timestamp."""
name = "my-job-230115-1030"
result = base_from_name(name)
assert result == "my-job"
def test_base_from_name_no_timestamp(self):
"""Test name without timestamp."""
name = "my-job"
result = base_from_name(name)
assert result == "my-job"
class TestSagemakerTimestamp:
"""Test sagemaker_timestamp function."""
def test_sagemaker_timestamp_format(self):
"""Test timestamp format."""
result = sagemaker_timestamp()
# Format: YYYY-MM-DD-HH-MM-SS-mmm
parts = result.split("-")
assert len(parts) == 7
assert len(parts[0]) == 4 # Year
assert len(parts[6]) == 3 # Milliseconds
def test_sagemaker_timestamp_uniqueness(self):
"""Test that timestamps are unique."""
result1 = sagemaker_timestamp()
time.sleep(0.01)
result2 = sagemaker_timestamp()
assert result1 != result2
class TestSagemakerShortTimestamp:
"""Test sagemaker_short_timestamp function."""
def test_sagemaker_short_timestamp_format(self):
"""Test short timestamp format."""
result = sagemaker_short_timestamp()
# Format: YYMMDD-HHMM
assert len(result) == 11
assert "-" in result
def test_sagemaker_short_timestamp_consistency(self):
"""Test timestamp consistency within same minute."""
result1 = sagemaker_short_timestamp()
result2 = sagemaker_short_timestamp()
# Should be same if called within same minute
assert result1 == result2 or len(result1) == len(result2)
class TestBuildDict:
"""Test build_dict function."""
def test_build_dict_with_value(self):
"""Test building dict with non-None value."""
result = build_dict("key1", "value1")
assert result == {"key1": "value1"}
def test_build_dict_with_none(self):
"""Test building dict with None value."""
result = build_dict("key1", None)
assert result == {}
def test_build_dict_with_empty_string(self):
"""Test building dict with empty string."""
result = build_dict("key1", "")
assert result == {}
def test_build_dict_with_zero(self):
"""Test building dict with zero value."""
result = build_dict("key1", 0)
assert result == {}
def test_build_dict_with_false(self):
"""Test building dict with False value."""
result = build_dict("key1", False)
assert result == {}
class TestGetConfigValue:
"""Test get_config_value function."""
def test_get_config_value_simple(self):
"""Test getting simple config value."""
config = {"key1": "value1"}
result = get_config_value("key1", config)
assert result == "value1"
def test_get_config_value_nested(self):
"""Test getting nested config value."""
config = {"level1": {"level2": {"level3": "value"}}}
result = get_config_value("level1.level2.level3", config)
assert result == "value"
def test_get_config_value_missing(self):
"""Test getting missing config value."""
config = {"key1": "value1"}
result = get_config_value("key2", config)
assert result is None
def test_get_config_value_none_config(self):
"""Test with None config."""
result = get_config_value("key1", None)
assert result is None
def test_get_config_value_partial_path(self):
"""Test with partial path that doesn't exist."""
config = {"level1": {"level2": "value"}}
result = get_config_value("level1.level3.level4", config)
assert result is None
class TestGetNestedValue:
"""Test get_nested_value function."""
def test_get_nested_value_simple(self):
"""Test getting simple nested value."""
dictionary = {"key1": "value1"}
result = get_nested_value(dictionary, ["key1"])
assert result == "value1"
def test_get_nested_value_deep(self):
"""Test getting deeply nested value."""
dictionary = {"a": {"b": {"c": "value"}}}
result = get_nested_value(dictionary, ["a", "b", "c"])
assert result == "value"
def test_get_nested_value_missing(self):
"""Test getting missing nested value."""
dictionary = {"a": {"b": "value"}}
result = get_nested_value(dictionary, ["a", "c"])
assert result is None
def test_get_nested_value_none_dict(self):
"""Test with None dictionary."""
result = get_nested_value(None, ["key"])
assert result is None
def test_get_nested_value_empty_keys(self):
"""Test with empty keys list."""
dictionary = {"key": "value"}
result = get_nested_value(dictionary, [])
assert result is None
def test_get_nested_value_invalid_structure(self):
"""Test with invalid dictionary structure."""
dictionary = {"a": "not_a_dict"}
with pytest.raises(ValueError):
get_nested_value(dictionary, ["a", "b"])
class TestSetNestedValue:
"""Test set_nested_value function."""
def test_set_nested_value_simple(self):
"""Test setting simple nested value."""
dictionary = {}
result = set_nested_value(dictionary, ["key1"], "value1")
assert result == {"key1": "value1"}
def test_set_nested_value_deep(self):
"""Test setting deeply nested value."""
dictionary = {}
result = set_nested_value(dictionary, ["a", "b", "c"], "value")
assert result == {"a": {"b": {"c": "value"}}}
def test_set_nested_value_existing(self):
"""Test setting value in existing structure."""
dictionary = {"a": {"b": "old_value"}}
result = set_nested_value(dictionary, ["a", "b"], "new_value")
assert result == {"a": {"b": "new_value"}}
def test_set_nested_value_none_dict(self):
"""Test with None dictionary."""
result = set_nested_value(None, ["key"], "value")
assert result == {"key": "value"}
def test_set_nested_value_overwrite_non_dict(self):
"""Test overwriting non-dict value."""
dictionary = {"a": "not_a_dict"}
result = set_nested_value(dictionary, ["a", "b"], "value")
assert result == {"a": {"b": "value"}}
class TestGetShortVersion:
"""Test get_short_version function."""
def test_get_short_version_three_parts(self):
"""Test with three-part version."""
result = get_short_version("1.2.3")
assert result == "1.2"
def test_get_short_version_two_parts(self):
"""Test with two-part version."""
result = get_short_version("1.2")
assert result == "1.2"
def test_get_short_version_four_parts(self):
"""Test with four-part version."""
result = get_short_version("1.2.3.4")
assert result == "1.2"
def test_get_short_version_single_part(self):
"""Test with single-part version."""
result = get_short_version("1")
assert result == "1"
class TestSecondaryTrainingStatusChanged:
"""Test secondary_training_status_changed function."""
def test_secondary_training_status_changed_true(self):
"""Test when status has changed."""
current = {"SecondaryStatusTransitions": [{"StatusMessage": "Starting training"}]}
prev = {"SecondaryStatusTransitions": [{"StatusMessage": "Preparing data"}]}
result = secondary_training_status_changed(current, prev)
assert result is True
def test_secondary_training_status_changed_false(self):
"""Test when status hasn't changed."""
current = {"SecondaryStatusTransitions": [{"StatusMessage": "Training"}]}
prev = {"SecondaryStatusTransitions": [{"StatusMessage": "Training"}]}
result = secondary_training_status_changed(current, prev)
assert result is False
def test_secondary_training_status_changed_no_transitions(self):
"""Test with no transitions."""
current = {}
prev = {}
result = secondary_training_status_changed(current, prev)
assert result is False
def test_secondary_training_status_changed_none_prev(self):
"""Test with None previous description."""
current = {"SecondaryStatusTransitions": [{"StatusMessage": "Training"}]}
result = secondary_training_status_changed(current, None)
assert result is True
class TestSecondaryTrainingStatusMessage:
"""Test secondary_training_status_message function."""
def test_secondary_training_status_message_basic(self):
"""Test basic status message."""
from datetime import datetime
job_desc = {
"SecondaryStatusTransitions": [
{"Status": "Starting", "StatusMessage": "Starting training"}
],
"LastModifiedTime": datetime.now(),
}
result = secondary_training_status_message(job_desc, None)
assert "Starting" in result
assert "Starting training" in result
def test_secondary_training_status_message_no_transitions(self):
"""Test with no transitions."""
job_desc = {}
result = secondary_training_status_message(job_desc, None)
assert result == ""
def test_secondary_training_status_message_multiple_transitions(self):
"""Test with multiple transitions."""
from datetime import datetime
job_desc = {
"SecondaryStatusTransitions": [
{"Status": "Starting", "StatusMessage": "Starting"},
{"Status": "Training", "StatusMessage": "Training"},
],
"LastModifiedTime": datetime.now(),
}
prev_desc = {
"SecondaryStatusTransitions": [{"Status": "Starting", "StatusMessage": "Starting"}]
}
result = secondary_training_status_message(job_desc, prev_desc)
assert "Training" in result
class TestCreateTarFile:
"""Test create_tar_file function."""
def test_create_tar_file_single_file(self, tmp_path):
"""Test creating tar file from single file."""
test_file = tmp_path / "test.txt"
test_file.write_text("test content")
tar_path = create_tar_file([str(test_file)])
assert os.path.exists(tar_path)
with tarfile.open(tar_path, "r:gz") as tar:
members = tar.getmembers()
assert len(members) == 1
assert members[0].name == "test.txt"
os.remove(tar_path)
def test_create_tar_file_multiple_files(self, tmp_path):
"""Test creating tar file from multiple files."""
file1 = tmp_path / "file1.txt"
file2 = tmp_path / "file2.txt"
file1.write_text("content1")
file2.write_text("content2")
tar_path = create_tar_file([str(file1), str(file2)])
assert os.path.exists(tar_path)
with tarfile.open(tar_path, "r:gz") as tar:
members = tar.getmembers()
assert len(members) == 2
os.remove(tar_path)
def test_create_tar_file_with_target(self, tmp_path):
"""Test creating tar file with specific target path."""
test_file = tmp_path / "test.txt"
test_file.write_text("test content")
target = str(tmp_path / "output.tar.gz")
tar_path = create_tar_file([str(test_file)], target=target)
assert tar_path == target
assert os.path.exists(tar_path)
os.remove(tar_path)
class TestTmpdir:
"""Test _tmpdir context manager."""
def test_tmpdir_creates_directory(self):
"""Test that tmpdir creates a directory."""
with _tmpdir() as tmp:
assert os.path.exists(tmp)
assert os.path.isdir(tmp)
def test_tmpdir_cleans_up(self):
"""Test that tmpdir cleans up after use."""
tmp_path = None
with _tmpdir() as tmp:
tmp_path = tmp
assert os.path.exists(tmp_path)
assert not os.path.exists(tmp_path)
def test_tmpdir_with_prefix(self):
"""Test tmpdir with custom prefix."""
with _tmpdir(prefix="test_") as tmp:
assert "test_" in os.path.basename(tmp)
def test_tmpdir_with_suffix(self):
"""Test tmpdir with custom suffix."""
with _tmpdir(suffix="_test") as tmp:
assert os.path.basename(tmp).endswith("_test")
def test_tmpdir_with_directory(self, tmp_path):
"""Test tmpdir with custom directory."""
with _tmpdir(directory=str(tmp_path)) as tmp:
assert str(tmp_path) in tmp
def test_tmpdir_invalid_directory(self):
"""Test tmpdir with invalid directory."""
with pytest.raises(ValueError):
with _tmpdir(directory="/nonexistent/path"):
pass
class TestStsRegionalEndpoint:
"""Test sts_regional_endpoint function."""
def test_sts_regional_endpoint_standard(self):
"""Test STS endpoint for standard region."""
result = sts_regional_endpoint("us-west-2")
assert "sts" in result
assert "us-west-2" in result
assert result.startswith("https://")
def test_sts_regional_endpoint_china(self):
"""Test STS endpoint for China region."""
result = sts_regional_endpoint("cn-north-1")
assert "sts" in result
assert result.startswith("https://")
def test_sts_regional_endpoint_govcloud(self):
"""Test STS endpoint for GovCloud region."""
result = sts_regional_endpoint("us-gov-west-1")
assert "sts" in result
assert result.startswith("https://")
class TestRetries:
"""Test retries generator function."""
def test_retries_basic(self):
"""Test basic retry functionality."""
max_retries = 3
count = 0
for i in retries(max_retries, "test", seconds_to_sleep=0.01):
count += 1
if count < max_retries:
continue
break
assert count == max_retries
def test_retries_raises_exception(self):
"""Test that retries raises exception after max attempts."""
with pytest.raises(Exception, match="maximum retry count"):
for i in retries(2, "test operation", seconds_to_sleep=0.01):
pass
def test_retries_with_success(self):
"""Test retries with successful operation."""
count = 0
for i in retries(5, "test", seconds_to_sleep=0.01):
count += 1
if count == 2:
break
assert count == 2
class TestRetryWithBackoff:
"""Test retry_with_backoff function."""
def test_retry_with_backoff_success(self):
"""Test successful retry."""
mock_func = Mock(return_value="success")
result = retry_with_backoff(mock_func, num_attempts=3)
assert result == "success"
mock_func.assert_called_once()
def test_retry_with_backoff_eventual_success(self):
"""Test eventual success after retries."""
mock_func = Mock(side_effect=[Exception("error"), Exception("error"), "success"])
result = retry_with_backoff(mock_func, num_attempts=3)
assert result == "success"
assert mock_func.call_count == 3
def test_retry_with_backoff_max_attempts(self):
"""Test max attempts reached."""
mock_func = Mock(side_effect=Exception("error"))
with pytest.raises(Exception, match="error"):
retry_with_backoff(mock_func, num_attempts=2)
assert mock_func.call_count == 2
def test_retry_with_backoff_client_error(self):
"""Test with specific ClientError."""
error = ClientError(
{"Error": {"Code": "ThrottlingException", "Message": "Rate exceeded"}}, "operation"
)
mock_func = Mock(side_effect=[error, "success"])
result = retry_with_backoff(
mock_func, num_attempts=3, botocore_client_error_code="ThrottlingException"
)
assert result == "success"
def test_retry_with_backoff_invalid_attempts(self):
"""Test with invalid number of attempts."""
mock_func = Mock()
with pytest.raises(ValueError):
retry_with_backoff(mock_func, num_attempts=0)
class TestAwsPartition:
"""Test aws_partition function."""
def test_aws_partition_standard(self):
"""Test standard AWS partition."""
result = aws_partition("us-west-2")
assert result == "aws"
def test_aws_partition_china(self):
"""Test China partition."""
result = aws_partition("cn-north-1")
assert result == "aws-cn"
def test_aws_partition_govcloud(self):
"""Test GovCloud partition."""
result = aws_partition("us-gov-west-1")
assert result == "aws-us-gov"
class TestGetResourceNameFromArn:
"""Test get_resource_name_from_arn function."""
def test_get_resource_name_from_arn_endpoint(self):
"""Test extracting endpoint name from ARN."""
arn = "arn:aws:sagemaker:us-west-2:123456789012:endpoint/my-endpoint"
result = get_resource_name_from_arn(arn)
assert result == "my-endpoint"
def test_get_resource_name_from_arn_model(self):
"""Test extracting model name from ARN."""
arn = "arn:aws:sagemaker:us-west-2:123456789012:model/my-model"
result = get_resource_name_from_arn(arn)
assert result == "my-model"
def test_get_resource_name_from_arn_training_job(self):
"""Test extracting training job name from ARN."""
arn = "arn:aws:sagemaker:us-west-2:123456789012:training-job/my-training-job"
result = get_resource_name_from_arn(arn)
assert result == "my-training-job"
def test_get_resource_name_from_arn_with_path(self):
"""Test extracting resource name with path."""
arn = "arn:aws:sagemaker:us-west-2:123456789012:endpoint-config/path/to/config"
result = get_resource_name_from_arn(arn)
assert result == "path/to/config"
class TestPopOutUnusedKwarg:
"""Test pop_out_unused_kwarg function."""
def test_pop_out_unused_kwarg_present(self):
"""Test popping present kwarg."""
kwargs = {"arg1": "value1", "arg2": "value2"}
pop_out_unused_kwarg("arg1", kwargs)
assert "arg1" not in kwargs
assert "arg2" in kwargs
def test_pop_out_unused_kwarg_not_present(self):
"""Test popping non-existent kwarg."""
kwargs = {"arg1": "value1"}
pop_out_unused_kwarg("arg2", kwargs)
assert kwargs == {"arg1": "value1"}
def test_pop_out_unused_kwarg_with_override(self):
"""Test popping kwarg with override value."""
kwargs = {"arg1": "value1"}
pop_out_unused_kwarg("arg1", kwargs, override_val="new_value")
assert "arg1" not in kwargs
class TestToString:
"""Test to_string function."""
def test_to_string_basic(self):
"""Test converting basic object to string."""
result = to_string("test")
assert result == "test"
def test_to_string_number(self):
"""Test converting number to string."""
result = to_string(123)
assert result == "123"
def test_to_string_none(self):
"""Test converting None to string."""
result = to_string(None)
assert result == "None"
class TestGetModule:
"""Test get_module function."""
def test_get_module_existing(self):
"""Test importing existing module."""
result = get_module("os")
assert result is not None
assert hasattr(result, "path")
def test_get_module_nonexistent(self):
"""Test importing non-existent module."""
with pytest.raises(Exception, match="Cannot import module"):
get_module("nonexistent_module_xyz")
def test_get_module_builtin(self):
"""Test importing built-in module."""
result = get_module("sys")
assert result is not None
assert hasattr(result, "version")
class TestResolveValueFromConfig:
"""Test resolve_value_from_config function."""
def test_resolve_value_from_config_direct_input(self):
"""Test with direct input provided."""
result = resolve_value_from_config(
direct_input="direct_value", config_path="some.path", default_value="default_value"
)
assert result == "direct_value"
def test_resolve_value_from_config_default(self):
"""Test with default value."""
result = resolve_value_from_config(
direct_input=None, config_path=None, default_value="default_value"
)
assert result == "default_value"
def test_resolve_value_from_config_none(self):
"""Test with all None values."""
result = resolve_value_from_config(direct_input=None, config_path=None, default_value=None)
assert result is None
@patch("sagemaker.core.common_utils.get_sagemaker_config_value")
def test_resolve_value_from_config_from_config(self, mock_get_config):
"""Test with value from config."""
mock_get_config.return_value = "config_value"
result = resolve_value_from_config(
direct_input=None,
config_path="some.path",
default_value="default_value",
sagemaker_session=Mock(),
)
assert result == "config_value"
class TestGetSagemakerConfigValue:
"""Test get_sagemaker_config_value function."""
@patch("sagemaker.core.common_utils.get_config_value")
@patch("sagemaker.core.config.config_manager.SageMakerConfig")
def test_get_sagemaker_config_value_from_session(self, mock_config_manager, mock_get_config):
"""Test getting config value from session."""
mock_config_manager.return_value.validate_sagemaker_config = Mock()
mock_session = Mock()
mock_session.sagemaker_config = {"SchemaVersion": "1.0", "key": "value"}
mock_get_config.return_value = "value"
result = get_sagemaker_config_value(mock_session, "key")
assert result == "value"
@patch("sagemaker.core.common_utils.get_config_value")
@patch("sagemaker.core.config.config_manager.SageMakerConfig")
def test_get_sagemaker_config_value_from_dict(self, mock_config_manager, mock_get_config):
"""Test getting config value from dict."""
mock_config_manager.return_value.validate_sagemaker_config = Mock()
mock_get_config.return_value = "value"
result = get_sagemaker_config_value(
None, "key", sagemaker_config={"SchemaVersion": "1.0", "key": "value"}
)
assert result == "value"
def test_get_sagemaker_config_value_no_config(self):
"""Test with no config available."""
result = get_sagemaker_config_value(None, "key")
assert result is None
@patch("sagemaker.core.common_utils.get_config_value")
@patch("sagemaker.core.config.config_manager.SageMakerConfig")
def test_get_sagemaker_config_value_nested(self, mock_config_manager, mock_get_config):
"""Test getting nested config value."""
mock_config_manager.return_value.validate_sagemaker_config = Mock()
mock_session = Mock()
mock_session.sagemaker_config = {"SchemaVersion": "1.0", "level1": {"level2": "value"}}
mock_get_config.return_value = "value"
result = get_sagemaker_config_value(mock_session, "level1.level2")
assert result == "value"
class TestDeferredError:
"""Test DeferredError class."""
def test_deferred_error_raises_on_access(self):
"""Test that DeferredError raises exception on access."""
from sagemaker.core.common_utils import DeferredError
original_error = ImportError("Module not found")
deferred = DeferredError(original_error)
with pytest.raises(ImportError, match="Module not found"):
_ = deferred.some_attribute
def test_deferred_error_raises_on_method_call(self):
"""Test that DeferredError raises exception on method call."""
from sagemaker.core.common_utils import DeferredError
original_error = ImportError("Module not found")
deferred = DeferredError(original_error)
with pytest.raises(ImportError):
deferred.some_method()
class TestS3DataConfig:
"""Test S3DataConfig class."""
def test_s3_data_config_init(self):
"""Test S3DataConfig initialization."""
from sagemaker.core.common_utils import S3DataConfig
mock_session = Mock()
config = S3DataConfig(
sagemaker_session=mock_session, bucket_name="test-bucket", prefix="test-prefix"
)
assert config.bucket_name == "test-bucket"
assert config.prefix == "test-prefix"
assert config.sagemaker_session == mock_session
def test_s3_data_config_missing_bucket(self):
"""Test S3DataConfig with missing bucket."""
from sagemaker.core.common_utils import S3DataConfig
with pytest.raises(ValueError):
S3DataConfig(sagemaker_session=Mock(), bucket_name=None, prefix="test-prefix")
def test_s3_data_config_fetch_data_config(self):
"""Test fetching data config from S3."""
from sagemaker.core.common_utils import S3DataConfig
mock_session = Mock()
mock_session.read_s3_file.return_value = '{"key": "value"}'
config = S3DataConfig(
sagemaker_session=mock_session, bucket_name="test-bucket", prefix="test-prefix"
)
result = config.fetch_data_config()
assert result == {"key": "value"}
mock_session.read_s3_file.assert_called_once_with("test-bucket", "test-prefix")
class TestDownloadFolder:
"""Test download_folder function."""
def test_download_folder_single_file(self):
"""Test downloading single file."""
from sagemaker.core.common_utils import download_folder
mock_session = Mock()
mock_s3 = Mock()
mock_obj = Mock()
mock_session.s3_resource = mock_s3
mock_s3.Object.return_value = mock_obj
with tempfile.TemporaryDirectory() as tmpdir:
download_folder("bucket", "file.txt", tmpdir, mock_session)
mock_obj.download_file.assert_called_once()
def test_download_folder_with_prefix(self):
"""Test downloading folder with prefix."""
from sagemaker.core.common_utils import download_folder
mock_session = Mock()
mock_s3 = Mock()
mock_bucket = Mock()
mock_session.s3_resource = mock_s3
mock_s3.Bucket.return_value = mock_bucket
mock_bucket.objects.filter.return_value = []
mock_obj = Mock()
mock_obj.download_file.side_effect = ClientError(
{"Error": {"Code": "404", "Message": "Not Found"}}, "operation"
)
mock_s3.Object.return_value = mock_obj
with tempfile.TemporaryDirectory() as tmpdir:
download_folder("bucket", "prefix/", tmpdir, mock_session)
class TestRepackModel:
"""Test repack_model function."""
def test_repack_model_basic(self, tmp_path):
"""Test basic model repacking."""
from sagemaker.core.common_utils import repack_model
# Create test files
model_dir = tmp_path / "model"
model_dir.mkdir()
(model_dir / "model.pth").write_text("model data")
model_tar = tmp_path / "model.tar.gz"
with tarfile.open(model_tar, "w:gz") as tar:
tar.add(model_dir, arcname=".")
script = tmp_path / "inference.py"
script.write_text("# inference script")
output = tmp_path / "output.tar.gz"
mock_session = Mock()
mock_session.settings = None
repack_model(str(script), None, [], f"file://{model_tar}", f"file://{output}", mock_session)
assert output.exists()
class TestVolumeSupported:
"""Test volume_size_supported function."""
def test_volume_size_supported_standard(self):
"""Test standard instance type."""
from sagemaker.core.common_utils import volume_size_supported
assert volume_size_supported("ml.m5.xlarge") is True
def test_volume_size_supported_with_d(self):
"""Test instance with d in family."""
from sagemaker.core.common_utils import volume_size_supported
assert volume_size_supported("ml.c5d.xlarge") is False
def test_volume_size_supported_g5(self):
"""Test g5 instance."""
from sagemaker.core.common_utils import volume_size_supported
assert volume_size_supported("ml.g5.xlarge") is False
def test_volume_size_supported_local(self):
"""Test local mode."""