-
Notifications
You must be signed in to change notification settings - Fork 14.5k
/
test_sagemaker.py
911 lines (809 loc) · 38.9 KB
/
test_sagemaker.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
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License 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.
from __future__ import annotations
import time
from datetime import datetime
from unittest import mock
from unittest.mock import patch
import pytest
from botocore.exceptions import ClientError
from dateutil.tz import tzlocal
from moto import mock_sagemaker
from airflow.exceptions import AirflowException
from airflow.providers.amazon.aws.hooks.logs import AwsLogsHook
from airflow.providers.amazon.aws.hooks.s3 import S3Hook
from airflow.providers.amazon.aws.hooks.sagemaker import (
LogState,
SageMakerHook,
secondary_training_status_changed,
secondary_training_status_message,
)
role = "arn:aws:iam:role/test-role"
path = "local/data"
bucket = "test-bucket"
key = "test/data"
data_url = f"s3://{bucket}/{key}"
job_name = "test-job"
model_name = "test-model"
config_name = "test-endpoint-config"
endpoint_name = "test-endpoint"
image = "test-image"
test_arn_return = {"Arn": "testarn"}
output_url = f"s3://{bucket}/test/output"
create_training_params = {
"AlgorithmSpecification": {"TrainingImage": image, "TrainingInputMode": "File"},
"RoleArn": role,
"OutputDataConfig": {"S3OutputPath": output_url},
"ResourceConfig": {"InstanceCount": 2, "InstanceType": "ml.c4.8xlarge", "VolumeSizeInGB": 50},
"TrainingJobName": job_name,
"HyperParameters": {"k": "10", "feature_dim": "784", "mini_batch_size": "500", "force_dense": "True"},
"StoppingCondition": {"MaxRuntimeInSeconds": 60 * 60},
"InputDataConfig": [
{
"ChannelName": "train",
"DataSource": {
"S3DataSource": {
"S3DataType": "S3Prefix",
"S3Uri": data_url,
"S3DataDistributionType": "FullyReplicated",
}
},
"CompressionType": "None",
"RecordWrapperType": "None",
},
{
"ChannelName": "train_fs",
"DataSource": {
"FileSystemDataSource": {
"DirectoryPath": "/tmp",
"FileSystemAccessMode": "ro",
"FileSystemId": "fs-abc",
"FileSystemType": "FSxLustre",
}
},
"CompressionType": "None",
"RecordWrapperType": "None",
},
],
}
create_tuning_params = {
"HyperParameterTuningJobName": job_name,
"HyperParameterTuningJobConfig": {
"Strategy": "Bayesian",
"HyperParameterTuningJobObjective": {"Type": "Maximize", "MetricName": "test_metric"},
"ResourceLimits": {"MaxNumberOfTrainingJobs": 123, "MaxParallelTrainingJobs": 123},
"ParameterRanges": {
"IntegerParameterRanges": [
{"Name": "k", "MinValue": "2", "MaxValue": "10"},
]
},
},
"TrainingJobDefinition": {
"StaticHyperParameters": create_training_params["HyperParameters"],
"AlgorithmSpecification": create_training_params["AlgorithmSpecification"],
"RoleArn": "string",
"InputDataConfig": create_training_params["InputDataConfig"],
"OutputDataConfig": create_training_params["OutputDataConfig"],
"ResourceConfig": create_training_params["ResourceConfig"],
"StoppingCondition": dict(MaxRuntimeInSeconds=60 * 60),
},
}
create_transform_params = {
"TransformJobName": job_name,
"ModelName": model_name,
"BatchStrategy": "MultiRecord",
"TransformInput": {"DataSource": {"S3DataSource": {"S3DataType": "S3Prefix", "S3Uri": data_url}}},
"TransformOutput": {
"S3OutputPath": output_url,
},
"TransformResources": {"InstanceType": "ml.m4.xlarge", "InstanceCount": 123},
}
create_transform_params_fs = {
"TransformJobName": job_name,
"ModelName": model_name,
"BatchStrategy": "MultiRecord",
"TransformInput": {
"DataSource": {
"FileSystemDataSource": {
"DirectoryPath": "/tmp",
"FileSystemAccessMode": "ro",
"FileSystemId": "fs-abc",
"FileSystemType": "FSxLustre",
}
}
},
"TransformOutput": {
"S3OutputPath": output_url,
},
"TransformResources": {"InstanceType": "ml.m4.xlarge", "InstanceCount": 123},
}
create_model_params = {
"ModelName": model_name,
"PrimaryContainer": {
"Image": image,
"ModelDataUrl": output_url,
},
"ExecutionRoleArn": role,
}
create_endpoint_config_params = {
"EndpointConfigName": config_name,
"ProductionVariants": [
{
"VariantName": "AllTraffic",
"ModelName": model_name,
"InitialInstanceCount": 1,
"InstanceType": "ml.c4.xlarge",
}
],
}
create_endpoint_params = {"EndpointName": endpoint_name, "EndpointConfigName": config_name}
update_endpoint_params = create_endpoint_params
DESCRIBE_TRAINING_COMPLETED_RETURN = {
"TrainingJobStatus": "Completed",
"ResourceConfig": {"InstanceCount": 1, "InstanceType": "ml.c4.xlarge", "VolumeSizeInGB": 10},
"TrainingStartTime": datetime(2018, 2, 17, 7, 15, 0, 103000),
"TrainingEndTime": datetime(2018, 2, 17, 7, 19, 34, 953000),
"ResponseMetadata": {
"HTTPStatusCode": 200,
},
}
DESCRIBE_TRAINING_INPROGRESS_RETURN = dict(DESCRIBE_TRAINING_COMPLETED_RETURN)
DESCRIBE_TRAINING_INPROGRESS_RETURN.update({"TrainingJobStatus": "InProgress"})
DESCRIBE_TRAINING_FAILED_RETURN = dict(DESCRIBE_TRAINING_COMPLETED_RETURN)
DESCRIBE_TRAINING_FAILED_RETURN.update({"TrainingJobStatus": "Failed", "FailureReason": "Unknown"})
DESCRIBE_TRAINING_STOPPING_RETURN = dict(DESCRIBE_TRAINING_COMPLETED_RETURN)
DESCRIBE_TRAINING_STOPPING_RETURN.update({"TrainingJobStatus": "Stopping"})
message = "message"
status = "status"
SECONDARY_STATUS_DESCRIPTION_1 = {
"SecondaryStatusTransitions": [{"StatusMessage": message, "Status": status}]
}
SECONDARY_STATUS_DESCRIPTION_2 = {
"SecondaryStatusTransitions": [{"StatusMessage": "different message", "Status": status}]
}
DEFAULT_LOG_STREAMS = {"logStreams": [{"logStreamName": job_name + "/xxxxxxxxx"}]}
LIFECYCLE_LOG_STREAMS = [
DEFAULT_LOG_STREAMS,
DEFAULT_LOG_STREAMS,
DEFAULT_LOG_STREAMS,
DEFAULT_LOG_STREAMS,
DEFAULT_LOG_STREAMS,
DEFAULT_LOG_STREAMS,
]
DEFAULT_LOG_EVENTS = [
{"nextForwardToken": None, "events": [{"timestamp": 1, "message": "hi there #1"}]},
{"nextForwardToken": None, "events": []},
]
STREAM_LOG_EVENTS = [
{"nextForwardToken": None, "events": [{"timestamp": 1, "message": "hi there #1"}]},
{"nextForwardToken": None, "events": []},
{
"nextForwardToken": None,
"events": [{"timestamp": 1, "message": "hi there #1"}, {"timestamp": 2, "message": "hi there #2"}],
},
{"nextForwardToken": None, "events": []},
{
"nextForwardToken": None,
"events": [
{"timestamp": 2, "message": "hi there #2"},
{"timestamp": 2, "message": "hi there #2a"},
{"timestamp": 3, "message": "hi there #3"},
],
},
{"nextForwardToken": None, "events": []},
]
test_evaluation_config = {
"Image": image,
"Role": role,
"S3Operations": {
"S3CreateBucket": [{"Bucket": bucket}],
"S3Upload": [{"Path": path, "Bucket": bucket, "Key": key, "Tar": False}],
},
}
class TestSageMakerHook:
@mock.patch.object(AwsLogsHook, "get_log_events")
def test_multi_stream_iter(self, mock_log_stream):
event = {"timestamp": 1}
mock_log_stream.side_effect = [iter([event]), iter([]), None]
hook = SageMakerHook()
event_iter = hook.multi_stream_iter("log", [None, None, None])
assert next(event_iter) == (0, event)
@mock.patch.object(S3Hook, "create_bucket")
@mock.patch.object(S3Hook, "load_file")
def test_configure_s3_resources(self, mock_load_file, mock_create_bucket):
hook = SageMakerHook()
evaluation_result = {"Image": image, "Role": role}
hook.configure_s3_resources(test_evaluation_config)
assert test_evaluation_config == evaluation_result
mock_create_bucket.assert_called_once_with(bucket_name=bucket)
mock_load_file.assert_called_once_with(path, key, bucket)
@mock.patch.object(SageMakerHook, "get_conn")
@mock.patch.object(S3Hook, "check_for_key")
@mock.patch.object(S3Hook, "check_for_bucket")
@mock.patch.object(S3Hook, "check_for_prefix")
def test_check_s3_url(self, mock_check_prefix, mock_check_bucket, mock_check_key, mock_client):
mock_client.return_value = None
hook = SageMakerHook()
mock_check_bucket.side_effect = [False, True, True, True]
mock_check_key.side_effect = [False, True, False]
mock_check_prefix.side_effect = [False, True, True]
with pytest.raises(AirflowException):
hook.check_s3_url(data_url)
with pytest.raises(AirflowException):
hook.check_s3_url(data_url)
assert hook.check_s3_url(data_url) is True
assert hook.check_s3_url(data_url) is True
@mock.patch.object(SageMakerHook, "get_conn")
@mock.patch.object(SageMakerHook, "check_s3_url")
def test_check_valid_training(self, mock_check_url, mock_client):
mock_client.return_value = None
hook = SageMakerHook()
hook.check_training_config(create_training_params)
mock_check_url.assert_called_once_with(data_url)
# InputDataConfig is optional, verify if check succeeds without InputDataConfig
create_training_params_no_inputdataconfig = create_training_params.copy()
create_training_params_no_inputdataconfig.pop("InputDataConfig")
hook.check_training_config(create_training_params_no_inputdataconfig)
@mock.patch.object(SageMakerHook, "get_conn")
@mock.patch.object(SageMakerHook, "check_s3_url")
def test_check_valid_tuning(self, mock_check_url, mock_client):
mock_client.return_value = None
hook = SageMakerHook()
hook.check_tuning_config(create_tuning_params)
mock_check_url.assert_called_once_with(data_url)
def test_conn(self):
hook = SageMakerHook(aws_conn_id="sagemaker_test_conn_id")
assert hook.aws_conn_id == "sagemaker_test_conn_id"
@mock.patch.object(SageMakerHook, "check_training_config")
@mock.patch.object(SageMakerHook, "get_conn")
def test_create_training_job(self, mock_client, mock_check_training):
mock_check_training.return_value = True
mock_session = mock.Mock()
attrs = {"create_training_job.return_value": test_arn_return}
mock_session.configure_mock(**attrs)
mock_client.return_value = mock_session
hook = SageMakerHook(aws_conn_id="sagemaker_test_conn_id")
response = hook.create_training_job(
create_training_params, wait_for_completion=False, print_log=False
)
mock_session.create_training_job.assert_called_once_with(**create_training_params)
assert response == test_arn_return
@mock.patch.object(SageMakerHook, "check_training_config")
@mock.patch.object(SageMakerHook, "get_conn")
@mock.patch("time.sleep", return_value=None)
def test_training_ends_with_wait(self, _, mock_client, mock_check_training):
mock_check_training.return_value = True
mock_session = mock.Mock()
attrs = {
"create_training_job.return_value": test_arn_return,
"describe_training_job.side_effect": [
DESCRIBE_TRAINING_INPROGRESS_RETURN,
DESCRIBE_TRAINING_STOPPING_RETURN,
DESCRIBE_TRAINING_COMPLETED_RETURN,
],
}
mock_session.configure_mock(**attrs)
mock_client.return_value = mock_session
hook = SageMakerHook(aws_conn_id="sagemaker_test_conn_id_1")
hook.create_training_job(
create_training_params, wait_for_completion=True, print_log=False, check_interval=0
)
assert mock_session.describe_training_job.call_count == 3
@mock.patch.object(SageMakerHook, "check_training_config")
@mock.patch.object(SageMakerHook, "get_conn")
@mock.patch("time.sleep", return_value=None)
def test_training_throws_error_when_failed_with_wait(self, _, mock_client, mock_check_training):
mock_check_training.return_value = True
mock_session = mock.Mock()
attrs = {
"create_training_job.return_value": test_arn_return,
"describe_training_job.side_effect": [
DESCRIBE_TRAINING_INPROGRESS_RETURN,
DESCRIBE_TRAINING_STOPPING_RETURN,
DESCRIBE_TRAINING_FAILED_RETURN,
DESCRIBE_TRAINING_COMPLETED_RETURN,
],
}
mock_session.configure_mock(**attrs)
mock_client.return_value = mock_session
hook = SageMakerHook(aws_conn_id="sagemaker_test_conn_id_1")
with pytest.raises(AirflowException):
hook.create_training_job(
create_training_params,
wait_for_completion=True,
print_log=False,
check_interval=0,
)
assert mock_session.describe_training_job.call_count == 3
@mock.patch.object(SageMakerHook, "check_tuning_config")
@mock.patch.object(SageMakerHook, "get_conn")
def test_create_tuning_job(self, mock_client, mock_check_tuning_config):
mock_session = mock.Mock()
attrs = {"create_hyper_parameter_tuning_job.return_value": test_arn_return}
mock_session.configure_mock(**attrs)
mock_client.return_value = mock_session
hook = SageMakerHook(aws_conn_id="sagemaker_test_conn_id")
response = hook.create_tuning_job(create_tuning_params, wait_for_completion=False)
mock_session.create_hyper_parameter_tuning_job.assert_called_once_with(**create_tuning_params)
assert response == test_arn_return
@mock.patch.object(SageMakerHook, "check_s3_url")
@mock.patch.object(SageMakerHook, "get_conn")
def test_create_transform_job(self, mock_client, mock_check_url):
mock_check_url.return_value = True
mock_session = mock.Mock()
attrs = {"create_transform_job.return_value": test_arn_return}
mock_session.configure_mock(**attrs)
mock_client.return_value = mock_session
hook = SageMakerHook(aws_conn_id="sagemaker_test_conn_id")
response = hook.create_transform_job(create_transform_params, wait_for_completion=False)
mock_session.create_transform_job.assert_called_once_with(**create_transform_params)
assert response == test_arn_return
@mock.patch.object(SageMakerHook, "get_conn")
def test_create_transform_job_fs(self, mock_client):
mock_session = mock.Mock()
attrs = {"create_transform_job.return_value": test_arn_return}
mock_session.configure_mock(**attrs)
mock_client.return_value = mock_session
hook = SageMakerHook(aws_conn_id="sagemaker_test_conn_id")
response = hook.create_transform_job(create_transform_params_fs, wait_for_completion=False)
mock_session.create_transform_job.assert_called_once_with(**create_transform_params_fs)
assert response == test_arn_return
@mock.patch.object(SageMakerHook, "get_conn")
def test_create_model(self, mock_client):
mock_session = mock.Mock()
attrs = {"create_model.return_value": test_arn_return}
mock_session.configure_mock(**attrs)
mock_client.return_value = mock_session
hook = SageMakerHook(aws_conn_id="sagemaker_test_conn_id")
response = hook.create_model(create_model_params)
mock_session.create_model.assert_called_once_with(**create_model_params)
assert response == test_arn_return
@mock.patch.object(SageMakerHook, "get_conn")
def test_create_endpoint_config(self, mock_client):
mock_session = mock.Mock()
attrs = {"create_endpoint_config.return_value": test_arn_return}
mock_session.configure_mock(**attrs)
mock_client.return_value = mock_session
hook = SageMakerHook(aws_conn_id="sagemaker_test_conn_id")
response = hook.create_endpoint_config(create_endpoint_config_params)
mock_session.create_endpoint_config.assert_called_once_with(**create_endpoint_config_params)
assert response == test_arn_return
@mock.patch.object(SageMakerHook, "get_conn")
def test_create_endpoint(self, mock_client):
mock_session = mock.Mock()
attrs = {"create_endpoint.return_value": test_arn_return}
mock_session.configure_mock(**attrs)
mock_client.return_value = mock_session
hook = SageMakerHook(aws_conn_id="sagemaker_test_conn_id")
response = hook.create_endpoint(create_endpoint_params, wait_for_completion=False)
mock_session.create_endpoint.assert_called_once_with(**create_endpoint_params)
assert response == test_arn_return
@mock.patch.object(SageMakerHook, "get_conn")
def test_update_endpoint(self, mock_client):
mock_session = mock.Mock()
attrs = {"update_endpoint.return_value": test_arn_return}
mock_session.configure_mock(**attrs)
mock_client.return_value = mock_session
hook = SageMakerHook(aws_conn_id="sagemaker_test_conn_id")
response = hook.update_endpoint(update_endpoint_params, wait_for_completion=False)
mock_session.update_endpoint.assert_called_once_with(**update_endpoint_params)
assert response == test_arn_return
@mock.patch.object(SageMakerHook, "get_conn")
def test_describe_training_job(self, mock_client):
mock_session = mock.Mock()
attrs = {"describe_training_job.return_value": "InProgress"}
mock_session.configure_mock(**attrs)
mock_client.return_value = mock_session
hook = SageMakerHook(aws_conn_id="sagemaker_test_conn_id")
response = hook.describe_training_job(job_name)
mock_session.describe_training_job.assert_called_once_with(TrainingJobName=job_name)
assert response == "InProgress"
@mock.patch.object(SageMakerHook, "get_conn")
def test_describe_tuning_job(self, mock_client):
mock_session = mock.Mock()
attrs = {"describe_hyper_parameter_tuning_job.return_value": "InProgress"}
mock_session.configure_mock(**attrs)
mock_client.return_value = mock_session
hook = SageMakerHook(aws_conn_id="sagemaker_test_conn_id")
response = hook.describe_tuning_job(job_name)
mock_session.describe_hyper_parameter_tuning_job.assert_called_once_with(
HyperParameterTuningJobName=job_name
)
assert response == "InProgress"
@mock.patch.object(SageMakerHook, "get_conn")
def test_describe_transform_job(self, mock_client):
mock_session = mock.Mock()
attrs = {"describe_transform_job.return_value": "InProgress"}
mock_session.configure_mock(**attrs)
mock_client.return_value = mock_session
hook = SageMakerHook(aws_conn_id="sagemaker_test_conn_id")
response = hook.describe_transform_job(job_name)
mock_session.describe_transform_job.assert_called_once_with(TransformJobName=job_name)
assert response == "InProgress"
@mock.patch.object(SageMakerHook, "get_conn")
def test_describe_model(self, mock_client):
mock_session = mock.Mock()
attrs = {"describe_model.return_value": model_name}
mock_session.configure_mock(**attrs)
mock_client.return_value = mock_session
hook = SageMakerHook(aws_conn_id="sagemaker_test_conn_id")
response = hook.describe_model(model_name)
mock_session.describe_model.assert_called_once_with(ModelName=model_name)
assert response == model_name
@mock.patch.object(SageMakerHook, "get_conn")
def test_describe_endpoint_config(self, mock_client):
mock_session = mock.Mock()
attrs = {"describe_endpoint_config.return_value": config_name}
mock_session.configure_mock(**attrs)
mock_client.return_value = mock_session
hook = SageMakerHook(aws_conn_id="sagemaker_test_conn_id")
response = hook.describe_endpoint_config(config_name)
mock_session.describe_endpoint_config.assert_called_once_with(EndpointConfigName=config_name)
assert response == config_name
@mock.patch.object(SageMakerHook, "get_conn")
def test_describe_endpoint(self, mock_client):
mock_session = mock.Mock()
attrs = {"describe_endpoint.return_value": "InProgress"}
mock_session.configure_mock(**attrs)
mock_client.return_value = mock_session
hook = SageMakerHook(aws_conn_id="sagemaker_test_conn_id")
response = hook.describe_endpoint(endpoint_name)
mock_session.describe_endpoint.assert_called_once_with(EndpointName=endpoint_name)
assert response == "InProgress"
def test_secondary_training_status_changed_true(self):
changed = secondary_training_status_changed(
SECONDARY_STATUS_DESCRIPTION_1, SECONDARY_STATUS_DESCRIPTION_2
)
assert changed
def test_secondary_training_status_changed_false(self):
changed = secondary_training_status_changed(
SECONDARY_STATUS_DESCRIPTION_1, SECONDARY_STATUS_DESCRIPTION_1
)
assert not changed
def test_secondary_training_status_message_status_changed(self):
now = datetime.now(tzlocal())
SECONDARY_STATUS_DESCRIPTION_1["LastModifiedTime"] = now
expected_time = datetime.utcfromtimestamp(time.mktime(now.timetuple())).strftime("%Y-%m-%d %H:%M:%S")
expected = f"{expected_time} {status} - {message}"
assert (
secondary_training_status_message(SECONDARY_STATUS_DESCRIPTION_1, SECONDARY_STATUS_DESCRIPTION_2)
== expected
)
@mock.patch.object(AwsLogsHook, "conn")
@mock.patch.object(SageMakerHook, "get_conn")
@mock.patch.object(time, "monotonic")
def test_describe_training_job_with_logs_in_progress(self, mock_time, mock_client, mock_log_client):
mock_session = mock.Mock()
mock_log_session = mock.Mock()
attrs = {"describe_training_job.return_value": DESCRIBE_TRAINING_COMPLETED_RETURN}
log_attrs = {
"describe_log_streams.side_effect": LIFECYCLE_LOG_STREAMS,
"get_log_events.side_effect": STREAM_LOG_EVENTS,
}
mock_time.return_value = 50
mock_session.configure_mock(**attrs)
mock_client.return_value = mock_session
mock_log_session.configure_mock(**log_attrs)
mock_log_client.return_value = mock_log_session
hook = SageMakerHook(aws_conn_id="sagemaker_test_conn_id")
response = hook.describe_training_job_with_log(
job_name=job_name,
positions={},
stream_names=[],
instance_count=1,
state=LogState.WAIT_IN_PROGRESS,
last_description={},
last_describe_job_call=0,
)
assert response == (LogState.JOB_COMPLETE, {}, 50)
@pytest.mark.parametrize("log_state", [LogState.JOB_COMPLETE, LogState.COMPLETE])
@mock.patch.object(AwsLogsHook, "conn")
@mock.patch.object(SageMakerHook, "get_conn")
def test_describe_training_job_with_complete_states(self, mock_client, mock_log_client, log_state):
mock_session = mock.Mock()
mock_log_session = mock.Mock()
attrs = {"describe_training_job.return_value": DESCRIBE_TRAINING_COMPLETED_RETURN}
log_attrs = {
"describe_log_streams.side_effect": LIFECYCLE_LOG_STREAMS,
"get_log_events.side_effect": STREAM_LOG_EVENTS,
}
mock_session.configure_mock(**attrs)
mock_client.return_value = mock_session
mock_log_session.configure_mock(**log_attrs)
mock_log_client.return_value = mock_log_session
hook = SageMakerHook(aws_conn_id="sagemaker_test_conn_id")
response = hook.describe_training_job_with_log(
job_name=job_name,
positions={},
stream_names=[],
instance_count=1,
state=log_state,
last_description={},
last_describe_job_call=0,
)
assert response == (LogState.COMPLETE, {}, 0)
@mock.patch.object(SageMakerHook, "check_training_config")
@mock.patch.object(AwsLogsHook, "conn")
@mock.patch.object(SageMakerHook, "get_conn")
@mock.patch.object(SageMakerHook, "describe_training_job_with_log")
@mock.patch("time.sleep", return_value=None)
def test_training_with_logs(self, _, mock_describe, mock_client, mock_log_client, mock_check_training):
mock_check_training.return_value = True
mock_describe.side_effect = [
(LogState.WAIT_IN_PROGRESS, DESCRIBE_TRAINING_INPROGRESS_RETURN, 0),
(LogState.JOB_COMPLETE, DESCRIBE_TRAINING_STOPPING_RETURN, 0),
(LogState.COMPLETE, DESCRIBE_TRAINING_COMPLETED_RETURN, 0),
]
mock_session = mock.Mock()
mock_log_session = mock.Mock()
attrs = {
"create_training_job.return_value": test_arn_return,
"describe_training_job.return_value": DESCRIBE_TRAINING_COMPLETED_RETURN,
}
log_attrs = {
"describe_log_streams.side_effect": LIFECYCLE_LOG_STREAMS,
"get_log_events.side_effect": STREAM_LOG_EVENTS,
}
mock_session.configure_mock(**attrs)
mock_log_session.configure_mock(**log_attrs)
mock_client.return_value = mock_session
mock_log_client.return_value = mock_log_session
hook = SageMakerHook(aws_conn_id="sagemaker_test_conn_id_1")
hook.create_training_job(
create_training_params, wait_for_completion=True, print_log=True, check_interval=0
)
assert mock_describe.call_count == 3
assert mock_session.describe_training_job.call_count == 1
@mock.patch.object(SageMakerHook, "get_conn")
def test_count_processing_jobs_by_name(self, mock_conn):
hook = SageMakerHook(aws_conn_id="sagemaker_test_conn_id")
existing_job_name = "existing_job"
mock_conn().list_processing_jobs.return_value = {
"ProcessingJobSummaries": [{"ProcessingJobName": existing_job_name}]
}
ret = hook.count_processing_jobs_by_name(existing_job_name)
assert ret == 1
@mock.patch.object(SageMakerHook, "get_conn")
def test_count_processing_jobs_by_name_only_counts_actual_hits(self, mock_conn):
hook = SageMakerHook(aws_conn_id="sagemaker_test_conn_id")
existing_job_name = "existing_job"
mock_conn().list_processing_jobs.return_value = {
"ProcessingJobSummaries": [
{"ProcessingJobName": existing_job_name},
{"ProcessingJobName": f"contains_but_does_not_start_with_{existing_job_name}"},
{"ProcessingJobName": f"{existing_job_name}_with_different_suffix-123"},
]
}
ret = hook.count_processing_jobs_by_name(existing_job_name)
assert ret == 1
@mock.patch.object(SageMakerHook, "get_conn")
@mock.patch("time.sleep", return_value=None)
def test_count_processing_jobs_by_name_retries_on_throttle_exception(self, _, mock_conn):
throttle_exception = ClientError(
error_response={"Error": {"Code": "ThrottlingException"}}, operation_name="empty"
)
successful_result = {"ProcessingJobSummaries": [{"ProcessingJobName": "existing_job"}]}
# Return a ThrottleException on the first call, then a mocked successful value the second.
mock_conn().list_processing_jobs.side_effect = [throttle_exception, successful_result]
hook = SageMakerHook(aws_conn_id="sagemaker_test_conn_id")
ret = hook.count_processing_jobs_by_name("existing_job")
assert mock_conn().list_processing_jobs.call_count == 2
assert ret == 1
@mock.patch.object(SageMakerHook, "get_conn")
@mock.patch("time.sleep", return_value=None)
def test_count_processing_jobs_by_name_fails_after_max_retries(self, _, mock_conn):
mock_conn().list_processing_jobs.side_effect = ClientError(
error_response={"Error": {"Code": "ThrottlingException"}}, operation_name="empty"
)
hook = SageMakerHook(aws_conn_id="sagemaker_test_conn_id")
retries = 3
with pytest.raises(ClientError) as raised_exception:
hook.count_processing_jobs_by_name("existing_job", retries=retries)
assert mock_conn().list_processing_jobs.call_count == retries + 1
assert raised_exception.value.response["Error"]["Code"] == "ThrottlingException"
@mock.patch.object(SageMakerHook, "get_conn")
def test_count_processing_jobs_by_name_job_not_exists_should_return_falsy(self, mock_conn):
error_resp = {"Error": {"Code": "ResourceNotFound"}}
mock_conn().list_processing_jobs.side_effect = ClientError(
error_response=error_resp, operation_name="empty"
)
hook = SageMakerHook(aws_conn_id="sagemaker_test_conn_id")
ret = hook.count_processing_jobs_by_name("existing_job")
assert ret == 0
@mock_sagemaker
def test_delete_model(self):
hook = SageMakerHook()
with patch.object(hook.conn, "delete_model") as mock_delete:
hook.delete_model(model_name="test")
mock_delete.assert_called_once_with(ModelName="test")
@mock_sagemaker
def test_delete_model_when_not_exist(self):
hook = SageMakerHook()
with pytest.raises(ClientError) as raised_exception:
hook.delete_model(model_name="test")
ex = raised_exception.value
assert ex.operation_name == "DeleteModel"
assert ex.response["ResponseMetadata"]["HTTPStatusCode"] == 404
@patch("airflow.providers.amazon.aws.hooks.sagemaker.SageMakerHook.conn", new_callable=mock.PropertyMock)
def test_start_pipeline_returns_arn(self, mock_conn):
mock_conn().start_pipeline_execution.return_value = {"PipelineExecutionArn": "hellotest"}
hook = SageMakerHook(aws_conn_id="aws_default")
params_dict = {"one": "1", "two": "2"}
arn = hook.start_pipeline(pipeline_name="test_name", pipeline_params=params_dict)
assert arn == "hellotest"
args_passed = mock_conn().start_pipeline_execution.call_args.kwargs
assert args_passed["PipelineName"] == "test_name"
# check conversion to the weird format for passing parameters (list of tuples)
assert len(args_passed["PipelineParameters"]) == 2
for transformed_param in args_passed["PipelineParameters"]:
assert "Name" in transformed_param.keys()
assert "Value" in transformed_param.keys()
# Name contains the key
assert transformed_param["Name"] in params_dict.keys()
# Value contains the value associated with the key in Name
assert transformed_param["Value"] == params_dict[transformed_param["Name"]]
@patch("airflow.providers.amazon.aws.hooks.sagemaker.SageMakerHook.conn", new_callable=mock.PropertyMock)
def test_start_pipeline_waits_for_completion(self, mock_conn):
mock_conn().describe_pipeline_execution.side_effect = [
{"PipelineExecutionStatus": "Executing"},
{"PipelineExecutionStatus": "Executing"},
{"PipelineExecutionStatus": "Succeeded"},
]
hook = SageMakerHook(aws_conn_id="aws_default")
hook.start_pipeline(pipeline_name="test_name", wait_for_completion=True, check_interval=0)
assert mock_conn().describe_pipeline_execution.call_count == 3
@patch("airflow.providers.amazon.aws.hooks.sagemaker.SageMakerHook.conn", new_callable=mock.PropertyMock)
def test_stop_pipeline_returns_status(self, mock_conn):
mock_conn().describe_pipeline_execution.return_value = {"PipelineExecutionStatus": "Stopping"}
hook = SageMakerHook(aws_conn_id="aws_default")
pipeline_status = hook.stop_pipeline(pipeline_exec_arn="test")
assert pipeline_status == "Stopping"
mock_conn().stop_pipeline_execution.assert_called_once_with(PipelineExecutionArn="test")
@patch("airflow.providers.amazon.aws.hooks.sagemaker.SageMakerHook.conn", new_callable=mock.PropertyMock)
def test_stop_pipeline_waits_for_completion(self, mock_conn):
mock_conn().describe_pipeline_execution.side_effect = [
{"PipelineExecutionStatus": "Stopping"},
{"PipelineExecutionStatus": "Stopping"},
{"PipelineExecutionStatus": "Stopped"},
]
hook = SageMakerHook(aws_conn_id="aws_default")
pipeline_status = hook.stop_pipeline(
pipeline_exec_arn="test", wait_for_completion=True, check_interval=0
)
assert pipeline_status == "Stopped"
assert mock_conn().describe_pipeline_execution.call_count == 3
@patch("airflow.providers.amazon.aws.hooks.sagemaker.SageMakerHook.conn", new_callable=mock.PropertyMock)
def test_stop_pipeline_waits_for_completion_even_when_already_stopped(self, mock_conn):
mock_conn().stop_pipeline_execution.side_effect = ClientError(
error_response={
"Error": {"Message": "Only pipelines with 'Executing' status can be stopped", "Code": "0"}
},
operation_name="empty",
)
mock_conn().describe_pipeline_execution.side_effect = [
{"PipelineExecutionStatus": "Stopping"},
{"PipelineExecutionStatus": "Stopped"},
]
hook = SageMakerHook(aws_conn_id="aws_default")
pipeline_status = hook.stop_pipeline(
pipeline_exec_arn="test", wait_for_completion=True, check_interval=0
)
assert pipeline_status == "Stopped"
@patch("airflow.providers.amazon.aws.hooks.sagemaker.SageMakerHook.conn", new_callable=mock.PropertyMock)
def test_stop_pipeline_raises_when_already_stopped_if_specified(self, mock_conn):
error = ClientError(
error_response={
"Error": {"Message": "Only pipelines with 'Executing' status can be stopped", "Code": "0"}
},
operation_name="empty",
)
mock_conn().stop_pipeline_execution.side_effect = error
mock_conn().describe_pipeline_execution.return_value = {"PipelineExecutionStatus": "Stopping"}
hook = SageMakerHook(aws_conn_id="aws_default")
with pytest.raises(ClientError) as raised_exception:
hook.stop_pipeline(pipeline_exec_arn="test", fail_if_not_running=True)
assert raised_exception.value == error
@patch("airflow.providers.amazon.aws.hooks.sagemaker.SageMakerHook.conn", new_callable=mock.PropertyMock)
def test_stop_pipeline_retries_on_conflict(self, mock_conn):
conflict_error = ClientError(
error_response={"Error": {"Code": "ConflictException"}},
operation_name="empty",
)
mock_conn().stop_pipeline_execution.side_effect = [
conflict_error,
conflict_error,
None,
]
hook = SageMakerHook(aws_conn_id="aws_default")
hook.stop_pipeline(pipeline_exec_arn="test")
assert mock_conn().stop_pipeline_execution.call_count == 3
@patch("airflow.providers.amazon.aws.hooks.sagemaker.SageMakerHook.conn", new_callable=mock.PropertyMock)
def test_stop_pipeline_fails_if_all_retries_error(self, mock_conn):
conflict_error = ClientError(
error_response={"Error": {"Message": "blah", "Code": "ConflictException"}},
operation_name="empty",
)
mock_conn().stop_pipeline_execution.side_effect = conflict_error
hook = SageMakerHook(aws_conn_id="aws_default")
with pytest.raises(ClientError) as raised_exception:
hook.stop_pipeline(pipeline_exec_arn="test")
assert mock_conn().stop_pipeline_execution.call_count == 3
assert raised_exception.value == conflict_error
@patch("airflow.providers.amazon.aws.hooks.sagemaker.SageMakerHook.conn", new_callable=mock.PropertyMock)
def test_create_model_package_group(self, mock_conn):
created = SageMakerHook().create_model_package_group("group-name")
mock_conn().create_model_package_group.assert_called_once_with(
ModelPackageGroupName="group-name",
ModelPackageGroupDescription="",
)
assert created
@patch("airflow.providers.amazon.aws.hooks.sagemaker.SageMakerHook.conn", new_callable=mock.PropertyMock)
def test_create_model_package_group_returns_false_if_exists(self, mock_conn):
mock_conn().create_model_package_group.side_effect = ClientError(
error_response={
"Error": {
"Code": "ValidationException",
"Message": "Model Package Group already exists: arn:aws:sagemaker:foo:bar",
}
},
operation_name="empty",
)
hook = SageMakerHook()
created = hook.create_model_package_group("group-name")
assert created is False
@patch("airflow.providers.amazon.aws.hooks.sagemaker.SageMakerHook.conn", new_callable=mock.PropertyMock)
def test_create_auto_ml_parameter_structure(self, conn_mock):
hook = SageMakerHook()
hook.create_auto_ml_job(
job_name="a",
s3_input="b",
target_attribute="c",
s3_output="d",
role_arn="e",
compressed_input=True,
time_limit=30,
wait_for_completion=False,
)
assert conn_mock().create_auto_ml_job.call_args.kwargs == {
"AutoMLJobConfig": {"CompletionCriteria": {"MaxAutoMLJobRuntimeInSeconds": 30}},
"AutoMLJobName": "a",
"InputDataConfig": [
{
"CompressionType": "Gzip",
"DataSource": {"S3DataSource": {"S3DataType": "S3Prefix", "S3Uri": "b"}},
"TargetAttributeName": "c",
}
],
"OutputDataConfig": {"S3OutputPath": "d"},
"RoleArn": "e",
}
@patch("airflow.providers.amazon.aws.hooks.sagemaker.SageMakerHook.conn", new_callable=mock.PropertyMock)
def test_create_auto_ml_waits_for_completion(self, conn_mock):
hook = SageMakerHook()
conn_mock().describe_auto_ml_job.side_effect = [
{"AutoMLJobStatus": "InProgress", "AutoMLJobSecondaryStatus": "a"},
{"AutoMLJobStatus": "InProgress", "AutoMLJobSecondaryStatus": "b"},
{
"AutoMLJobStatus": "Completed",
"AutoMLJobSecondaryStatus": "c",
"BestCandidate": {"name": "me"},
},
]
ret = hook.create_auto_ml_job("a", "b", "c", "d", "e", check_interval=0)
assert conn_mock().describe_auto_ml_job.call_count == 3
assert ret == {"name": "me"}