-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathtest_pipeline.py
More file actions
2435 lines (2002 loc) · 91.1 KB
/
Copy pathtest_pipeline.py
File metadata and controls
2435 lines (2002 loc) · 91.1 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
import os
import tempfile
from unittest.mock import Mock, patch
import pytest
import yaml
from click.testing import CliRunner
from clarifai.cli.pipeline import compile as compile_command
from clarifai.cli.pipeline import init, run, upload
from clarifai.cli.pipeline_template import info, list_templates
from clarifai.runners.pipelines.pipeline_builder import (
PipelineBuilder,
PipelineConfigValidator,
upload_pipeline,
)
class TestPipelineConfigValidator:
"""Test cases for PipelineConfigValidator."""
def test_validate_config_missing_pipeline_section(self):
"""Test validation with missing pipeline section."""
config = {}
with pytest.raises(ValueError, match="'pipeline' section not found"):
PipelineConfigValidator.validate_config(config)
def test_validate_config_missing_required_fields(self):
"""Test validation with missing required fields."""
config = {"pipeline": {}}
with pytest.raises(ValueError, match="'id' not found in pipeline section"):
PipelineConfigValidator.validate_config(config)
def test_validate_config_empty_required_fields(self):
"""Test validation with empty required fields."""
config = {"pipeline": {"id": "", "user_id": "test-user", "app_id": "test-app"}}
with pytest.raises(ValueError, match="'id' cannot be empty"):
PipelineConfigValidator.validate_config(config)
def test_validate_config_missing_orchestration_spec(self):
"""Test validation with missing orchestration spec."""
config = {
"pipeline": {"id": "test-pipeline", "user_id": "test-user", "app_id": "test-app"}
}
with pytest.raises(ValueError, match="'orchestration_spec' not found"):
PipelineConfigValidator.validate_config(config)
def test_validate_config_invalid_argo_yaml(self):
"""Test validation with invalid Argo YAML."""
config = {
"pipeline": {
"id": "test-pipeline",
"user_id": "test-user",
"app_id": "test-app",
"orchestration_spec": {"argo_orchestration_spec": "invalid: yaml: :"},
}
}
with pytest.raises(ValueError, match="Invalid YAML in argo_orchestration_spec"):
PipelineConfigValidator.validate_config(config)
def test_validate_config_valid_config(self):
"""Test validation with valid config."""
config = {
"pipeline": {
"id": "test-pipeline",
"user_id": "test-user",
"app_id": "test-app",
"step_directories": ["stepA", "stepB"],
"orchestration_spec": {
"argo_orchestration_spec": """
apiVersion: argoproj.io/v1alpha1
kind: Workflow
metadata:
generateName: test-workflow
spec:
entrypoint: sequence
templates:
- name: sequence
steps:
- - name: step1
templateRef:
name: users/test-user/apps/test-app/pipeline_steps/stepA
template: users/test-user/apps/test-app/pipeline_steps/stepA
- - name: step2
templateRef:
name: users/test-user/apps/test-app/pipeline_steps/stepB/versions/123
template: users/test-user/apps/test-app/pipeline_steps/stepB/versions/123
"""
},
}
}
# Should not raise any exception
PipelineConfigValidator.validate_config(config)
def test_validate_template_ref_invalid_name_template_mismatch(self):
"""Test template ref validation with name/template mismatch."""
config = {
"pipeline": {
"id": "test-pipeline",
"user_id": "test-user",
"app_id": "test-app",
"orchestration_spec": {
"argo_orchestration_spec": """
apiVersion: argoproj.io/v1alpha1
kind: Workflow
spec:
templates:
- name: sequence
steps:
- - name: step1
templateRef:
name: users/test-user/apps/test-app/pipeline_steps/stepA
template: users/test-user/apps/test-app/pipeline_steps/stepB
"""
},
}
}
with pytest.raises(ValueError, match="templateRef name .* must match template"):
PipelineConfigValidator.validate_config(config)
def test_validate_template_ref_invalid_pattern(self):
"""Test template ref validation with invalid pattern."""
config = {
"pipeline": {
"id": "test-pipeline",
"user_id": "test-user",
"app_id": "test-app",
"orchestration_spec": {
"argo_orchestration_spec": """
apiVersion: argoproj.io/v1alpha1
kind: Workflow
spec:
templates:
- name: sequence
steps:
- - name: step1
templateRef:
name: invalid-pattern
template: invalid-pattern
"""
},
}
}
with pytest.raises(ValueError, match="templateRef name .* must match either pattern"):
PipelineConfigValidator.validate_config(config)
def test_get_pipeline_steps_without_versions(self):
"""Test getting pipeline steps without versions."""
config = {
"pipeline": {
"id": "test-pipeline",
"user_id": "test-user",
"app_id": "test-app",
"orchestration_spec": {
"argo_orchestration_spec": """
apiVersion: argoproj.io/v1alpha1
kind: Workflow
spec:
templates:
- name: sequence
steps:
- - name: step1
templateRef:
name: users/test-user/apps/test-app/pipeline_steps/stepA
template: users/test-user/apps/test-app/pipeline_steps/stepA
- - name: step2
templateRef:
name: users/test-user/apps/test-app/pipeline_steps/stepB/versions/123
template: users/test-user/apps/test-app/pipeline_steps/stepB/versions/123
"""
},
}
}
steps = PipelineConfigValidator.get_pipeline_steps_without_versions(config)
assert steps == ["stepA"]
class TestPipelineBuilder:
"""Test cases for PipelineBuilder."""
@pytest.fixture
def sample_config(self):
"""Sample valid configuration for testing."""
return {
"pipeline": {
"id": "test-pipeline",
"user_id": "test-user",
"app_id": "test-app",
"step_directories": ["stepA"],
"orchestration_spec": {
"argo_orchestration_spec": """
apiVersion: argoproj.io/v1alpha1
kind: Workflow
metadata:
generateName: test-workflow
spec:
entrypoint: sequence
templates:
- name: sequence
steps:
- - name: step1
templateRef:
name: users/test-user/apps/test-app/pipeline_steps/stepA
template: users/test-user/apps/test-app/pipeline_steps/stepA
"""
},
}
}
@pytest.fixture
def temp_config_file(self, sample_config):
"""Create a temporary config file for testing."""
with tempfile.NamedTemporaryFile(mode='w', suffix='.yaml', delete=False) as f:
yaml.dump(sample_config, f)
temp_path = f.name
yield temp_path
# Cleanup
if os.path.exists(temp_path):
os.unlink(temp_path)
def test_pipeline_builder_initialization(self, temp_config_file):
"""Test PipelineBuilder initialization."""
builder = PipelineBuilder(temp_config_file)
assert builder.pipeline_id == "test-pipeline"
assert builder.user_id == "test-user"
assert builder.app_id == "test-app"
assert builder.config_path == os.path.abspath(temp_config_file)
def test_pipeline_builder_invalid_config(self):
"""Test PipelineBuilder with invalid config."""
with tempfile.NamedTemporaryFile(mode='w', suffix='.yaml', delete=False) as f:
yaml.dump({"invalid": "config"}, f)
temp_path = f.name
try:
with pytest.raises(ValueError, match="'pipeline' section not found"):
PipelineBuilder(temp_path)
finally:
os.unlink(temp_path)
@patch('clarifai.runners.pipelines.pipeline_builder.BaseClient')
def test_client_property(self, mock_base_client, temp_config_file):
"""Test the client property creates a BaseClient."""
mock_client_instance = Mock()
mock_base_client.return_value = mock_client_instance
builder = PipelineBuilder(temp_config_file)
client = builder.client
mock_base_client.assert_called_once_with(user_id="test-user", app_id="test-app")
assert client == mock_client_instance
def test_save_config(self, temp_config_file, sample_config):
"""Test saving configuration back to file."""
builder = PipelineBuilder(temp_config_file)
# Modify config
builder.config["pipeline"]["id"] = "modified-pipeline"
builder._save_config()
# Read back and verify
with open(temp_config_file, 'r') as f:
saved_config = yaml.safe_load(f)
assert saved_config["pipeline"]["id"] == "modified-pipeline"
@patch(
'clarifai.runners.pipelines.pipeline_builder.PipelineBuilder._upload_pipeline_step_with_version_capture'
)
def test_upload_pipeline_steps_success(self, mock_upload, temp_config_file):
"""Test successful pipeline steps upload."""
mock_upload.return_value = (True, "version-123")
builder = PipelineBuilder(temp_config_file)
# Mock the directory existence
with patch('os.path.exists', return_value=True):
result = builder.upload_pipeline_steps()
assert result is True
assert builder.uploaded_step_versions == {"stepA": "version-123"}
@patch(
'clarifai.runners.pipelines.pipeline_builder.PipelineBuilder._upload_pipeline_step_with_version_capture'
)
def test_upload_pipeline_steps_failure(self, mock_upload, temp_config_file):
"""Test pipeline steps upload failure."""
mock_upload.return_value = (False, "")
builder = PipelineBuilder(temp_config_file)
# Mock the directory existence
with patch('os.path.exists', return_value=True):
result = builder.upload_pipeline_steps()
assert result is False
def test_upload_pipeline_steps_empty_directories(self, temp_config_file):
"""Test upload with empty step directories."""
builder = PipelineBuilder(temp_config_file)
builder.config["pipeline"]["step_directories"] = []
result = builder.upload_pipeline_steps()
assert result is False
@patch('clarifai.runners.pipelines.pipeline_builder.BaseClient')
def test_create_pipeline_success(self, mock_base_client, temp_config_file):
"""Test successful pipeline creation."""
mock_client_instance = Mock()
mock_base_client.return_value = mock_client_instance
# Mock successful response
mock_response = Mock()
mock_response.status.code = 10000 # SUCCESS status code
# Mock pipeline in response for logging
mock_pipeline = Mock()
mock_pipeline.id = "test-pipeline"
mock_pipeline_version = Mock()
mock_pipeline_version.id = "version-123"
mock_pipeline.pipeline_version = mock_pipeline_version
mock_response.pipelines = [mock_pipeline]
mock_client_instance.STUB.PostPipelines.return_value = mock_response
# Mock user_app_id properly
from clarifai_grpc.grpc.api import resources_pb2
mock_user_app_id = resources_pb2.UserAppIDSet(user_id="test-user", app_id="test-app")
mock_client_instance.user_app_id = mock_user_app_id
builder = PipelineBuilder(temp_config_file)
success, version_id = builder.create_pipeline()
assert success is True
assert version_id == "version-123"
mock_client_instance.STUB.PostPipelines.assert_called_once()
@patch('clarifai.runners.pipelines.pipeline_builder.BaseClient')
def test_create_pipeline_failure(self, mock_base_client, temp_config_file):
"""Test pipeline creation failure."""
mock_client_instance = Mock()
mock_base_client.return_value = mock_client_instance
# Mock failure response
mock_response = Mock()
mock_response.status.code = 40400 # FAILURE status code
mock_response.status.description = "Test error"
mock_response.status.details = "Test details"
mock_client_instance.STUB.PostPipelines.return_value = mock_response
# Mock user_app_id properly
from clarifai_grpc.grpc.api import resources_pb2
mock_user_app_id = resources_pb2.UserAppIDSet(user_id="test-user", app_id="test-app")
mock_client_instance.user_app_id = mock_user_app_id
builder = PipelineBuilder(temp_config_file)
success, version_id = builder.create_pipeline()
assert success is False
assert version_id == ""
class TestPipelineCLIIntegration:
"""Integration tests for the pipeline CLI command."""
def test_cli_upload_help(self):
"""Test the CLI help output."""
runner = CliRunner()
result = runner.invoke(upload, ['--help'])
assert result.exit_code == 0
assert "Upload a pipeline with associated pipeline steps" in result.output
assert "PATH" in result.output
assert '--user_id' in result.output
assert '--app_id' in result.output
assert '--user-id' not in result.output
assert '--app-id' not in result.output
def test_cli_compile_help_uses_underscore_identity_flags(self):
"""Test compile help uses the existing underscore flag convention."""
runner = CliRunner()
result = runner.invoke(compile_command, ['--help'])
assert result.exit_code == 0
assert '--user_id' in result.output
assert '--app_id' in result.output
assert '--user-id' not in result.output
assert '--app-id' not in result.output
def test_cli_upload_missing_config(self):
"""Test CLI upload with missing config file."""
runner = CliRunner()
with tempfile.TemporaryDirectory() as temp_dir:
config_path = os.path.join(temp_dir, "nonexistent.yaml")
result = runner.invoke(upload, [config_path])
assert result.exit_code != 0 # Should fail
# Should fail due to missing file
def test_cli_upload_invalid_config(self):
"""Test CLI upload with invalid config file."""
runner = CliRunner()
with tempfile.TemporaryDirectory() as temp_dir:
config_path = os.path.join(temp_dir, "invalid.yaml")
# Create invalid config
invalid_config = {"invalid": "config"}
with open(config_path, 'w') as f:
yaml.dump(invalid_config, f)
result = runner.invoke(upload, [config_path])
assert result.exit_code == 1
# Should fail due to invalid config structure
class TestPipelineConfigValidatorEdgeCases:
"""Additional edge case tests for PipelineConfigValidator."""
def test_validate_config_step_directories_not_list(self):
"""Test validation when step_directories is not a list."""
config = {
"pipeline": {
"id": "test-pipeline",
"user_id": "test-user",
"app_id": "test-app",
"step_directories": "not-a-list",
"orchestration_spec": {
"argo_orchestration_spec": """
apiVersion: argoproj.io/v1alpha1
kind: Workflow
spec:
templates: []
"""
},
}
}
with pytest.raises(ValueError, match="'step_directories' must be a list"):
PipelineConfigValidator.validate_config(config)
def test_validate_argo_workflow_missing_required_fields(self):
"""Test Argo workflow validation with missing required fields."""
config = {
"pipeline": {
"id": "test-pipeline",
"user_id": "test-user",
"app_id": "test-app",
"orchestration_spec": {
"argo_orchestration_spec": """
kind: Workflow
spec:
templates: []
"""
},
}
}
with pytest.raises(ValueError, match="'apiVersion' not found in argo_orchestration_spec"):
PipelineConfigValidator.validate_config(config)
def test_validate_argo_workflow_wrong_api_version(self):
"""Test Argo workflow validation with wrong API version."""
config = {
"pipeline": {
"id": "test-pipeline",
"user_id": "test-user",
"app_id": "test-app",
"orchestration_spec": {
"argo_orchestration_spec": """
apiVersion: v1
kind: Workflow
spec:
templates: []
"""
},
}
}
with pytest.raises(
ValueError, match="argo_orchestration_spec must have apiVersion 'argoproj.io/v1alpha1'"
):
PipelineConfigValidator.validate_config(config)
def test_validate_argo_workflow_wrong_kind(self):
"""Test Argo workflow validation with wrong kind."""
config = {
"pipeline": {
"id": "test-pipeline",
"user_id": "test-user",
"app_id": "test-app",
"orchestration_spec": {
"argo_orchestration_spec": """
apiVersion: argoproj.io/v1alpha1
kind: Pod
spec:
templates: []
"""
},
}
}
with pytest.raises(ValueError, match="argo_orchestration_spec must have kind 'Workflow'"):
PipelineConfigValidator.validate_config(config)
def test_validate_template_ref_missing_fields(self):
"""Test template ref validation with missing fields."""
config = {
"pipeline": {
"id": "test-pipeline",
"user_id": "test-user",
"app_id": "test-app",
"orchestration_spec": {
"argo_orchestration_spec": """
apiVersion: argoproj.io/v1alpha1
kind: Workflow
spec:
templates:
- name: sequence
steps:
- - name: step1
templateRef:
name: users/test-user/apps/test-app/pipeline_steps/stepA
"""
},
}
}
with pytest.raises(
ValueError, match="templateRef must have both 'name' and 'template' fields"
):
PipelineConfigValidator.validate_config(config)
def test_get_pipeline_steps_without_versions_empty(self):
"""Test getting pipeline steps when all have versions."""
config = {
"pipeline": {
"id": "test-pipeline",
"user_id": "test-user",
"app_id": "test-app",
"orchestration_spec": {
"argo_orchestration_spec": """
apiVersion: argoproj.io/v1alpha1
kind: Workflow
spec:
templates:
- name: sequence
steps:
- - name: step1
templateRef:
name: users/test-user/apps/test-app/pipeline_steps/stepA/versions/123
template: users/test-user/apps/test-app/pipeline_steps/stepA/versions/123
"""
},
}
}
steps = PipelineConfigValidator.get_pipeline_steps_without_versions(config)
assert steps == []
class TestPipelineBuilderEdgeCases:
"""Additional edge case tests for PipelineBuilder."""
@pytest.fixture
def config_without_step_directories(self):
"""Config without step_directories field."""
return {
"pipeline": {
"id": "test-pipeline",
"user_id": "test-user",
"app_id": "test-app",
"orchestration_spec": {
"argo_orchestration_spec": """
apiVersion: argoproj.io/v1alpha1
kind: Workflow
metadata:
generateName: test-workflow
spec:
entrypoint: sequence
templates:
- name: sequence
steps:
- - name: step1
templateRef:
name: users/test-user/apps/test-app/pipeline_steps/stepA/versions/123
template: users/test-user/apps/test-app/pipeline_steps/stepA/versions/123
"""
},
}
}
@pytest.fixture
def temp_config_file_no_dirs(self, config_without_step_directories):
"""Create a temporary config file without step directories."""
with tempfile.NamedTemporaryFile(mode='w', suffix='.yaml', delete=False) as f:
yaml.dump(config_without_step_directories, f)
temp_path = f.name
yield temp_path
# Cleanup
if os.path.exists(temp_path):
os.unlink(temp_path)
def test_pipeline_builder_no_step_directories(self, temp_config_file_no_dirs):
"""Test PipelineBuilder with config that has no step_directories but all templateRefs have versions."""
builder = PipelineBuilder(temp_config_file_no_dirs)
# Should succeed when step_directories is missing but all templateRefs already have versions
result = builder.upload_pipeline_steps()
assert result is True
assert builder.uploaded_step_versions == {}
def test_update_config_with_no_versions(self, temp_config_file_no_dirs):
"""Test that config remains unchanged when no versions were uploaded."""
builder = PipelineBuilder(temp_config_file_no_dirs)
# Config should be unchanged when no versions are available
assert "step_directories" not in builder.config["pipeline"]
class TestUploadPipeline:
"""Test cases for the upload_pipeline function."""
@patch('clarifai.runners.pipelines.pipeline_builder.PipelineBuilder')
def test_upload_pipeline_with_file_path_success(self, mock_builder_class):
"""Test successful pipeline upload with file path."""
mock_builder = Mock()
mock_builder_class.return_value = mock_builder
mock_builder.upload_pipeline_steps.return_value = True
mock_builder.create_pipeline.return_value = (True, "version-123")
mock_builder.ensure_app_exists.return_value = True
# Should not raise any exception
upload_pipeline("test-config.yaml")
mock_builder_class.assert_called_once_with("test-config.yaml")
mock_builder.ensure_app_exists.assert_called_once()
mock_builder.upload_pipeline_steps.assert_called_once()
mock_builder.create_pipeline.assert_called_once()
# Note: config.yaml is no longer modified during pipeline upload
@patch('clarifai.runners.pipelines.pipeline_builder.PipelineBuilder')
@patch('os.path.isdir')
@patch('os.path.exists')
def test_upload_pipeline_with_directory_path_success(
self, mock_exists, mock_isdir, mock_builder_class
):
"""Test successful pipeline upload with directory path."""
mock_builder = Mock()
mock_builder_class.return_value = mock_builder
mock_isdir.return_value = True
mock_exists.return_value = True # config.yaml exists in directory
mock_builder.upload_pipeline_steps.return_value = True
mock_builder.create_pipeline.return_value = (True, "version-123")
mock_builder.ensure_app_exists.return_value = True
# Should not raise any exception
path_to_dir = "/path/to/directory"
upload_pipeline(path_to_dir)
# Should call PipelineBuilder with the config.yaml path
mock_builder_class.assert_called_once_with(os.path.join(path_to_dir, "config.yaml"))
mock_builder.ensure_app_exists.assert_called_once()
mock_builder.upload_pipeline_steps.assert_called_once()
mock_builder.create_pipeline.assert_called_once()
# Note: config.yaml is no longer modified during pipeline upload
@patch('os.path.isdir')
@patch('os.path.exists')
@patch('sys.exit')
def test_upload_pipeline_directory_without_config(self, mock_exit, mock_exists, mock_isdir):
"""Test pipeline upload with directory path but no config.yaml."""
mock_isdir.return_value = True
mock_exists.return_value = False # config.yaml does not exist in directory
mock_exit.side_effect = SystemExit(1)
with pytest.raises(SystemExit):
upload_pipeline("/path/to/directory")
mock_exit.assert_called_once_with(1)
@patch('clarifai.runners.pipelines.pipeline_builder.PipelineBuilder')
def test_upload_pipeline_success(self, mock_builder_class):
"""Test successful pipeline upload."""
mock_builder = Mock()
mock_builder_class.return_value = mock_builder
mock_builder.upload_pipeline_steps.return_value = True
mock_builder.create_pipeline.return_value = (True, "version-123")
mock_builder.ensure_app_exists.return_value = True
# Should not raise any exception
upload_pipeline("test-config.yaml")
mock_builder.ensure_app_exists.assert_called_once()
mock_builder.upload_pipeline_steps.assert_called_once()
mock_builder.create_pipeline.assert_called_once()
# Note: config.yaml is no longer modified during pipeline upload
@patch('clarifai.runners.pipelines.pipeline_builder.PipelineBuilder')
@patch('sys.exit')
def test_upload_pipeline_app_check_failure(self, mock_exit, mock_builder_class):
"""Test pipeline upload exits when app ensure/create fails."""
mock_builder = Mock()
mock_builder_class.return_value = mock_builder
mock_builder.ensure_app_exists.return_value = False
mock_exit.side_effect = SystemExit(1)
with pytest.raises(SystemExit):
upload_pipeline("test-config.yaml")
mock_exit.assert_called_once_with(1)
mock_builder.upload_pipeline_steps.assert_not_called()
mock_builder.create_pipeline.assert_not_called()
@patch('clarifai.runners.pipelines.pipeline_builder.PipelineBuilder')
@patch('sys.exit')
def test_upload_pipeline_step_failure(self, mock_exit, mock_builder_class):
"""Test pipeline upload with step failure."""
mock_builder = Mock()
mock_builder_class.return_value = mock_builder
mock_builder.ensure_app_exists.return_value = True
mock_builder.upload_pipeline_steps.return_value = False
# Make sys.exit raise an exception to stop execution
mock_exit.side_effect = SystemExit(1)
with pytest.raises(SystemExit):
upload_pipeline("test-config.yaml")
mock_exit.assert_called_once_with(1)
mock_builder.create_pipeline.assert_not_called()
@patch('clarifai.runners.pipelines.pipeline_builder.PipelineBuilder')
@patch('sys.exit')
def test_upload_pipeline_creation_failure(self, mock_exit, mock_builder_class):
"""Test pipeline upload with creation failure."""
mock_builder = Mock()
mock_builder_class.return_value = mock_builder
mock_builder.ensure_app_exists.return_value = True
mock_builder.upload_pipeline_steps.return_value = True
mock_builder.create_pipeline.return_value = (False, "")
upload_pipeline("test-config.yaml")
mock_exit.assert_called_once_with(1)
class TestUploadPipelineCLIIntegration:
"""Integration tests for CLI with new path handling."""
def test_cli_upload_with_directory_path(self):
"""Test CLI upload with directory path containing config.yaml."""
runner = CliRunner()
with runner.isolated_filesystem():
# Create a directory with config.yaml
os.makedirs("pipeline_dir")
config_content = {
"pipeline": {
"id": "test-pipeline",
"user_id": "test-user",
"app_id": "test-app",
"orchestration_spec": {
"argo_orchestration_spec": """
apiVersion: argoproj.io/v1alpha1
kind: Workflow
spec:
templates: []
"""
},
}
}
with open("pipeline_dir/config.yaml", 'w') as f:
yaml.dump(config_content, f)
# Mock the pipeline upload to avoid actual API calls
with patch(
'clarifai.runners.pipelines.pipeline_builder.PipelineBuilder'
) as mock_builder_class:
mock_builder = Mock()
mock_builder_class.return_value = mock_builder
mock_builder.upload_pipeline_steps.return_value = True
mock_builder.create_pipeline.return_value = (True, "version-123")
pipeline_dir_path = 'pipeline_dir'
result = runner.invoke(upload, [pipeline_dir_path])
# Should succeed
assert result.exit_code == 0
# Should have called PipelineBuilder with the config.yaml path
expected_config_path = os.path.join(pipeline_dir_path, "config.yaml")
mock_builder_class.assert_called_once_with(expected_config_path)
def test_cli_upload_with_file_path(self):
"""Test CLI upload with direct config.yaml file path."""
runner = CliRunner()
with runner.isolated_filesystem():
# Create a config.yaml file
config_content = {
"pipeline": {
"id": "test-pipeline",
"user_id": "test-user",
"app_id": "test-app",
"orchestration_spec": {
"argo_orchestration_spec": """
apiVersion: argoproj.io/v1alpha1
kind: Workflow
spec:
templates: []
"""
},
}
}
with open("my-config.yaml", 'w') as f:
yaml.dump(config_content, f)
# Mock the pipeline upload to avoid actual API calls
with patch(
'clarifai.runners.pipelines.pipeline_builder.PipelineBuilder'
) as mock_builder_class:
mock_builder = Mock()
mock_builder_class.return_value = mock_builder
mock_builder.upload_pipeline_steps.return_value = True
mock_builder.create_pipeline.return_value = (True, "version-123")
result = runner.invoke(upload, ['my-config.yaml'])
# Should succeed
assert result.exit_code == 0
# Should have called PipelineBuilder with the file path
expected_config_path = "my-config.yaml"
mock_builder_class.assert_called_once_with(expected_config_path)
class TestPipelineInitCommand:
"""Test cases for the pipeline init CLI command."""
def test_init_command_creates_expected_structure(self):
"""Test that init command creates the expected directory structure."""
runner = CliRunner(env={"PYTHONIOENCODING": "utf-8"})
with runner.isolated_filesystem():
# Provide inputs for the interactive prompts
inputs = "test-user\ntest-app\nhello-world-pipeline\n2\nstepA\nstepB\n"
result = runner.invoke(init, ['.'], input=inputs)
assert result.exit_code == 0
# Check that all expected files were created
expected_files = [
'config.yaml',
'README.md',
'stepA/config.yaml',
'stepA/requirements.txt',
'stepA/1/pipeline_step.py',
'stepB/config.yaml',
'stepB/requirements.txt',
'stepB/1/pipeline_step.py',
]
for file_path in expected_files:
assert os.path.exists(file_path), f"Expected file {file_path} was not created"
def test_init_command_with_custom_inputs(self):
"""Test that init command works with custom user inputs."""
runner = CliRunner(env={"PYTHONIOENCODING": "utf-8"})
with runner.isolated_filesystem():
# Provide custom inputs
inputs = "custom-user\ncustom-app\ncustom-pipeline\n3\ndata-prep\nmodel-train\nmodel-deploy\n"
result = runner.invoke(init, ['.'], input=inputs)
assert result.exit_code == 0
# Check that custom step directories were created
assert os.path.exists('data-prep/config.yaml')
assert os.path.exists('model-train/config.yaml')
assert os.path.exists('model-deploy/config.yaml')
# Verify the pipeline config contains the custom values
with open('config.yaml', 'r') as f:
config = yaml.safe_load(f)
assert config['pipeline']['id'] == 'custom-pipeline'
assert config['pipeline']['user_id'] == 'custom-user'
assert config['pipeline']['app_id'] == 'custom-app'
assert config['pipeline']['step_directories'] == [
'data-prep',
'model-train',
'model-deploy',
]
def test_init_command_dir_uses_context_user_and_app_without_prompting(self):
"""Test that explicit DIR init uses context user/app without prompting for them."""
runner = CliRunner(env={"PYTHONIOENCODING": "utf-8"})
class MockContext:
def __init__(self):
self.user_id = 'ctx-user'
self.app_id = 'ctx-app'
def get(self, key, default=None):
return getattr(self, key, default)
class MockConfig:
def __init__(self):
self.current = MockContext()
with runner.isolated_filesystem():
# only prompts for pipeline id, num steps, and step names
inputs = "ctx-pipeline\n2\nstepA\nstepB\n"
result = runner.invoke(init, ['my_pipeline'], input=inputs, obj=MockConfig())
assert result.exit_code == 0
assert "User ID" not in result.output
assert "App ID" not in result.output
with open('my_pipeline/config.yaml', 'r') as f:
config = yaml.safe_load(f)
assert config['pipeline']['user_id'] == 'ctx-user'
assert config['pipeline']['app_id'] == 'ctx-app'
def test_init_command_dir_uses_default_app_id_when_context_app_missing(self):
"""Test explicit DIR init falls back to pipeline-app when app_id missing in context."""
runner = CliRunner(env={"PYTHONIOENCODING": "utf-8"})
class MockContext:
def __init__(self):
self.user_id = 'ctx-user'
self.app_id = None
def get(self, key, default=None):
return getattr(self, key, default)
class MockConfig:
def __init__(self):
self.current = MockContext()
with runner.isolated_filesystem():
inputs = "ctx-pipeline\n2\nstepA\nstepB\n"
result = runner.invoke(init, ['my_pipeline'], input=inputs, obj=MockConfig())
assert result.exit_code == 0
assert "App ID" not in result.output
with open('my_pipeline/config.yaml', 'r') as f:
config = yaml.safe_load(f)
assert config['pipeline']['user_id'] == 'ctx-user'
assert config['pipeline']['app_id'] == 'pipeline-app'
def test_init_command_dir_app_id_option_overrides_context_app(self):
"""Test explicit DIR init uses --app_id over context app_id."""
runner = CliRunner(env={"PYTHONIOENCODING": "utf-8"})
class MockContext:
def __init__(self):
self.user_id = 'ctx-user'
self.app_id = 'ctx-app'
def get(self, key, default=None):
return getattr(self, key, default)
class MockConfig:
def __init__(self):
self.current = MockContext()
with runner.isolated_filesystem():
result = runner.invoke(
init, ['--app_id', 'override-app', 'my_pipeline'], obj=MockConfig()
)