-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathtest_deploy.py
More file actions
1509 lines (1279 loc) · 56.6 KB
/
test_deploy.py
File metadata and controls
1509 lines (1279 loc) · 56.6 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
"""Tests for the deploy module."""
import json
from unittest.mock import (
ANY,
MagicMock,
mock_open,
patch,
)
import zipfile
import pytest
import requests
from datacustomcode.credentials import AuthType, Credentials
from datacustomcode.deploy import (
DloPermission,
Permissions,
get_config,
)
# Patch get_version before importing deploy module
with patch("datacustomcode.version.get_version", return_value="1.2.3"):
from datacustomcode.deploy import (
AccessTokenResponse,
CodeExtensionMetadata,
CreateDeploymentResponse,
DataTransformConfig,
DeploymentsResponse,
_make_api_call,
_retrieve_access_token,
_retrieve_access_token_from_sf_cli,
_sanitize_api_name,
create_data_transform,
create_deployment,
deploy_full,
get_deployments,
has_nonempty_requirements_file,
prepare_dependency_archive,
run_data_transform,
upload_zip,
wait_for_deployment,
zip,
)
class TestPrepareDependencyArchive:
# Shared expected commands
EXPECTED_DOCKER_IMAGES_CMD = (
"docker images -q datacloud-custom-code-dependency-builder"
)
EXPECTED_BUILD_CMD = (
"docker build "
"-t datacloud-custom-code-dependency-builder --file Dockerfile.dependencies . "
)
EXPECTED_DOCKER_RUN_CMD = (
"docker run --rm "
'-v "/tmp/test_dir:/workspace" '
"datacloud-custom-code-dependency-builder "
)
@patch("datacustomcode.deploy.cmd_output")
@patch("datacustomcode.deploy.shutil.copy")
@patch("datacustomcode.deploy.tempfile.TemporaryDirectory")
@patch("datacustomcode.deploy.os.path.join")
@patch("datacustomcode.deploy.os.makedirs")
@patch("datacustomcode.deploy.docker_build_cmd")
@patch("datacustomcode.deploy.docker_run_cmd")
def test_prepare_dependency_archive_image_exists(
self,
mock_docker_run_cmd,
mock_docker_build_cmd,
mock_makedirs,
mock_join,
mock_temp_dir,
mock_copy,
mock_cmd_output,
):
"""Test prepare_dependency_archive when Docker image already exists."""
# Mock the temporary directory context manager
mock_temp_dir_instance = MagicMock()
mock_temp_dir_instance.__enter__.return_value = "/tmp/test_dir"
mock_temp_dir_instance.__exit__.return_value = None
mock_temp_dir.return_value = mock_temp_dir_instance
# Mock cmd_output to return image ID (indicating image exists)
mock_cmd_output.return_value = "abc123"
# Mock os.path.join for archive path
mock_join.return_value = "/tmp/test_dir/native_dependencies.tar.gz"
# Mock the docker command functions
mock_docker_build_cmd.return_value = "mock build command"
mock_docker_run_cmd.return_value = "mock run command"
prepare_dependency_archive("/test/dir", "default", "script")
# Verify docker images command was called
mock_cmd_output.assert_any_call(self.EXPECTED_DOCKER_IMAGES_CMD)
# Verify docker build command was not called (since image already exists)
mock_docker_build_cmd.assert_not_called()
# Verify files were copied to temp directory
mock_copy.assert_any_call("requirements.txt", "/tmp/test_dir")
mock_copy.assert_any_call("build_native_dependencies.sh", "/tmp/test_dir")
# Verify docker run command was called
mock_docker_run_cmd.assert_called_once_with("default", "/tmp/test_dir")
mock_cmd_output.assert_any_call("mock run command", env=ANY)
# Verify archives directory was created
mock_makedirs.assert_called_once_with("payload/archives", exist_ok=True)
# Verify archive was copied back
mock_copy.assert_any_call(
"/tmp/test_dir/native_dependencies.tar.gz",
"payload/archives/native_dependencies.tar.gz",
)
@patch("datacustomcode.deploy.cmd_output")
@patch("datacustomcode.deploy.shutil.copy")
@patch("datacustomcode.deploy.tempfile.TemporaryDirectory")
@patch("datacustomcode.deploy.os.path.join")
@patch("datacustomcode.deploy.os.makedirs")
@patch("datacustomcode.deploy.docker_build_cmd")
@patch("datacustomcode.deploy.docker_run_cmd")
def test_prepare_dependency_archive_build_image(
self,
mock_docker_run_cmd,
mock_docker_build_cmd,
mock_makedirs,
mock_join,
mock_temp_dir,
mock_copy,
mock_cmd_output,
):
"""Test prepare_dependency_archive when Docker image needs to be built."""
# Mock the temporary directory context manager
mock_temp_dir_instance = MagicMock()
mock_temp_dir_instance.__enter__.return_value = "/tmp/test_dir"
mock_temp_dir_instance.__exit__.return_value = None
mock_temp_dir.return_value = mock_temp_dir_instance
# Mock cmd_output to return None for image check (image doesn't exist)
# and then return some value for subsequent calls
mock_cmd_output.side_effect = [None, None, None, None]
# Mock os.path.join for archive path
mock_join.return_value = "/tmp/test_dir/native_dependencies.tar.gz"
# Mock the docker command functions
mock_docker_build_cmd.return_value = "mock build command"
mock_docker_run_cmd.return_value = "mock run command"
prepare_dependency_archive("/test/dir", "default", "script")
# Verify docker images command was called
mock_cmd_output.assert_any_call(self.EXPECTED_DOCKER_IMAGES_CMD)
# Verify docker build command was called
mock_docker_build_cmd.assert_called_once_with("default")
mock_cmd_output.assert_any_call("mock build command", env=ANY)
# Verify files were copied to temp directory
mock_copy.assert_any_call("requirements.txt", "/tmp/test_dir")
mock_copy.assert_any_call("build_native_dependencies.sh", "/tmp/test_dir")
# Verify docker run command was called
mock_docker_run_cmd.assert_called_once_with("default", "/tmp/test_dir")
mock_cmd_output.assert_any_call("mock run command", env=ANY)
# Verify archives directory was created
mock_makedirs.assert_called_once_with("payload/archives", exist_ok=True)
# Verify archive was copied back
mock_copy.assert_any_call(
"/tmp/test_dir/native_dependencies.tar.gz",
"payload/archives/native_dependencies.tar.gz",
)
@patch("datacustomcode.deploy.cmd_output")
@patch("datacustomcode.deploy.shutil.copy")
@patch("datacustomcode.deploy.tempfile.TemporaryDirectory")
@patch("datacustomcode.deploy.os.path.join")
@patch("datacustomcode.deploy.os.makedirs")
@patch("datacustomcode.deploy.docker_build_cmd")
@patch("datacustomcode.deploy.docker_run_cmd")
def test_prepare_dependency_archive_docker_build_failure(
self,
mock_docker_run_cmd,
mock_docker_build_cmd,
mock_makedirs,
mock_join,
mock_temp_dir,
mock_copy,
mock_cmd_output,
):
"""Test prepare_dependency_archive when Docker build fails."""
# Mock the temporary directory context manager
mock_temp_dir_instance = MagicMock()
mock_temp_dir_instance.__enter__.return_value = "/tmp/test_dir"
mock_temp_dir_instance.__exit__.return_value = None
mock_temp_dir.return_value = mock_temp_dir_instance
# Mock cmd_output to return None for image check, then raise exception for build
from datacustomcode.cmd import CalledProcessError
mock_cmd_output.side_effect = [
None, # Image doesn't exist
CalledProcessError(
1, ("docker", "build"), b"Build failed", b"Error"
), # Build fails
]
with pytest.raises(CalledProcessError, match="Build failed"):
prepare_dependency_archive("/test/dir", "default", "script")
# Verify docker images command was called
mock_cmd_output.assert_any_call(self.EXPECTED_DOCKER_IMAGES_CMD)
# Verify docker build command was called
mock_docker_build_cmd.assert_called_once_with("default")
@patch("datacustomcode.deploy.cmd_output")
@patch("datacustomcode.deploy.shutil.copy")
@patch("datacustomcode.deploy.tempfile.TemporaryDirectory")
@patch("datacustomcode.deploy.os.path.join")
@patch("datacustomcode.deploy.os.makedirs")
@patch("datacustomcode.deploy.docker_build_cmd")
@patch("datacustomcode.deploy.docker_run_cmd")
def test_prepare_dependency_archive_docker_run_failure(
self,
mock_docker_run_cmd,
mock_docker_build_cmd,
mock_makedirs,
mock_join,
mock_temp_dir,
mock_copy,
mock_cmd_output,
):
"""Test prepare_dependency_archive when Docker run fails."""
# Mock the temporary directory context manager
mock_temp_dir_instance = MagicMock()
mock_temp_dir_instance.__enter__.return_value = "/tmp/test_dir"
mock_temp_dir_instance.__exit__.return_value = None
mock_temp_dir.return_value = mock_temp_dir_instance
# Mock cmd_output to return image ID, then raise exception for run
from datacustomcode.cmd import CalledProcessError
mock_cmd_output.side_effect = [
"abc123", # Image exists
CalledProcessError(
1, ("docker", "run"), b"Run failed", b"Error"
), # Run fails
]
with pytest.raises(CalledProcessError, match="Run failed"):
prepare_dependency_archive("/test/dir", "default", "script")
# Verify docker images command was called
mock_cmd_output.assert_any_call(self.EXPECTED_DOCKER_IMAGES_CMD)
# Verify files were copied to temp directory
mock_copy.assert_any_call("requirements.txt", "/tmp/test_dir")
mock_copy.assert_any_call("build_native_dependencies.sh", "/tmp/test_dir")
# Verify docker run command was called
mock_docker_run_cmd.assert_called_once_with("default", "/tmp/test_dir")
@patch("datacustomcode.deploy.cmd_output")
@patch("datacustomcode.deploy.shutil.copy")
@patch("datacustomcode.deploy.tempfile.TemporaryDirectory")
@patch("datacustomcode.deploy.os.path.join")
@patch("datacustomcode.deploy.os.makedirs")
@patch("datacustomcode.deploy.docker_build_cmd")
@patch("datacustomcode.deploy.docker_run_cmd")
def test_prepare_dependency_archive_file_copy_failure(
self,
mock_docker_run_cmd,
mock_docker_build_cmd,
mock_makedirs,
mock_join,
mock_temp_dir,
mock_copy,
mock_cmd_output,
):
"""Test prepare_dependency_archive when file copy fails."""
# Mock the temporary directory context manager
mock_temp_dir_instance = MagicMock()
mock_temp_dir_instance.__enter__.return_value = "/tmp/test_dir"
mock_temp_dir_instance.__exit__.return_value = None
mock_temp_dir.return_value = mock_temp_dir_instance
# Mock cmd_output to return image ID
mock_cmd_output.return_value = "abc123"
# Mock shutil.copy to raise exception
mock_copy.side_effect = FileNotFoundError("File not found")
with pytest.raises(FileNotFoundError, match="File not found"):
prepare_dependency_archive("/test/dir", "default", "script")
# Verify docker images command was called
mock_cmd_output.assert_any_call(self.EXPECTED_DOCKER_IMAGES_CMD)
# Verify files were attempted to be copied
mock_copy.assert_any_call("requirements.txt", "/tmp/test_dir")
@patch("datacustomcode.deploy.cmd_output")
@patch("datacustomcode.deploy.shutil.copytree")
@patch("datacustomcode.deploy.shutil.rmtree")
@patch("datacustomcode.deploy.shutil.copy")
@patch("datacustomcode.deploy.tempfile.TemporaryDirectory")
@patch("datacustomcode.deploy.os.path.exists")
@patch("datacustomcode.deploy.os.path.join")
@patch("datacustomcode.deploy.os.makedirs")
@patch("datacustomcode.deploy.docker_build_cmd")
@patch("datacustomcode.deploy.docker_run_cmd")
def test_prepare_dependency_archive_function_type(
self,
mock_docker_run_cmd,
mock_docker_build_cmd,
mock_makedirs,
mock_join,
mock_exists,
mock_temp_dir,
mock_copy,
mock_rmtree,
mock_copytree,
mock_cmd_output,
):
"""Test prepare_dependency_archive with function package type."""
# Mock the temporary directory context manager
mock_temp_dir_instance = MagicMock()
mock_temp_dir_instance.__enter__.return_value = "/tmp/test_dir"
mock_temp_dir_instance.__exit__.return_value = None
mock_temp_dir.return_value = mock_temp_dir_instance
# Mock cmd_output to return image ID (indicating image exists)
mock_cmd_output.return_value = "abc123"
# Mock os.path.join for py-files paths
def join_side_effect(*args):
if args == ("/tmp/test_dir", "py-files"):
return "/tmp/test_dir/py-files"
return "/".join(args)
mock_join.side_effect = join_side_effect
# Mock os.path.exists
def exists_side_effect(path):
if path == "/tmp/test_dir/py-files":
return True
if path == "payload/py-files":
return False
return False
mock_exists.side_effect = exists_side_effect
# Mock the docker command functions
mock_docker_build_cmd.return_value = "mock build command"
mock_docker_run_cmd.return_value = "mock run command"
prepare_dependency_archive("/test/dir", "default", "function")
# Verify docker images command was called
mock_cmd_output.assert_any_call(self.EXPECTED_DOCKER_IMAGES_CMD)
# Verify docker build command was not called (since image already exists)
mock_docker_build_cmd.assert_not_called()
# Verify files were copied to temp directory
mock_copy.assert_any_call("requirements.txt", "/tmp/test_dir")
mock_copy.assert_any_call("build_native_dependencies.sh", "/tmp/test_dir")
# Verify docker run command was called
mock_docker_run_cmd.assert_called_once_with("default", "/tmp/test_dir")
mock_cmd_output.assert_any_call("mock run command", env=ANY)
# Verify payload directory was created
mock_makedirs.assert_called_once_with("payload", exist_ok=True)
# Verify py-files was NOT removed (doesn't exist yet)
mock_rmtree.assert_not_called()
# Verify py-files directory was copied
mock_copytree.assert_called_once_with(
"/tmp/test_dir/py-files", "payload/py-files"
)
@patch("datacustomcode.deploy.cmd_output")
@patch("datacustomcode.deploy.shutil.copy")
@patch("datacustomcode.deploy.tempfile.TemporaryDirectory")
@patch("datacustomcode.deploy.os.path.exists")
@patch("datacustomcode.deploy.os.path.join")
@patch("datacustomcode.deploy.os.makedirs")
@patch("datacustomcode.deploy.docker_build_cmd")
@patch("datacustomcode.deploy.docker_run_cmd")
def test_prepare_dependency_archive_function_type_missing_pyfiles(
self,
mock_docker_run_cmd,
mock_docker_build_cmd,
mock_makedirs,
mock_join,
mock_exists,
mock_temp_dir,
mock_copy,
mock_cmd_output,
):
"""
Test prepare_dependency_archive with function type when py-files is missing.
Should log and continue without error.
"""
# Mock the temporary directory context manager
mock_temp_dir_instance = MagicMock()
mock_temp_dir_instance.__enter__.return_value = "/tmp/test_dir"
mock_temp_dir_instance.__exit__.return_value = None
mock_temp_dir.return_value = mock_temp_dir_instance
# Mock cmd_output to return image ID (indicating image exists)
mock_cmd_output.return_value = "abc123"
# Mock os.path.join for py-files path
def join_side_effect(*args):
if args == ("/tmp/test_dir", "py-files"):
return "/tmp/test_dir/py-files"
return "/".join(args)
mock_join.side_effect = join_side_effect
# Mock os.path.exists to return False for py-files (doesn't exist)
mock_exists.return_value = False
# Mock the docker command functions
mock_docker_build_cmd.return_value = "mock build command"
mock_docker_run_cmd.return_value = "mock run command"
# Should complete successfully without raising an error
prepare_dependency_archive("/test/dir", "default", "function")
# Verify docker commands were called
mock_cmd_output.assert_any_call(self.EXPECTED_DOCKER_IMAGES_CMD)
mock_docker_run_cmd.assert_called_once_with("default", "/tmp/test_dir")
class TestHasNonemptyRequirementsFile:
@patch("datacustomcode.deploy.os.path.dirname")
@patch("datacustomcode.deploy.os.path.isfile")
@patch(
"builtins.open",
new_callable=mock_open,
read_data="numpy==1.21.0\npandas==1.3.0",
)
def test_has_nonempty_requirements_file_with_dependencies(
self, mock_file, mock_isfile, mock_dirname
):
"""
Test has_nonempty_requirements_file when requirements.txt has dependencies.
"""
mock_dirname.return_value = "/parent/dir"
mock_isfile.return_value = True
result = has_nonempty_requirements_file("/test/dir")
assert result is True
mock_isfile.assert_called_once_with("/parent/dir/requirements.txt")
mock_file.assert_called_once_with(
"/parent/dir/requirements.txt", "r", encoding="utf-8"
)
@patch("datacustomcode.deploy.os.path.dirname")
@patch("datacustomcode.deploy.os.path.isfile")
@patch(
"builtins.open",
new_callable=mock_open,
read_data="# This is a comment\n\n # Another comment",
)
def test_has_nonempty_requirements_file_only_comments(
self, mock_file, mock_isfile, mock_dirname
):
"""
Test has_nonempty_requirements_file when requirements.txt has only comments.
"""
mock_dirname.return_value = "/parent/dir"
mock_isfile.return_value = True
result = has_nonempty_requirements_file("/test/dir")
assert result is False
mock_isfile.assert_called_once_with("/parent/dir/requirements.txt")
mock_file.assert_called_once_with(
"/parent/dir/requirements.txt", "r", encoding="utf-8"
)
@patch("datacustomcode.deploy.os.path.dirname")
@patch("datacustomcode.deploy.os.path.isfile")
@patch("builtins.open", new_callable=mock_open, read_data="")
def test_has_nonempty_requirements_file_empty_file(
self, mock_file, mock_isfile, mock_dirname
):
"""Test has_nonempty_requirements_file when requirements.txt is empty."""
mock_dirname.return_value = "/parent/dir"
mock_isfile.return_value = True
result = has_nonempty_requirements_file("/test/dir")
assert result is False
mock_isfile.assert_called_once_with("/parent/dir/requirements.txt")
mock_file.assert_called_once_with(
"/parent/dir/requirements.txt", "r", encoding="utf-8"
)
@patch("datacustomcode.deploy.os.path.dirname")
@patch("datacustomcode.deploy.os.path.isfile")
def test_has_nonempty_requirements_file_not_exists(self, mock_isfile, mock_dirname):
"""Test has_nonempty_requirements_file when requirements.txt doesn't exist."""
mock_dirname.return_value = "/parent/dir"
mock_isfile.return_value = False
result = has_nonempty_requirements_file("/test/dir")
assert result is False
mock_isfile.assert_called_once_with("/parent/dir/requirements.txt")
@patch("datacustomcode.deploy.os.path.dirname")
@patch("datacustomcode.deploy.os.path.isfile")
@patch("builtins.open", side_effect=PermissionError("Permission denied"))
def test_has_nonempty_requirements_file_permission_error(
self, mock_file, mock_isfile, mock_dirname
):
"""Test has_nonempty_requirements_file when file access fails."""
mock_dirname.return_value = "/parent/dir"
mock_isfile.return_value = True
result = has_nonempty_requirements_file("/test/dir")
assert result is False
mock_isfile.assert_called_once_with("/parent/dir/requirements.txt")
mock_file.assert_called_once_with(
"/parent/dir/requirements.txt", "r", encoding="utf-8"
)
@patch("datacustomcode.deploy.os.path.dirname")
@patch("datacustomcode.deploy.os.path.isfile")
@patch(
"builtins.open",
new_callable=mock_open,
read_data="numpy==1.21.0\n# Comment\npandas==1.3.0",
)
def test_has_nonempty_requirements_file_mixed_content(
self, mock_file, mock_isfile, mock_dirname
):
"""Test has_nonempty_requirements_file with mixed dependencies and comments."""
mock_dirname.return_value = "/parent/dir"
mock_isfile.return_value = True
result = has_nonempty_requirements_file("/test/dir")
assert result is True
mock_isfile.assert_called_once_with("/parent/dir/requirements.txt")
mock_file.assert_called_once_with(
"/parent/dir/requirements.txt", "r", encoding="utf-8"
)
class TestMakeApiCall:
@patch("datacustomcode.deploy.requests.request")
def test_make_api_call_with_token(self, mock_request):
"""Test API call with authentication token."""
mock_response = MagicMock()
mock_response.status_code = 200
mock_response.json.return_value = {"key": "value"}
mock_request.return_value = mock_response
result = _make_api_call(
"https://example.com", "POST", token="test_token", json={"data": "value"}
)
mock_request.assert_called_once_with(
method="POST",
url="https://example.com",
headers={"Authorization": "Bearer test_token"},
json={"data": "value"},
)
assert result == {"key": "value"}
@patch("datacustomcode.deploy.requests.request")
def test_make_api_call_invalid_response(self, mock_request):
"""Test API call with non-dict response."""
mock_response = MagicMock()
mock_response.status_code = 200
mock_response.json.return_value = ["list", "response"] # Non-dict response
mock_request.return_value = mock_response
with pytest.raises(AssertionError, match="Unexpected response type"):
_make_api_call("https://example.com", "GET")
class TestRetrieveAccessToken:
@patch("datacustomcode.deploy._make_api_call")
def test_retrieve_access_token(self, mock_make_api_call):
"""Test retrieving access token."""
credentials = Credentials(
login_url="https://example.com",
client_id="id",
auth_type=AuthType.OAUTH_TOKENS,
refresh_token="refresh",
client_secret="secret",
)
mock_make_api_call.return_value = {
"access_token": "test_token",
"instance_url": "https://instance.example.com",
}
result = _retrieve_access_token(credentials)
mock_make_api_call.assert_called_once()
call_args = mock_make_api_call.call_args
assert call_args.kwargs["data"]["grant_type"] == "refresh_token"
assert call_args.kwargs["data"]["refresh_token"] == "refresh"
assert isinstance(result, AccessTokenResponse)
assert result.access_token == "test_token"
assert result.instance_url == "https://instance.example.com"
@patch("datacustomcode.deploy._make_api_call")
def test_retrieve_access_token_client_credentials(self, mock_make_api_call):
"""Test retrieving access token with client credentials flow."""
credentials = Credentials(
login_url="https://example.com",
client_id="id",
auth_type=AuthType.CLIENT_CREDENTIALS,
client_secret="secret",
)
mock_make_api_call.return_value = {
"access_token": "test_token",
"instance_url": "https://instance.example.com",
}
result = _retrieve_access_token(credentials)
mock_make_api_call.assert_called_once()
call_args = mock_make_api_call.call_args
assert call_args.kwargs["data"]["grant_type"] == "client_credentials"
assert isinstance(result, AccessTokenResponse)
assert result.access_token == "test_token"
assert result.instance_url == "https://instance.example.com"
class TestCreateDeployment:
@patch("datacustomcode.deploy._make_api_call")
def test_create_deployment_success(self, mock_make_api_call):
"""Test successful deployment creation."""
access_token = AccessTokenResponse(
access_token="test_token", instance_url="https://instance.example.com"
)
metadata = CodeExtensionMetadata(
name="test_job",
version="1.0.0",
description="Test job",
computeType="CPU_M",
codeType="script",
)
mock_make_api_call.return_value = {
"fileUploadUrl": "https://upload.example.com"
}
result = create_deployment(access_token, metadata)
mock_make_api_call.assert_called_once()
assert isinstance(result, CreateDeploymentResponse)
assert result.fileUploadUrl == "https://upload.example.com"
@patch("datacustomcode.deploy._make_api_call")
def test_create_deployment_conflict(self, mock_make_api_call):
"""Test deployment creation with conflict response."""
access_token = AccessTokenResponse(
access_token="test_token", instance_url="https://instance.example.com"
)
metadata = CodeExtensionMetadata(
name="test_job",
version="1.0.0",
description="Test job",
computeType="CPU_M",
codeType="script",
)
# Mock HTTP error with 409 Conflict
mock_response = MagicMock()
mock_response.status_code = 409
http_error = requests.HTTPError("Deployment exists")
http_error.response = mock_response
mock_make_api_call.side_effect = http_error
with pytest.raises(ValueError, match="Deployment test_job exists"):
create_deployment(access_token, metadata)
@patch("datacustomcode.deploy._make_api_call")
def test_create_deployment_function_invoke_options(self, mock_make_api_call):
"""Test deployment creation with function invoke options."""
access_token = AccessTokenResponse(
access_token="test_token", instance_url="https://instance.example.com"
)
metadata = CodeExtensionMetadata(
name="test_job",
version="1.0.0",
description="Test job",
computeType="CPU_M",
functionInvokeOptions=["option1", "option2"],
codeType="function",
)
mock_make_api_call.return_value = {
"fileUploadUrl": "https://upload.example.com"
}
result = create_deployment(access_token, metadata)
mock_make_api_call.assert_called_once()
assert isinstance(result, CreateDeploymentResponse)
assert result.fileUploadUrl == "https://upload.example.com"
class TestZip:
@patch("datacustomcode.deploy.has_nonempty_requirements_file")
@patch("datacustomcode.deploy.prepare_dependency_archive")
@patch("zipfile.ZipFile")
@patch("os.walk")
def test_zip_with_requirements(
self, mock_walk, mock_zipfile, mock_prepare, mock_has_requirements
):
"""Test zipping a directory with requirements.txt."""
mock_has_requirements.return_value = True
mock_zipfile_instance = MagicMock()
mock_zipfile.return_value.__enter__.return_value = mock_zipfile_instance
mock_zipfile_instance.write = MagicMock()
# Mock os.walk to return some test files
mock_walk.return_value = [
("/test/dir", ["subdir"], ["file1.py", "file2.py"]),
("/test/dir/subdir", [], ["file3.py"]),
]
zip("/test/dir", "default", "script")
mock_has_requirements.assert_called_once_with("/test/dir")
mock_prepare.assert_called_once_with("/test/dir", "default", "script")
mock_zipfile.assert_called_once_with(
"deployment.zip", "w", zipfile.ZIP_DEFLATED
)
assert mock_zipfile_instance.write.call_count == 3 # One call per file
@patch("datacustomcode.deploy.has_nonempty_requirements_file")
@patch("datacustomcode.deploy.prepare_dependency_archive")
@patch("zipfile.ZipFile")
@patch("os.walk")
def test_zip_without_requirements(
self, mock_walk, mock_zipfile, mock_prepare, mock_has_requirements
):
"""Test zipping a directory without requirements.txt."""
mock_has_requirements.return_value = False
mock_zipfile_instance = MagicMock()
mock_zipfile.return_value.__enter__.return_value = mock_zipfile_instance
mock_zipfile_instance.write = MagicMock()
# Mock os.walk to return some test files
mock_walk.return_value = [
("/test/dir", ["subdir"], ["file1.py", "file2.py"]),
("/test/dir/subdir", [], ["file3.py"]),
]
zip("/test/dir", "default", "script")
mock_has_requirements.assert_called_once_with("/test/dir")
mock_prepare.assert_not_called()
mock_zipfile.assert_called_once_with(
"deployment.zip", "w", zipfile.ZIP_DEFLATED
)
assert mock_zipfile_instance.write.call_count == 3 # One call per file
@patch("datacustomcode.deploy.has_nonempty_requirements_file")
@patch("datacustomcode.deploy.prepare_dependency_archive")
@patch("zipfile.ZipFile")
@patch("os.walk")
def test_zip_with_function_package_type(
self,
mock_walk,
mock_zipfile,
mock_prepare,
mock_has_requirements,
):
"""Test zipping a directory with function package type."""
mock_has_requirements.return_value = True
mock_zipfile_instance = MagicMock()
mock_zipfile.return_value.__enter__.return_value = mock_zipfile_instance
mock_zipfile_instance.write = MagicMock()
# Mock os.walk to return some test files
mock_walk.return_value = [
("/test/dir", ["subdir"], ["file1.py", "file2.py"]),
("/test/dir/subdir", [], ["file3.py"]),
]
zip("/test/dir", "default", "function")
mock_has_requirements.assert_called_once_with("/test/dir")
mock_prepare.assert_called_once_with("/test/dir", "default", "function")
mock_zipfile.assert_called_once_with(
"deployment.zip", "w", zipfile.ZIP_DEFLATED
)
assert mock_zipfile_instance.write.call_count == 3 # One call per file
class TestUploadZip:
@patch("datacustomcode.deploy.requests.put")
@patch("builtins.open", new_callable=mock_open, read_data=b"test data")
def test_upload_zip_success(self, mock_file, mock_put):
"""Test successful zip upload."""
mock_response = MagicMock()
mock_put.return_value = mock_response
upload_zip("https://upload.example.com")
mock_file.assert_called_once_with("deployment.zip", "rb")
mock_put.assert_called_once_with(
"https://upload.example.com",
data=mock_file.return_value,
headers={"Content-Type": "application/zip"},
)
mock_response.raise_for_status.assert_called_once()
@patch("datacustomcode.deploy.requests.put")
@patch("builtins.open", new_callable=mock_open, read_data=b"test data")
def test_upload_zip_http_error(self, mock_file, mock_put):
"""Test zip upload with HTTP error."""
mock_response = MagicMock()
mock_response.raise_for_status.side_effect = requests.HTTPError("Upload failed")
mock_put.return_value = mock_response
with pytest.raises(requests.HTTPError, match="Upload failed"):
upload_zip("https://upload.example.com")
mock_file.assert_called_once_with("deployment.zip", "rb")
mock_put.assert_called_once_with(
"https://upload.example.com",
data=mock_file.return_value,
headers={"Content-Type": "application/zip"},
)
class TestGetDeployments:
@patch("datacustomcode.deploy._make_api_call")
def test_get_deployments(self, mock_make_api_call):
"""Test getting deployment status."""
access_token = AccessTokenResponse(
access_token="test_token", instance_url="https://instance.example.com"
)
metadata = CodeExtensionMetadata(
name="test_job",
version="1.0.0",
description="Test job",
computeType="CPU_M",
codeType="script",
)
mock_make_api_call.return_value = {"deploymentStatus": "Deployed"}
result = get_deployments(access_token, metadata)
mock_make_api_call.assert_called_once()
assert isinstance(result, DeploymentsResponse)
assert result.deploymentStatus == "Deployed"
class TestWaitForDeployment:
@patch("datacustomcode.deploy.time.sleep")
@patch("datacustomcode.deploy.time.time")
@patch("datacustomcode.deploy.get_deployments")
def test_wait_for_deployment_success(
self, mock_get_deployments, mock_time, mock_sleep
):
"""Test waiting for deployment to complete successfully."""
access_token = AccessTokenResponse(
access_token="test_token", instance_url="https://instance.example.com"
)
metadata = CodeExtensionMetadata(
name="test_job",
version="1.0.0",
description="Test job",
computeType="CPU_M",
codeType="script",
)
callback = MagicMock()
# Mock deployment statuses
mock_time.side_effect = [100, 101, 102] # Start time, check time, final time
mock_get_deployments.return_value = DeploymentsResponse(
deploymentStatus="Deployed"
)
wait_for_deployment(access_token, metadata, callback)
# Verify the callback was called with the correct status
callback.assert_called_once_with("Deployed")
mock_sleep.assert_not_called()
@patch("datacustomcode.deploy.time.sleep")
@patch("datacustomcode.deploy.time.time")
@patch("datacustomcode.deploy.get_deployments")
def test_wait_for_deployment_timeout(
self, mock_get_deployments, mock_time, mock_sleep
):
"""Test wait for deployment timing out."""
access_token = AccessTokenResponse(
access_token="test_token", instance_url="https://instance.example.com"
)
metadata = CodeExtensionMetadata(
name="test_job",
version="1.0.0",
description="Test job",
computeType="CPU_M",
codeType="script",
)
# Mock time to simulate timeout
mock_time.side_effect = [100, 100 + 3001] # Start time, check time (> timeout)
mock_get_deployments.return_value = DeploymentsResponse(
deploymentStatus="InProgress"
)
with pytest.raises(TimeoutError, match="Deployment timed out"):
wait_for_deployment(access_token, metadata)
class TestDataTransformConfig:
@patch(
"builtins.open",
new_callable=mock_open,
read_data=(
'{"sdkVersion": "1.0.0", "entryPoint": "entrypoint.py", '
'"dataspace": "test_dataspace", '
'"permissions": {"read": {"dlo": ["input_dlo"]}, '
'"write": {"dlo": ["output_dlo"]}}}'
),
)
def test_get_config(self, mock_file):
"""Test getting data transform config from config.json file."""
result = get_config("/test/dir")
assert isinstance(result, DataTransformConfig)
assert result.sdkVersion == "1.0.0"
assert result.entryPoint == "entrypoint.py"
assert result.dataspace == "test_dataspace"
assert result.permissions.read.dlo == ["input_dlo"]
assert result.permissions.write.dlo == ["output_dlo"]
@patch("datacustomcode.deploy.os.path.exists")
def test_verify_data_transform_config_missing(self, mock_exists):
"""Test verifying data transform config file when it doesn't exist."""
mock_exists.return_value = False
with pytest.raises(
FileNotFoundError,
match="config.json not found at /test/dir/payload/config.json",
):
get_config("/test/dir/payload")
@patch("datacustomcode.deploy.os.path.exists")
@patch("builtins.open", new_callable=mock_open, read_data='{"invalid": "json"')
def test_verify_data_transform_config_invalid_json(self, mock_file, mock_exists):
"""Test verifying data transform config with invalid JSON."""
mock_exists.return_value = True
with pytest.raises(
ValueError,
match="config.json at /test/dir/payload/config.json is not valid JSON",
):
get_config("/test/dir/payload")
@patch("datacustomcode.deploy.os.path.exists")
@patch("builtins.open", new_callable=mock_open, read_data='{"sdkVersion": "1.0.0"}')
def test_verify_data_transform_config_missing_fields(self, mock_file, mock_exists):
"""Test verifying data transform config with missing required fields."""
mock_exists.return_value = True
with pytest.raises(
ValueError,
match="config.json at /test/dir/payload/config.json is missing "
"required fields: entryPoint, dataspace, permissions",
):
get_config("/test/dir/payload")
class TestCreateDataTransform:
@patch("datacustomcode.deploy.get_config")
@patch("datacustomcode.deploy._make_api_call")
def test_create_data_transform(self, mock_make_api_call, mock_get_config):
"""Test creating a data transform in DataCloud."""
access_token = AccessTokenResponse(
access_token="test_token", instance_url="https://instance.example.com"