-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathtest_base_worker.py
2060 lines (1778 loc) · 68.5 KB
/
test_base_worker.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
import uuid
from typing import Any, Dict, Optional, Type
from unittest import mock
from unittest.mock import MagicMock, Mock
import httpx
import pendulum
import pytest
from packaging import version
from pydantic import Field
from starlette import status
import prefect
import prefect.client.schemas as schemas
from prefect.blocks.core import Block
from prefect.client.base import ServerType
from prefect.client.orchestration import PrefectClient, get_client
from prefect.client.schemas import FlowRun
from prefect.client.schemas.objects import WorkerMetadata
from prefect.exceptions import (
CrashedRun,
ObjectNotFound,
)
from prefect.flows import flow
from prefect.server import models
from prefect.server.schemas.actions import WorkPoolUpdate as ServerWorkPoolUpdate
from prefect.server.schemas.core import Deployment, Flow, WorkPool
from prefect.server.schemas.responses import DeploymentResponse
from prefect.settings import (
PREFECT_API_URL,
PREFECT_TEST_MODE,
PREFECT_WORKER_PREFETCH_SECONDS,
get_current_settings,
temporary_settings,
)
from prefect.states import Completed, Pending, Running, Scheduled
from prefect.testing.utilities import AsyncMock
from prefect.utilities.pydantic import parse_obj_as
from prefect.workers.base import (
BaseJobConfiguration,
BaseVariables,
BaseWorker,
)
class WorkerTestImpl(BaseWorker):
type: str = "test"
job_configuration: Type[BaseJobConfiguration] = BaseJobConfiguration
async def run(self):
pass
@pytest.fixture(autouse=True)
async def ensure_default_agent_pool_exists(session):
# The default agent work pool is created by a migration, but is cleared on
# consecutive test runs. This fixture ensures that the default agent work
# pool exists before each test.
default_work_pool = await models.workers.read_work_pool_by_name(
session=session, work_pool_name=models.workers.DEFAULT_AGENT_WORK_POOL_NAME
)
if default_work_pool is None:
await models.workers.create_work_pool(
session=session,
work_pool=WorkPool(
name=models.workers.DEFAULT_AGENT_WORK_POOL_NAME, type="prefect-agent"
),
)
await session.commit()
@pytest.fixture
async def variables(prefect_client: PrefectClient):
await prefect_client._client.post(
"/variables/", json={"name": "test_variable_1", "value": "test_value_1"}
)
await prefect_client._client.post(
"/variables/", json={"name": "test_variable_2", "value": "test_value_2"}
)
@pytest.fixture
def no_api_url():
with temporary_settings(updates={PREFECT_TEST_MODE: False, PREFECT_API_URL: None}):
yield
async def test_worker_requires_api_url_when_not_in_test_mode(no_api_url):
with pytest.raises(ValueError, match="PREFECT_API_URL"):
async with WorkerTestImpl(
name="test",
work_pool_name="test-work-pool",
):
pass
async def test_worker_creates_work_pool_by_default_during_sync(
prefect_client: PrefectClient,
):
with pytest.raises(ObjectNotFound):
await prefect_client.read_work_pool("test-work-pool")
async with WorkerTestImpl(
name="test",
work_pool_name="test-work-pool",
) as worker:
await worker.sync_with_backend()
worker_status = worker.get_status()
assert worker_status["work_pool"]["name"] == "test-work-pool"
work_pool = await prefect_client.read_work_pool("test-work-pool")
assert str(work_pool.id) == worker_status["work_pool"]["id"]
async def test_worker_does_not_creates_work_pool_when_create_pool_is_false(
prefect_client: PrefectClient,
):
with pytest.raises(ObjectNotFound):
await prefect_client.read_work_pool("test-work-pool")
async with WorkerTestImpl(
name="test", work_pool_name="test-work-pool", create_pool_if_not_found=False
) as worker:
await worker.sync_with_backend()
worker_status = worker.get_status()
assert worker_status["work_pool"] is None
with pytest.raises(ObjectNotFound):
await prefect_client.read_work_pool("test-work-pool")
@pytest.mark.parametrize(
"setting,attr",
[
(PREFECT_WORKER_PREFETCH_SECONDS, "prefetch_seconds"),
],
)
async def test_worker_respects_settings(setting, attr):
assert (
WorkerTestImpl(name="test", work_pool_name="test-work-pool").get_status()[
"settings"
][attr]
== setting.value()
)
async def test_worker_sends_heartbeat_messages(
prefect_client: PrefectClient,
):
async with WorkerTestImpl(name="test", work_pool_name="test-work-pool") as worker:
await worker.sync_with_backend()
workers = await prefect_client.read_workers_for_work_pool(
work_pool_name="test-work-pool"
)
assert len(workers) == 1
first_heartbeat = workers[0].last_heartbeat_time
assert first_heartbeat is not None
await worker.sync_with_backend()
workers = await prefect_client.read_workers_for_work_pool(
work_pool_name="test-work-pool"
)
second_heartbeat = workers[0].last_heartbeat_time
assert second_heartbeat > first_heartbeat
async def test_worker_sends_heartbeat_gets_id(respx_mock):
work_pool_name = "test-work-pool"
test_worker_id = uuid.UUID("028EC481-5899-49D7-B8C5-37A2726E9840")
async with WorkerTestImpl(name="test", work_pool_name=work_pool_name) as worker:
setattr(worker, "_should_get_worker_id", lambda: True)
# Pass through the non-relevant paths
respx_mock.get(f"api/work_pools/{work_pool_name}").pass_through()
respx_mock.get("api/csrf-token?").pass_through()
respx_mock.post("api/work_pools/").pass_through()
respx_mock.patch(f"api/work_pools/{work_pool_name}").pass_through()
respx_mock.post(
f"api/work_pools/{work_pool_name}/workers/heartbeat",
).mock(
return_value=httpx.Response(status.HTTP_200_OK, text=str(test_worker_id))
)
await worker.sync_with_backend()
assert worker.backend_id == test_worker_id
async def test_worker_sends_heartbeat_only_gets_id_once():
async with WorkerTestImpl(name="test", work_pool_name="test-work-pool") as worker:
worker._client.server_type = ServerType.CLOUD
mock = AsyncMock(return_value="test")
setattr(worker._client, "send_worker_heartbeat", mock)
await worker.sync_with_backend()
await worker.sync_with_backend()
second_call = mock.await_args_list[1]
assert worker.backend_id == "test"
assert not second_call.kwargs["get_worker_id"]
async def test_worker_with_work_pool(
prefect_client: PrefectClient, worker_deployment_wq1, work_pool
):
@flow
def test_flow():
pass
def create_run_with_deployment(state):
return prefect_client.create_flow_run_from_deployment(
worker_deployment_wq1.id, state=state
)
flow_runs = [
await create_run_with_deployment(Pending()),
await create_run_with_deployment(
Scheduled(scheduled_time=pendulum.now("utc").subtract(days=1))
),
await create_run_with_deployment(
Scheduled(scheduled_time=pendulum.now("utc").add(seconds=5))
),
await create_run_with_deployment(
Scheduled(scheduled_time=pendulum.now("utc").add(seconds=5))
),
await create_run_with_deployment(
Scheduled(scheduled_time=pendulum.now("utc").add(seconds=20))
),
await create_run_with_deployment(Running()),
await create_run_with_deployment(Completed()),
await prefect_client.create_flow_run(test_flow, state=Scheduled()),
]
flow_run_ids = [run.id for run in flow_runs]
async with WorkerTestImpl(work_pool_name=work_pool.name) as worker:
submitted_flow_runs = await worker.get_and_submit_flow_runs()
# Should only include scheduled runs in the past or next prefetch seconds
# Should not include runs without deployments
assert {flow_run.id for flow_run in submitted_flow_runs} == set(flow_run_ids[1:4])
async def test_worker_with_work_pool_and_work_queue(
prefect_client: PrefectClient,
worker_deployment_wq1,
worker_deployment_wq_2,
work_queue_1,
work_pool,
):
@flow
def test_flow():
pass
def create_run_with_deployment_1(state):
return prefect_client.create_flow_run_from_deployment(
worker_deployment_wq1.id, state=state
)
def create_run_with_deployment_2(state):
return prefect_client.create_flow_run_from_deployment(
worker_deployment_wq_2.id, state=state
)
flow_runs = [
await create_run_with_deployment_1(Pending()),
await create_run_with_deployment_1(
Scheduled(scheduled_time=pendulum.now("utc").subtract(days=1))
),
await create_run_with_deployment_1(
Scheduled(scheduled_time=pendulum.now("utc").add(seconds=5))
),
await create_run_with_deployment_2(
Scheduled(scheduled_time=pendulum.now("utc").add(seconds=5))
),
await create_run_with_deployment_2(
Scheduled(scheduled_time=pendulum.now("utc").add(seconds=20))
),
await create_run_with_deployment_1(Running()),
await create_run_with_deployment_1(Completed()),
await prefect_client.create_flow_run(test_flow, state=Scheduled()),
]
flow_run_ids = [run.id for run in flow_runs]
async with WorkerTestImpl(
work_pool_name=work_pool.name, work_queues=[work_queue_1.name]
) as worker:
submitted_flow_runs = await worker.get_and_submit_flow_runs()
assert {flow_run.id for flow_run in submitted_flow_runs} == set(flow_run_ids[1:3])
async def test_priority_trumps_lateness(
prefect_client: PrefectClient,
worker_deployment_wq1,
worker_deployment_wq_2,
work_queue_1,
work_pool,
):
@flow
def test_flow():
pass
def create_run_with_deployment_1(state):
return prefect_client.create_flow_run_from_deployment(
worker_deployment_wq1.id, state=state
)
def create_run_with_deployment_2(state):
return prefect_client.create_flow_run_from_deployment(
worker_deployment_wq_2.id, state=state
)
flow_runs = [
await create_run_with_deployment_2(
Scheduled(scheduled_time=pendulum.now("utc").subtract(days=1))
),
await create_run_with_deployment_1(
Scheduled(scheduled_time=pendulum.now("utc").add(seconds=5))
),
]
flow_run_ids = [run.id for run in flow_runs]
async with WorkerTestImpl(work_pool_name=work_pool.name, limit=1) as worker:
worker._submit_run = AsyncMock() # don't run anything
submitted_flow_runs = await worker.get_and_submit_flow_runs()
assert {flow_run.id for flow_run in submitted_flow_runs} == set(flow_run_ids[1:2])
async def test_worker_releases_limit_slot_when_aborting_a_change_to_pending(
prefect_client: PrefectClient, worker_deployment_wq1, work_pool
):
"""Regression test for https://github.com/PrefectHQ/prefect/issues/15952"""
def create_run_with_deployment(state):
return prefect_client.create_flow_run_from_deployment(
worker_deployment_wq1.id, state=state
)
flow_run = await create_run_with_deployment(
Scheduled(scheduled_time=pendulum.now("utc").subtract(days=1))
)
run_mock = AsyncMock()
release_mock = Mock()
async with WorkerTestImpl(work_pool_name=work_pool.name, limit=1) as worker:
worker.run = run_mock
worker._propose_pending_state = AsyncMock(return_value=False)
worker._release_limit_slot = release_mock
await worker.get_and_submit_flow_runs()
run_mock.assert_not_called()
release_mock.assert_called_once_with(flow_run.id)
async def test_worker_with_work_pool_and_limit(
prefect_client: PrefectClient, worker_deployment_wq1, work_pool
):
@flow
def test_flow():
pass
def create_run_with_deployment(state):
return prefect_client.create_flow_run_from_deployment(
worker_deployment_wq1.id, state=state
)
flow_runs = [
await create_run_with_deployment(Pending()),
await create_run_with_deployment(
Scheduled(scheduled_time=pendulum.now("utc").subtract(days=1))
),
await create_run_with_deployment(
Scheduled(scheduled_time=pendulum.now("utc").add(seconds=5))
),
await create_run_with_deployment(
Scheduled(scheduled_time=pendulum.now("utc").add(seconds=5))
),
await create_run_with_deployment(
Scheduled(scheduled_time=pendulum.now("utc").add(seconds=20))
),
await create_run_with_deployment(Running()),
await create_run_with_deployment(Completed()),
await prefect_client.create_flow_run(test_flow, state=Scheduled()),
]
flow_run_ids = [run.id for run in flow_runs]
async with WorkerTestImpl(work_pool_name=work_pool.name, limit=2) as worker:
worker._submit_run = AsyncMock() # don't run anything
submitted_flow_runs = await worker.get_and_submit_flow_runs()
assert {flow_run.id for flow_run in submitted_flow_runs} == set(
flow_run_ids[1:3]
)
submitted_flow_runs = await worker.get_and_submit_flow_runs()
assert {flow_run.id for flow_run in submitted_flow_runs} == set(
flow_run_ids[1:3]
)
worker._limiter.release_on_behalf_of(flow_run_ids[1])
submitted_flow_runs = await worker.get_and_submit_flow_runs()
assert {flow_run.id for flow_run in submitted_flow_runs} == set(
flow_run_ids[1:4]
)
async def test_worker_calls_run_with_expected_arguments(
prefect_client: PrefectClient, worker_deployment_wq1, work_pool, monkeypatch
):
run_mock = AsyncMock()
@flow
def test_flow():
pass
def create_run_with_deployment(state):
return prefect_client.create_flow_run_from_deployment(
worker_deployment_wq1.id, state=state
)
flow_runs = [
await create_run_with_deployment(Pending()),
await create_run_with_deployment(
Scheduled(scheduled_time=pendulum.now("utc").subtract(days=1))
),
await create_run_with_deployment(
Scheduled(scheduled_time=pendulum.now("utc").add(seconds=5))
),
await create_run_with_deployment(
Scheduled(scheduled_time=pendulum.now("utc").add(seconds=5))
),
await create_run_with_deployment(
Scheduled(scheduled_time=pendulum.now("utc").add(seconds=20))
),
await create_run_with_deployment(Running()),
await create_run_with_deployment(Completed()),
await prefect_client.create_flow_run(test_flow, state=Scheduled()),
]
async with WorkerTestImpl(work_pool_name=work_pool.name) as worker:
worker._work_pool = work_pool
worker.run = run_mock # don't run anything
await worker.get_and_submit_flow_runs()
assert run_mock.call_count == 3
assert {call.kwargs["flow_run"].id for call in run_mock.call_args_list} == {
fr.id for fr in flow_runs[1:4]
}
async def test_worker_warns_when_running_a_flow_run_with_a_storage_block(
prefect_client: PrefectClient, deployment, work_pool, caplog
):
@flow
def test_flow():
pass
def create_run_with_deployment(state):
return prefect_client.create_flow_run_from_deployment(
deployment.id, state=state
)
flow_run = await create_run_with_deployment(
Scheduled(scheduled_time=pendulum.now("utc").add(seconds=5))
)
async with WorkerTestImpl(work_pool_name=work_pool.name) as worker:
worker._work_pool = work_pool
await worker.get_and_submit_flow_runs()
assert (
f"Flow run {flow_run.id!r} was created from deployment"
f" {deployment.name!r} which is configured with a storage block. Please use an"
+ " agent to execute this flow run."
in caplog.text
)
flow_run = await prefect_client.read_flow_run(flow_run.id)
assert flow_run.state_name == "Scheduled"
async def test_worker_creates_only_one_client_context(
prefect_client, worker_deployment_wq1, work_pool, monkeypatch, caplog
):
tracking_mock = MagicMock()
orig_get_client = get_client
def get_client_spy(*args, **kwargs):
tracking_mock(*args, **kwargs)
return orig_get_client(*args, **kwargs)
monkeypatch.setattr("prefect.workers.base.get_client", get_client_spy)
run_mock = AsyncMock()
@flow
def test_flow():
pass
def create_run_with_deployment(state):
return prefect_client.create_flow_run_from_deployment(
worker_deployment_wq1.id, state=state
)
await create_run_with_deployment(
Scheduled(scheduled_time=pendulum.now("utc").subtract(days=1))
)
await create_run_with_deployment(
Scheduled(scheduled_time=pendulum.now("utc").add(seconds=5))
)
await create_run_with_deployment(
Scheduled(scheduled_time=pendulum.now("utc").add(seconds=5))
)
async with WorkerTestImpl(work_pool_name=work_pool.name) as worker:
worker._work_pool = work_pool
worker.run = run_mock # don't run anything
await worker.get_and_submit_flow_runs()
assert tracking_mock.call_count == 1
async def test_base_worker_gets_job_configuration_when_syncing_with_backend_with_just_job_config(
session, client
):
"""We don't really care how this happens as long as the worker winds up with a worker pool
with a correct base_job_template when creating a new work pool"""
class WorkerJobConfig(BaseJobConfiguration):
other: Optional[str] = Field(
default=None, json_schema_extra={"template": "{{ other }}"}
)
# Add a job configuration for the worker (currently used to create template
# if not found on the worker pool)
WorkerTestImpl.job_configuration = WorkerJobConfig
expected_job_template = {
"job_configuration": {
"command": "{{ command }}",
"env": "{{ env }}",
"labels": "{{ labels }}",
"name": "{{ name }}",
"other": "{{ other }}",
},
"variables": {
"properties": {
"command": {
"anyOf": [{"type": "string"}, {"type": "null"}],
"default": None,
"title": "Command",
"description": (
"The command to use when starting a flow run. "
"In most cases, this should be left blank and the command "
"will be automatically generated by the worker."
),
},
"env": {
"title": "Environment Variables",
"type": "object",
"additionalProperties": {
"anyOf": [{"type": "string"}, {"type": "null"}]
},
"description": (
"Environment variables to set when starting a flow run."
),
},
"labels": {
"title": "Labels",
"type": "object",
"additionalProperties": {"type": "string"},
"description": (
"Labels applied to infrastructure created by the worker using "
"this job configuration."
),
},
"name": {
"anyOf": [{"type": "string"}, {"type": "null"}],
"default": None,
"title": "Name",
"description": (
"Name given to infrastructure created by the worker using this "
"job configuration."
),
},
"other": {
"title": "Other",
"anyOf": [{"type": "string"}, {"type": "null"}],
"default": None,
},
},
"type": "object",
},
}
pool_name = "test-pool"
# Create a new worker pool
response = await client.post(
"/work_pools/", json=dict(name=pool_name, type="test-type")
)
result = parse_obj_as(schemas.objects.WorkPool, response.json())
model = await models.workers.read_work_pool(session=session, work_pool_id=result.id)
assert model.name == pool_name
# Create a worker with the new pool and sync with the backend
worker = WorkerTestImpl(
name="test",
work_pool_name=pool_name,
)
async with get_client() as client:
worker._client = client
await worker.sync_with_backend()
assert worker._work_pool.base_job_template == expected_job_template
async def test_base_worker_gets_job_configuration_when_syncing_with_backend_with_job_config_and_variables(
session, client
):
"""We don't really care how this happens as long as the worker winds up with a worker pool
with a correct base_job_template when creating a new work pool"""
class WorkerJobConfig(BaseJobConfiguration):
other: Optional[str] = Field(
default=None, json_schema_extra={"template": "{{ other }}"}
)
class WorkerVariables(BaseVariables):
other: Optional[str] = Field(default="woof")
# Add a job configuration and variables for the worker (currently used to create template
# if not found on the worker pool)
WorkerTestImpl.job_configuration = WorkerJobConfig
WorkerTestImpl.job_configuration_variables = WorkerVariables
pool_name = "test-pool"
# Create a new worker pool
response = await client.post(
"/work_pools/", json=dict(name=pool_name, type="test-type")
)
result = parse_obj_as(schemas.objects.WorkPool, response.json())
model = await models.workers.read_work_pool(session=session, work_pool_id=result.id)
assert model.name == pool_name
# Create a worker with the new pool and sync with the backend
worker = WorkerTestImpl(
name="test",
work_pool_name=pool_name,
)
async with get_client() as client:
worker._client = client
await worker.sync_with_backend()
assert (
worker._work_pool.base_job_template
== WorkerTestImpl.get_default_base_job_template()
)
@pytest.mark.parametrize(
"template,overrides,expected",
[
(
{ # Base template with no overrides
"job_configuration": {
"command": "{{ command }}",
"env": "{{ env }}",
"labels": "{{ labels }}",
"name": "{{ name }}",
},
"variables": {
"properties": {
"command": {
"type": "string",
"title": "Command",
"default": "echo hello",
},
"env": {
"title": "Environment Variables",
"type": "object",
"additionalProperties": {"type": "string"},
"description": (
"Environment variables to set when starting a flow run."
),
},
},
"type": "object",
},
},
{}, # No overrides
{ # Expected result
"command": "echo hello",
"env": {},
"labels": {},
"name": None,
},
),
],
)
async def test_base_job_configuration_from_template_and_overrides(
template, overrides, expected
):
"""Test that the job configuration is correctly built from the template and overrides"""
config = await BaseJobConfiguration.from_template_and_values(
base_job_template=template, values=overrides
)
assert config.model_dump() == expected
@pytest.mark.parametrize(
"template,overrides,expected",
[
(
{ # Base template with no overrides
"job_configuration": {
"var1": "{{ var1 }}",
"var2": "{{ var2 }}",
},
"variables": {
"properties": {
"var1": {
"type": "string",
"title": "Var1",
"default": "hello",
},
"var2": {
"type": "integer",
"title": "Var2",
"default": 42,
},
},
"required": [],
},
},
{}, # No overrides
{ # Expected result
"command": None,
"env": {},
"labels": {},
"name": None,
"var1": "hello",
"var2": 42,
},
),
(
{ # Base template with no overrides, but unused variables
"job_configuration": {
"var1": "{{ var1 }}",
"var2": "{{ var2 }}",
},
"variables": {
"properties": {
"var1": {
"type": "string",
"title": "Var1",
"default": "hello",
},
"var2": {
"type": "integer",
"title": "Var2",
"default": 42,
},
"var3": {
"type": "integer",
"title": "Var3",
"default": 21,
},
},
"required": [],
},
},
{}, # No overrides
{ # Expected result
"command": None,
"env": {},
"labels": {},
"name": None,
"var1": "hello",
"var2": 42,
},
),
(
{ # Base template with command variables
"job_configuration": {
"var1": "{{ var1 }}",
"var2": "{{ var2 }}",
},
"variables": {
"properties": {
"var1": {
"type": "string",
"title": "Var1",
"default": "hello",
},
"var2": {
"type": "integer",
"title": "Var2",
"default": 42,
},
"command": {
"type": "string",
"title": "Command",
"default": "echo hello",
},
},
"required": [],
},
},
{}, # No overrides
{ # Expected result
"command": (
None
), # command variable is not used in the job configuration
"env": {},
"labels": {},
"name": None,
"var1": "hello",
"var2": 42,
},
),
(
{ # Base template with var1 overridden
"job_configuration": {
"var1": "{{ var1 }}",
"var2": "{{ var2 }}",
},
"variables": {
"properties": {
"var1": {
"type": "string",
"title": "Var1",
"default": "hello",
},
"var2": {
"type": "integer",
"title": "Var2",
"default": 42,
},
},
},
"required": [],
},
{"var1": "woof!"}, # var1 overridden
{ # Expected result
"command": None,
"env": {},
"labels": {},
"name": None,
"var1": "woof!",
"var2": 42,
},
),
(
{ # Base template with var1 overridden and var1 required
"job_configuration": {
"var1": "{{ var1 }}",
"var2": "{{ var2 }}",
},
"variables": {
"properties": {
"var1": {
"type": "string",
"title": "Var1",
},
"var2": {
"type": "integer",
"title": "Var2",
"default": 42,
},
},
},
"required": ["var1"],
},
{"var1": "woof!"}, # var1 overridden
{ # Expected result
"command": None,
"env": {},
"labels": {},
"name": None,
"var1": "woof!",
"var2": 42,
},
),
],
)
async def test_job_configuration_from_template_and_overrides(
template, overrides, expected
):
"""Test that the job configuration is correctly built from the template and overrides"""
class ArbitraryJobConfiguration(BaseJobConfiguration):
var1: str = Field(json_schema_extra={"template": "{{ var1 }}"})
var2: int = Field(json_schema_extra={"template": "{{ var2 }}"})
config = await ArbitraryJobConfiguration.from_template_and_values(
base_job_template=template, values=overrides
)
assert config.model_dump() == expected
async def test_job_configuration_from_template_and_overrides_with_nested_variables():
template = {
"job_configuration": {
"config": {
"var1": "{{ var1 }}",
"var2": "{{ var2 }}",
}
},
"variables": {
"properties": {
"var1": {
"type": "string",
"title": "Var1",
},
"var2": {
"type": "integer",
"title": "Var2",
"default": 42,
},
},
},
"required": ["var1"],
}
class ArbitraryJobConfiguration(BaseJobConfiguration):
config: Dict[str, Any] = Field(
json_schema_extra={
"template": {"var1": "{{ var1 }}", "var2": "{{ var2 }}"}
},
default_factory=dict,
)
config = await ArbitraryJobConfiguration.from_template_and_values(
base_job_template=template, values={"var1": "woof!"}
)
assert config.model_dump() == {
"command": None,
"env": {},
"labels": {},
"name": None,
"config": {
"var1": "woof!",
"var2": 42,
},
}
async def test_job_configuration_from_template_and_overrides_with_hard_coded_primitives():
template = {
"job_configuration": {"config": {"var1": 1, "var2": 1.1, "var3": True}},
"variables": {},
}
class ArbitraryJobConfiguration(BaseJobConfiguration):
config: Dict[str, Any] = Field(
json_schema_extra={"template": {"var1": 1, "var2": 1.1, "var3": True}}
)
config = await ArbitraryJobConfiguration.from_template_and_values(
base_job_template=template, values={}
)
assert config.model_dump() == {
"command": None,
"env": {},
"labels": {},
"name": None,
"config": {"var1": 1, "var2": 1.1, "var3": True},
}
async def test_job_configuration_from_template_overrides_with_block():
class ArbitraryBlock(Block):
a: int
b: str
template = {
"job_configuration": {
"var1": "{{ var1 }}",
"arbitrary_block": "{{ arbitrary_block }}",
},
"variables": {
"properties": {
"var1": {
"type": "string",
},
"arbitrary_block": {},
},
"definitions": {
"ArbitraryBlock": {
"title": "ArbitraryBlock",
"type": "object",
"properties": {