-
Notifications
You must be signed in to change notification settings - Fork 442
/
test_client.py
1575 lines (1298 loc) · 53.3 KB
/
test_client.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
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) ZenML GmbH 2022. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
# https://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.
import os
import random
import string
from contextlib import ExitStack as does_not_raise
from contextlib import contextmanager
from typing import Any, Dict, Generator, Optional
from uuid import uuid4
import pytest
from pydantic import BaseModel
from tests.integration.functional.conftest import (
constant_int_output_test_step,
int_plus_one_test_step,
)
from tests.integration.functional.utils import sample_name
from zenml.client import Client
from zenml.config.pipeline_spec import PipelineSpec
from zenml.config.source import Source
from zenml.constants import PAGE_SIZE_DEFAULT
from zenml.enums import (
MetadataResourceTypes,
ModelStages,
SecretScope,
StackComponentType,
)
from zenml.exceptions import (
EntityExistsError,
IllegalOperationError,
InitializationException,
StackComponentExistsError,
StackExistsError,
)
from zenml.io import fileio
from zenml.metadata.metadata_types import MetadataTypeEnum
from zenml.model.model_version import ModelVersion
from zenml.models import (
ComponentResponse,
PipelineBuildRequest,
PipelineDeploymentRequest,
PipelineRequest,
StackResponse,
)
from zenml.utils import io_utils
from zenml.utils.string_utils import random_str
def _create_local_orchestrator(
client: Client,
orchestrator_name: str = "OrchesTraitor",
) -> ComponentResponse:
return client.create_stack_component(
name=orchestrator_name,
flavor="local",
component_type=StackComponentType.ORCHESTRATOR,
configuration={},
)
def _create_local_artifact_store(
client: Client,
artifact_store_name: str = "Art-E-Fact",
) -> ComponentResponse:
return client.create_stack_component(
name=artifact_store_name,
flavor="local",
component_type=StackComponentType.ARTIFACT_STORE,
configuration={},
)
def _create_local_stack(
client: Client,
stack_name: str,
orchestrator_name: Optional[str] = None,
artifact_store_name: Optional[str] = None,
) -> StackResponse:
"""Creates a local stack with components with the given names. If the names are not given, a random string is used instead."""
def _random_name():
return "".join(random.choices(string.ascii_letters, k=10))
orchestrator = _create_local_orchestrator(
client=client, orchestrator_name=orchestrator_name or _random_name()
)
artifact_store = _create_local_artifact_store(
client=client,
artifact_store_name=artifact_store_name or _random_name(),
)
return client.create_stack(
name=stack_name,
components={
StackComponentType.ORCHESTRATOR: str(orchestrator.id),
StackComponentType.ARTIFACT_STORE: str(artifact_store.id),
},
)
def test_repository_detection(tmp_path):
"""Tests detection of ZenML repositories in a directory."""
assert Client.is_repository_directory(tmp_path) is False
Client.initialize(tmp_path)
assert Client.is_repository_directory(tmp_path) is True
def test_initializing_repo_creates_directory_and_uses_default_stack(
tmp_path, clean_client
):
"""Tests that repo initialization creates a .zen directory and uses the default local stack."""
Client.initialize(tmp_path)
assert fileio.exists(str(tmp_path / ".zen"))
client = Client()
# switch to the new repo root
client.activate_root(tmp_path)
stack = client.active_stack_model
assert isinstance(
stack.components[StackComponentType.ORCHESTRATOR][0],
ComponentResponse,
)
assert isinstance(
stack.components[StackComponentType.ARTIFACT_STORE][0],
ComponentResponse,
)
with pytest.raises(KeyError):
assert stack.components[StackComponentType.CONTAINER_REGISTRY]
def test_initializing_repo_twice_fails(tmp_path):
"""Tests that initializing a repo in a directory where another repo already exists fails."""
Client.initialize(tmp_path)
with pytest.raises(InitializationException):
Client.initialize(tmp_path)
def test_freshly_initialized_repo_attributes(tmp_path):
"""Tests that the attributes of a new repository are set correctly."""
Client.initialize(tmp_path)
client = Client(tmp_path)
assert client.root == tmp_path
def test_finding_repository_directory_with_explicit_path(
tmp_path, clean_client
):
"""Tests that a repository can be found using an explicit path, an environment variable and the current working directory."""
subdirectory_path = tmp_path / "some_other_directory"
io_utils.create_dir_recursive_if_not_exists(str(subdirectory_path))
os.chdir(str(subdirectory_path))
# no repo exists and explicit path passed
assert Client.find_repository(tmp_path) is None
assert Client(tmp_path).root is None
# no repo exists and no path passed (=uses current working directory)
assert Client.find_repository() is None
Client._reset_instance()
assert Client().root is None
# no repo exists and explicit path set via environment variable
os.environ["ZENML_REPOSITORY_PATH"] = str(tmp_path)
assert Client.find_repository() is None
Client._reset_instance()
assert Client().root is None
del os.environ["ZENML_REPOSITORY_PATH"]
# initializing the repo
Client.initialize(tmp_path)
# repo exists and explicit path passed
assert Client.find_repository(tmp_path) == tmp_path
assert Client(tmp_path).root == tmp_path
# repo exists and explicit path to subdirectory passed
assert Client.find_repository(subdirectory_path) is None
assert Client(subdirectory_path).root is None
# repo exists and no path passed (=uses current working directory)
assert Client.find_repository() == tmp_path
Client._reset_instance()
assert Client().root == tmp_path
# repo exists and explicit path set via environment variable
os.environ["ZENML_REPOSITORY_PATH"] = str(tmp_path)
assert Client.find_repository() == tmp_path
Client._reset_instance()
assert Client().root == tmp_path
# repo exists and explicit path to subdirectory set via environment variable
os.environ["ZENML_REPOSITORY_PATH"] = str(subdirectory_path)
assert Client.find_repository() is None
Client._reset_instance()
assert Client().root is None
del os.environ["ZENML_REPOSITORY_PATH"]
def test_creating_repository_instance_during_step_execution(mocker):
"""Tests that creating a Repository instance while a step is being executed does not fail."""
mocker.patch(
"zenml.environment.Environment.step_is_running",
return_value=True,
)
with does_not_raise():
Client()
def test_activating_nonexisting_stack_fails(clean_client):
"""Tests that activating a stack name that isn't registered fails."""
with pytest.raises(KeyError):
clean_client.activate_stack(str(uuid4()))
def test_activating_a_stack_updates_the_config_file(clean_client):
"""Tests that the newly active stack name gets persisted."""
stack = _create_local_stack(client=clean_client, stack_name="new_stack")
clean_client.activate_stack(stack.id)
assert Client(clean_client.root).active_stack_model.name == stack.name
def test_registering_a_stack(clean_client):
"""Tests that registering a stack works and the stack gets persisted."""
orch = _create_local_orchestrator(
client=clean_client,
)
art = _create_local_artifact_store(
client=clean_client,
)
new_stack_name = "some_new_stack_name"
new_stack = clean_client.create_stack(
name=new_stack_name,
components={
StackComponentType.ORCHESTRATOR: str(orch.id),
StackComponentType.ARTIFACT_STORE: str(art.id),
},
)
Client(clean_client.root)
with does_not_raise():
clean_client.zen_store.get_stack(new_stack.id)
def test_registering_a_stack_with_existing_name(clean_client):
"""Tests that registering a stack for an existing name fails."""
_create_local_stack(
client=clean_client,
stack_name="axels_super_awesome_stack_of_fluffyness",
)
orchestrator = _create_local_orchestrator(clean_client)
artifact_store = _create_local_artifact_store(clean_client)
with pytest.raises(StackExistsError):
clean_client.create_stack(
name="axels_super_awesome_stack_of_fluffyness",
components={
StackComponentType.ORCHESTRATOR: str(orchestrator.id),
StackComponentType.ARTIFACT_STORE: str(artifact_store.id),
},
)
def test_updating_a_stack_with_new_component_succeeds(clean_client):
"""Tests that updating a new stack with already registered components updates the stack with the new or altered components passed in."""
stack = _create_local_stack(
client=clean_client, stack_name="some_new_stack_name"
)
clean_client.activate_stack(stack_name_id_or_prefix=stack.name)
old_orchestrator = stack.components[StackComponentType.ORCHESTRATOR][0]
old_artifact_store = stack.components[StackComponentType.ARTIFACT_STORE][0]
orchestrator = _create_local_orchestrator(
client=clean_client, orchestrator_name="different_orchestrator"
)
with does_not_raise():
updated_stack = clean_client.update_stack(
name_id_or_prefix=stack.name,
component_updates={
StackComponentType.ORCHESTRATOR: [str(orchestrator.id)],
},
)
active_orchestrator = updated_stack.components[
StackComponentType.ORCHESTRATOR
][0]
active_artifact_store = updated_stack.components[
StackComponentType.ARTIFACT_STORE
][0]
assert active_orchestrator != old_orchestrator
assert active_orchestrator == orchestrator
assert active_artifact_store == old_artifact_store
def test_renaming_stack_with_update_method_succeeds(clean_client):
"""Tests that renaming a stack with the update method succeeds."""
stack = _create_local_stack(
client=clean_client, stack_name="some_new_stack_name"
)
clean_client.activate_stack(stack.id)
new_stack_name = "new_stack_name"
with does_not_raise():
clean_client.update_stack(
name_id_or_prefix=stack.id, name=new_stack_name
)
assert clean_client.get_stack(name_id_or_prefix=new_stack_name)
def test_register_a_stack_with_unregistered_component_fails(clean_client):
"""Tests that registering a stack with an unregistered component fails."""
with pytest.raises(KeyError):
clean_client.create_stack(
name="axels_empty_stack_of_disappoint",
components={
StackComponentType.ORCHESTRATOR: "orchestrator_doesnt_exist",
StackComponentType.ARTIFACT_STORE: "this_also_doesnt",
},
)
def test_deregistering_the_active_stack(clean_client):
"""Tests that deregistering the active stack fails."""
with pytest.raises(ValueError):
clean_client.delete_stack(clean_client.active_stack_model.id)
def test_deregistering_a_non_active_stack(clean_client):
"""Tests that deregistering a non-active stack works."""
stack = _create_local_stack(
client=clean_client, stack_name="some_new_stack_name"
)
with does_not_raise():
clean_client.delete_stack(name_id_or_prefix=stack.id)
def test_getting_a_stack_component(clean_client):
"""Tests that getting a stack component returns the correct component."""
component = clean_client.active_stack_model.components[
StackComponentType.ORCHESTRATOR
][0]
with does_not_raise():
registered_component = clean_client.get_stack_component(
component_type=component.type, name_id_or_prefix=component.id
)
assert component == registered_component
def test_getting_a_nonexisting_stack_component(clean_client):
"""Tests that getting a stack component for a name that isn't registered fails."""
with pytest.raises(KeyError):
clean_client.get_stack(name_id_or_prefix=str(uuid4()))
def test_registering_a_stack_component_with_existing_name(clean_client):
"""Tests that registering a stack component for an existing name fails."""
_create_local_orchestrator(
client=clean_client, orchestrator_name="axels_orchestration_laboratory"
)
with pytest.raises(StackComponentExistsError):
clean_client.create_stack_component(
name="axels_orchestration_laboratory",
flavor="local",
component_type=StackComponentType.ORCHESTRATOR,
configuration={},
)
def test_registering_a_new_stack_component_succeeds(clean_client):
"""Tests that registering a stack component works and is persisted."""
new_artifact_store = _create_local_artifact_store(client=clean_client)
new_client = Client(clean_client.root)
with does_not_raise():
registered_artifact_store = new_client.get_stack_component(
component_type=new_artifact_store.type,
name_id_or_prefix=new_artifact_store.id,
)
assert registered_artifact_store == new_artifact_store
def test_deregistering_a_stack_component_in_stack_fails(clean_client):
"""Tests that deregistering a stack component works and is persisted."""
component = _create_local_stack(
clean_client, "", orchestrator_name="unregistered_orchestrator"
).components[StackComponentType.ORCHESTRATOR][0]
with pytest.raises(IllegalOperationError):
clean_client.delete_stack_component(
component_type=StackComponentType.ORCHESTRATOR,
name_id_or_prefix=str(component.id),
)
def test_deregistering_a_stack_component_that_is_part_of_a_registered_stack(
clean_client,
):
"""Tests that deregistering a stack component that is part of a registered stack fails."""
component = clean_client.active_stack_model.components[
StackComponentType.ORCHESTRATOR
][0]
with pytest.raises(IllegalOperationError):
clean_client.delete_stack_component(
name_id_or_prefix=component.id,
component_type=StackComponentType.ORCHESTRATOR,
)
def test_getting_a_pipeline(clean_client):
"""Tests fetching of a pipeline."""
# Non-existent ID
with pytest.raises(KeyError):
clean_client.get_pipeline(name_id_or_prefix=uuid4())
# Non-existent name
with pytest.raises(KeyError):
clean_client.get_pipeline(name_id_or_prefix="non_existent")
request = PipelineRequest(
user=clean_client.active_user.id,
workspace=clean_client.active_workspace.id,
name="pipeline",
version="1",
version_hash="",
spec=PipelineSpec(steps=[]),
)
response_1 = clean_client.zen_store.create_pipeline(request)
pipeline = clean_client.get_pipeline(name_id_or_prefix=response_1.id)
assert pipeline == response_1
pipeline = clean_client.get_pipeline(name_id_or_prefix="pipeline")
assert pipeline == response_1
pipeline = clean_client.get_pipeline(
name_id_or_prefix="pipeline", version="1"
)
assert pipeline == response_1
# Non-existent version
with pytest.raises(KeyError):
clean_client.get_pipeline(name_id_or_prefix="pipeline", version="2")
request.version = "2"
response_2 = clean_client.zen_store.create_pipeline(request)
# Gets latest version
pipeline = clean_client.get_pipeline(name_id_or_prefix="pipeline")
assert pipeline == response_2
def test_listing_pipelines(clean_client):
"""Tests listing of pipelines."""
assert clean_client.list_pipelines().total == 0
request = PipelineRequest(
user=clean_client.active_user.id,
workspace=clean_client.active_workspace.id,
name="pipeline",
version="1",
version_hash="",
spec=PipelineSpec(steps=[]),
)
response_1 = clean_client.zen_store.create_pipeline(request)
request.name = "other_pipeline"
request.version = "2"
response_2 = clean_client.zen_store.create_pipeline(request)
assert clean_client.list_pipelines().total == 2
assert clean_client.list_pipelines(name="pipeline").total == 1
assert clean_client.list_pipelines(name="pipeline").items[0] == response_1
assert clean_client.list_pipelines(version="1").total == 1
assert clean_client.list_pipelines(version="1").items[0] == response_1
assert clean_client.list_pipelines(version="2").total == 1
assert clean_client.list_pipelines(version="2").items[0] == response_2
assert (
clean_client.list_pipelines(name="other_pipeline", version="3").total
== 0
)
def test_create_run_metadata_for_pipeline_run(clean_client_with_run: Client):
"""Test creating run metadata linked only to a pipeline run."""
pipeline_run = clean_client_with_run.list_runs()[0]
existing_metadata = clean_client_with_run.list_run_metadata(
resource_id=pipeline_run.id,
resource_type=MetadataResourceTypes.PIPELINE_RUN,
)
# Assert that the created metadata is correct
new_metadata = clean_client_with_run.create_run_metadata(
metadata={"axel": "is awesome"},
resource_id=pipeline_run.id,
resource_type=MetadataResourceTypes.PIPELINE_RUN,
)
assert isinstance(new_metadata, list)
assert len(new_metadata) == 1
assert new_metadata[0].key == "axel"
assert new_metadata[0].value == "is awesome"
assert new_metadata[0].type == MetadataTypeEnum.STRING
assert new_metadata[0].resource_id == pipeline_run.id
assert new_metadata[0].resource_type == MetadataResourceTypes.PIPELINE_RUN
assert new_metadata[0].stack_component_id is None
# Assert new metadata is linked to the pipeline run
all_metadata = clean_client_with_run.list_run_metadata(
resource_id=pipeline_run.id,
resource_type=MetadataResourceTypes.PIPELINE_RUN,
)
assert len(all_metadata) == len(existing_metadata) + 1
def test_create_run_metadata_for_pipeline_run_and_component(
clean_client_with_run: Client,
):
"""Test creating metadata linked to a pipeline run and a stack component"""
pipeline_run = clean_client_with_run.list_runs()[0]
orchestrator_id = clean_client_with_run.active_stack_model.components[
"orchestrator"
][0].id
existing_metadata = clean_client_with_run.list_run_metadata(
resource_id=pipeline_run.id,
resource_type=MetadataResourceTypes.PIPELINE_RUN,
)
existing_component_metadata = clean_client_with_run.list_run_metadata(
stack_component_id=orchestrator_id
)
# Assert that the created metadata is correct
new_metadata = clean_client_with_run.create_run_metadata(
metadata={"aria": "is awesome too"},
resource_id=pipeline_run.id,
resource_type=MetadataResourceTypes.PIPELINE_RUN,
stack_component_id=orchestrator_id,
)
assert isinstance(new_metadata, list)
assert len(new_metadata) == 1
assert new_metadata[0].key == "aria"
assert new_metadata[0].value == "is awesome too"
assert new_metadata[0].type == MetadataTypeEnum.STRING
assert new_metadata[0].resource_id == pipeline_run.id
assert new_metadata[0].resource_type == MetadataResourceTypes.PIPELINE_RUN
assert new_metadata[0].stack_component_id == orchestrator_id
# Assert new metadata is linked to the pipeline run
registered_metadata = clean_client_with_run.list_run_metadata(
resource_id=pipeline_run.id,
resource_type=MetadataResourceTypes.PIPELINE_RUN,
)
assert len(registered_metadata) == len(existing_metadata) + 1
# Assert new metadata is linked to the stack component
registered_component_metadata = clean_client_with_run.list_run_metadata(
stack_component_id=orchestrator_id
)
assert (
len(registered_component_metadata)
== len(existing_component_metadata) + 1
)
def test_create_run_metadata_for_step_run(clean_client_with_run: Client):
"""Test creating run metadata linked only to a step run."""
step_run = clean_client_with_run.list_run_steps()[0]
existing_metadata = clean_client_with_run.list_run_metadata(
resource_id=step_run.id, resource_type=MetadataResourceTypes.STEP_RUN
)
# Assert that the created metadata is correct
new_metadata = clean_client_with_run.create_run_metadata(
metadata={"axel": "is awesome"},
resource_id=step_run.id,
resource_type=MetadataResourceTypes.STEP_RUN,
)
assert isinstance(new_metadata, list)
assert len(new_metadata) == 1
assert new_metadata[0].key == "axel"
assert new_metadata[0].value == "is awesome"
assert new_metadata[0].type == MetadataTypeEnum.STRING
assert new_metadata[0].resource_id == step_run.id
assert new_metadata[0].resource_type == MetadataResourceTypes.STEP_RUN
assert new_metadata[0].stack_component_id is None
# Assert new metadata is linked to the step run
registered_metadata = clean_client_with_run.list_run_metadata(
resource_id=step_run.id, resource_type=MetadataResourceTypes.STEP_RUN
)
assert len(registered_metadata) == len(existing_metadata) + 1
def test_create_run_metadata_for_step_run_and_component(
clean_client_with_run: Client,
):
"""Test creating metadata linked to a step run and a stack component"""
step_run = clean_client_with_run.list_run_steps()[0]
orchestrator_id = clean_client_with_run.active_stack_model.components[
"orchestrator"
][0].id
existing_metadata = clean_client_with_run.list_run_metadata(
resource_id=step_run.id, resource_type=MetadataResourceTypes.STEP_RUN
)
existing_component_metadata = clean_client_with_run.list_run_metadata(
stack_component_id=orchestrator_id
)
# Assert that the created metadata is correct
new_metadata = clean_client_with_run.create_run_metadata(
metadata={"aria": "is awesome too"},
resource_id=step_run.id,
resource_type=MetadataResourceTypes.STEP_RUN,
stack_component_id=orchestrator_id,
)
assert isinstance(new_metadata, list)
assert len(new_metadata) == 1
assert new_metadata[0].key == "aria"
assert new_metadata[0].value == "is awesome too"
assert new_metadata[0].type == MetadataTypeEnum.STRING
assert new_metadata[0].resource_id == step_run.id
assert new_metadata[0].resource_type == MetadataResourceTypes.STEP_RUN
assert new_metadata[0].stack_component_id == orchestrator_id
# Assert new metadata is linked to the step run
registered_metadata = clean_client_with_run.list_run_metadata(
resource_id=step_run.id, resource_type=MetadataResourceTypes.STEP_RUN
)
assert len(registered_metadata) == len(existing_metadata) + 1
# Assert new metadata is linked to the stack component
registered_component_metadata = clean_client_with_run.list_run_metadata(
stack_component_id=orchestrator_id
)
assert (
len(registered_component_metadata)
== len(existing_component_metadata) + 1
)
def test_create_run_metadata_for_artifact(clean_client_with_run: Client):
"""Test creating run metadata linked to an artifact."""
artifact_version = clean_client_with_run.list_artifact_versions()[0]
existing_metadata = clean_client_with_run.list_run_metadata(
resource_id=artifact_version.id,
resource_type=MetadataResourceTypes.ARTIFACT_VERSION,
)
# Assert that the created metadata is correct
new_metadata = clean_client_with_run.create_run_metadata(
metadata={"axel": "is awesome"},
resource_id=artifact_version.id,
resource_type=MetadataResourceTypes.ARTIFACT_VERSION,
)
assert isinstance(new_metadata, list)
assert len(new_metadata) == 1
assert new_metadata[0].key == "axel"
assert new_metadata[0].value == "is awesome"
assert new_metadata[0].type == MetadataTypeEnum.STRING
assert new_metadata[0].resource_id == artifact_version.id
assert (
new_metadata[0].resource_type == MetadataResourceTypes.ARTIFACT_VERSION
)
assert new_metadata[0].stack_component_id is None
# Assert new metadata is linked to the artifact
registered_metadata = clean_client_with_run.list_run_metadata(
resource_id=artifact_version.id,
resource_type=MetadataResourceTypes.ARTIFACT_VERSION,
)
assert len(registered_metadata) == len(existing_metadata) + 1
# .---------.
# | SECRETS |
# '---------'
def random_secret_name(prefix: str = "aria") -> str:
"""Function to get a random secret name or prefix."""
return f"pytest_{prefix}_{random_str(4)}"
@contextmanager
def random_secret_context() -> Generator[str, None, None]:
"""Context for testing secrets.
Generates a random secret prefix to avoid conflicts. Yields the prefix.
After the context is exited, all secrets with that prefix are deleted.
"""
prefix = random_secret_name()
yield prefix
client = Client()
for secret in client.list_secrets(name=f"startswith:{prefix}").items:
client.delete_secret(secret.id)
def test_create_secret_default_scope():
"""Test that secrets are created in the workspace scope by default."""
client = Client()
with random_secret_context() as name:
s = client.create_secret(
name=name,
values={"key": "value"},
)
assert s.scope == SecretScope.WORKSPACE
assert s.name == name
assert s.secret_values == {"key": "value"}
def test_create_secret_user_scope():
"""Test creating secrets in the user scope."""
client = Client()
with random_secret_context() as name:
s = client.create_secret(
name=name,
scope=SecretScope.USER,
values={"key": "value"},
)
assert s.scope == SecretScope.USER
assert s.name == name
assert s.secret_values == {"key": "value"}
def test_create_secret_existing_name_scope():
"""Test that creating a secret with an existing name fails."""
client = Client()
with random_secret_context() as name:
client.create_secret(
name=name,
values={"key": "value"},
)
with pytest.raises(EntityExistsError):
client.create_secret(
name=name,
values={"key": "value"},
)
def test_create_secret_existing_name_user_scope():
"""Test that creating a secret with an existing name in the user scope fails."""
client = Client()
with random_secret_context() as name:
client.create_secret(
name=name,
scope=SecretScope.USER,
values={"key": "value"},
)
with pytest.raises(EntityExistsError):
client.create_secret(
name=name,
scope=SecretScope.USER,
values={"key": "value"},
)
def test_create_secret_existing_name_different_scope():
"""Test that creating a secret with the same name in different scopes succeeds."""
client = Client()
with random_secret_context() as name:
s1 = client.create_secret(
name=name,
values={"key": "value"},
)
with does_not_raise():
s2 = client.create_secret(
name=name,
scope=SecretScope.USER,
values={"key": "value"},
)
assert s1.id != s2.id
assert s1.name == s2.name
# ---------------
# Pipeline Builds
# ---------------
def test_listing_builds(clean_client):
"""Tests listing builds."""
builds = clean_client.list_builds()
assert len(builds) == 0
request = PipelineBuildRequest(
user=clean_client.active_user.id,
workspace=clean_client.active_workspace.id,
images={},
is_local=False,
contains_code=True,
)
response = clean_client.zen_store.create_build(request)
builds = clean_client.list_builds()
assert len(builds) == 1
assert builds[0] == response
builds = clean_client.list_builds(stack_id=uuid4())
assert len(builds) == 0
def test_getting_builds(clean_client):
"""Tests getting builds."""
with pytest.raises(KeyError):
clean_client.get_build(str(uuid4()))
request = PipelineBuildRequest(
user=clean_client.active_user.id,
workspace=clean_client.active_workspace.id,
images={},
is_local=False,
contains_code=True,
)
response = clean_client.zen_store.create_build(request)
with does_not_raise():
build = clean_client.get_build(str(response.id))
assert build == response
def test_deleting_builds(clean_client):
"""Tests deleting builds."""
with pytest.raises(KeyError):
clean_client.delete_build(str(uuid4()))
request = PipelineBuildRequest(
user=clean_client.active_user.id,
workspace=clean_client.active_workspace.id,
images={},
is_local=False,
contains_code=True,
)
response = clean_client.zen_store.create_build(request)
with does_not_raise():
clean_client.delete_build(str(response.id))
with pytest.raises(KeyError):
clean_client.get_build(str(response.id))
# --------------------
# Pipeline Deployments
# --------------------
def test_listing_deployments(clean_client):
"""Tests listing deployments."""
deployments = clean_client.list_deployments()
assert len(deployments) == 0
request = PipelineDeploymentRequest(
user=clean_client.active_user.id,
workspace=clean_client.active_workspace.id,
stack=clean_client.active_stack.id,
run_name_template="",
pipeline_configuration={"name": "pipeline_name"},
client_version="0.12.3",
server_version="0.12.3",
)
response = clean_client.zen_store.create_deployment(request)
deployments = clean_client.list_deployments()
assert len(deployments) == 1
assert deployments[0] == response
deployments = clean_client.list_deployments(stack_id=uuid4())
assert len(deployments) == 0
def test_getting_deployments(clean_client):
"""Tests getting deployments."""
with pytest.raises(KeyError):
clean_client.get_deployment(str(uuid4()))
request = PipelineDeploymentRequest(
user=clean_client.active_user.id,
workspace=clean_client.active_workspace.id,
stack=clean_client.active_stack.id,
run_name_template="",
pipeline_configuration={"name": "pipeline_name"},
client_version="0.12.3",
server_version="0.12.3",
)
response = clean_client.zen_store.create_deployment(request)
with does_not_raise():
deployment = clean_client.get_deployment(str(response.id))
assert deployment == response
def test_deleting_deployments(clean_client):
"""Tests deleting deployments."""
with pytest.raises(KeyError):
clean_client.delete_deployment(str(uuid4()))
request = PipelineDeploymentRequest(
user=clean_client.active_user.id,
workspace=clean_client.active_workspace.id,
stack=clean_client.active_stack.id,
run_name_template="",
pipeline_configuration={"name": "pipeline_name"},
client_version="0.12.3",
server_version="0.12.3",
)
response = clean_client.zen_store.create_deployment(request)
with does_not_raise():
clean_client.delete_deployment(str(response.id))
with pytest.raises(KeyError):
clean_client.get_deployment(str(response.id))
def test_get_run(clean_client: Client, connected_two_step_pipeline):
"""Test that `get_run()` returns the correct run."""
pipeline_instance = connected_two_step_pipeline(
step_1=constant_int_output_test_step(),
step_2=int_plus_one_test_step(),
)
pipeline_instance.run()
run_ = clean_client.get_pipeline("connected_two_step_pipeline").runs[0]
assert clean_client.get_pipeline_run(run_.name) == run_
def test_get_run_fails_for_non_existent_run(clean_client: Client):
"""Test that `get_run()` raises a `KeyError` for non-existent runs."""
with pytest.raises(KeyError):
clean_client.get_pipeline_run("non_existent_run")
def test_get_unlisted_runs(clean_client: Client, connected_two_step_pipeline):
"""Test that listing unlisted runs works."""
assert len(clean_client.list_pipeline_runs(unlisted=True)) == 0
pipeline_instance = connected_two_step_pipeline(
step_1=constant_int_output_test_step(),
step_2=int_plus_one_test_step(),
)
pipeline_instance.run()
assert len(clean_client.list_pipeline_runs(unlisted=True)) == 0
pipeline_instance.run(unlisted=True)
assert len(clean_client.list_pipeline_runs(unlisted=True)) == 1
class ClientCrudTestConfig(BaseModel):
entity_name: str
create_args: Dict[str, Any] = {}
get_args: Dict[str, Any] = {}
update_args: Dict[str, Any] = {}
delete_args: Dict[str, Any] = {}
crud_test_configs = [
ClientCrudTestConfig(
entity_name="user",
create_args={"name": sample_name("user_name")},
update_args={"updated_name": sample_name("updated_user_name")},
),
ClientCrudTestConfig(
entity_name="workspace",
create_args={"name": sample_name("workspace_name"), "description": ""},
update_args={"new_name": sample_name("updated_workspace_name")},
),
ClientCrudTestConfig(
entity_name="stack",
create_args={
"name": sample_name("stack_name"),