-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathtest_cli.py
More file actions
1389 lines (1192 loc) · 40.3 KB
/
test_cli.py
File metadata and controls
1389 lines (1192 loc) · 40.3 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 json
import os
import uuid
from collections.abc import Callable, Mapping
from dataclasses import dataclass
from io import StringIO
from pathlib import Path
from textwrap import dedent
from typing import Any, TypeVar
from unittest import mock
from unittest.mock import Mock, patch
import pytest
import responses
import yaml
from bluesky.protocols import Movable
from bluesky_stomp.messaging import StompClient
from bluesky_stomp.models import MessageTopic
from click.testing import CliRunner
from ophyd_async.core import AsyncStatus
from pydantic import BaseModel
from requests.exceptions import ConnectionError
from responses import matchers
from stomp.connect import StompConnection11 as Connection
from blueapi import __version__
from blueapi.cli.cli import ParametersType, main
from blueapi.cli.format import OutputFormat, fmt_dict
from blueapi.client.event_bus import BlueskyStreamingError
from blueapi.client.rest import (
BlueskyRemoteControlError,
InvalidParametersError,
ParameterError,
UnauthorisedAccessError,
UnknownPlanError,
)
from blueapi.config import (
ApplicationConfig,
ScratchConfig,
ScratchRepository,
generate_config_schema,
)
from blueapi.core.bluesky_types import DataEvent, Plan
from blueapi.service.model import (
DeviceModel,
DeviceResponse,
EnvironmentResponse,
PlanModel,
PlanResponse,
PythonEnvironmentResponse,
TaskRequest,
TaskResponse,
)
from blueapi.worker.event import (
ProgressEvent,
TaskError,
TaskResult,
TaskStatus,
WorkerEvent,
WorkerState,
)
@pytest.fixture
def mock_connection() -> Mock:
return Mock(spec=Connection)
@pytest.fixture
def mock_stomp_client(mock_connection: Mock) -> StompClient:
return StompClient(conn=mock_connection)
@pytest.fixture
def runner():
return CliRunner()
def test_cli_version(runner: CliRunner):
result = runner.invoke(main, ["--version"])
assert result.stdout == f"blueapi, version {__version__}\n"
def test_main_no_params():
runner = CliRunner()
result = runner.invoke(main)
expected = "Please invoke subcommand!\n"
assert result.stdout == expected
@patch("blueapi.service.main.start")
@patch("blueapi.cli.scratch.setup_scratch")
@patch("blueapi.cli.cli.os.umask")
@pytest.mark.parametrize("subcommand", ["serve", "setup-scratch"])
def test_runs_with_umask_002(
mock_umask: Mock,
mock_setup_scratch: Mock,
mock_start: Mock,
runner: CliRunner,
subcommand: str,
):
runner.invoke(main, [subcommand])
mock_umask.assert_called_once_with(0o002)
@patch("blueapi.client.rest.requests.Session.request")
def test_connection_error_caught_by_wrapper_func(
mock_requests: Mock, runner: CliRunner
):
mock_requests.side_effect = ConnectionError()
result = runner.invoke(main, ["controller", "plans"])
assert result.output == "Error: Failed to establish connection to blueapi server.\n"
@patch("blueapi.client.rest.requests.Session.request")
def test_authentication_error_caught_by_wrapper_func(
mock_requests: Mock, runner: CliRunner
):
mock_requests.side_effect = UnauthorisedAccessError(message="<Response [401]>")
result = runner.invoke(main, ["controller", "plans"])
assert (
result.output
== "Error: Access denied. Please check your login status and try again.\n"
)
@patch("blueapi.client.rest.requests.Session.request")
def test_remote_error_raised_by_wrapper_func(mock_requests: Mock, runner: CliRunner):
mock_requests.side_effect = BlueskyRemoteControlError("Response [450]")
result = runner.invoke(main, ["controller", "plans"])
assert (
isinstance(result.exception, BlueskyRemoteControlError)
and result.exception.args == ("Response [450]",)
and result.exit_code == 1
)
class MyModel(BaseModel):
id: str
ComplexType = TypeVar("ComplexType")
@dataclass
class MyDevice(Movable[ComplexType]):
name: str
@AsyncStatus.wrap
async def set(self, value: ComplexType): ...
@responses.activate
def test_get_plans(runner: CliRunner):
plan = Plan(name="my-plan", model=MyModel)
response = responses.add(
responses.GET,
"http://localhost:8000/plans",
json=PlanResponse(plans=[PlanModel.from_plan(plan)]).model_dump(),
status=200,
)
plans = runner.invoke(main, ["controller", "plans"])
assert response.call_count == 1
assert plans.output == "my-plan\n Args\n id=string (Required)\n"
@responses.activate
def test_get_devices(runner: CliRunner):
device = MyDevice(name="my-device")
response = responses.add(
responses.GET,
"http://localhost:8000/devices",
json=DeviceResponse(devices=[DeviceModel.from_device(device)]).model_dump(),
status=200,
)
plans = runner.invoke(main, ["controller", "devices"])
assert response.call_count == 1
assert plans.output == "my-device\n Movable['ComplexType']\n"
def test_invalid_config_path_handling(runner: CliRunner):
# test what happens if you pass an invalid config file...
result = runner.invoke(main, ["-c", "non_existent.yaml"])
assert result.exit_code == 1
@patch("blueapi.cli.cli.BlueapiClient.plans")
@patch("blueapi.cli.cli.OutputFormat.FULL.display")
def test_options_via_env(mock_display, mock_plans, runner: CliRunner):
result = runner.invoke(
main, args=["controller", "plans"], env={"BLUEAPI_CONTROLLER_OUTPUT": "full"}
)
mock_plans.__iter__.assert_called_once_with()
mock_display.assert_called_once_with(PlanResponse(plans=list(mock_plans)))
assert result.exit_code == 0
def test_invalid_config_via_env(runner: CliRunner):
result = runner.invoke(main, env={"BLUEAPI_CONFIG": "non_existent.yaml"})
assert result.exit_code == 1
@responses.activate
def test_submit_plan(runner: CliRunner):
body_data = {
"name": "sleep",
"params": {"time": 5},
"instrument_session": "cm12345-1",
}
response = responses.post(
url="http://a.fake.host:12345/tasks",
match=[matchers.json_params_matcher(body_data)],
)
config_path = "tests/unit_tests/example_yaml/rest_and_stomp_config.yaml"
output = runner.invoke(
main,
[
"-c",
config_path,
"controller",
"run",
"-i",
"cm12345-1",
"sleep",
'{"time": 5}',
],
)
assert response.call_count == 1, output.output
@responses.activate
def test_submit_plan_without_stomp(runner: CliRunner):
config_path = "tests/unit_tests/example_yaml/rest_config.yaml"
result = runner.invoke(
main,
[
"-c",
config_path,
"controller",
"run",
"-i",
"cm12345-1",
"sleep",
'{"time": 5}',
],
)
assert (
result.stderr
== "Error: Stomp configuration required to run plans is missing or disabled\n"
)
@patch("blueapi.client.client.StompClient")
@responses.activate
def test_run_plan(stomp_client: StompClient, runner: CliRunner):
task_id = "abcd-1234"
submit_response = responses.post(
url="http://a.fake.host:12345/tasks",
match=[
matchers.json_params_matcher(
{
"name": "sleep",
"params": {"time": 3},
"instrument_session": "cm12345-1",
}
)
],
json={"task_id": task_id},
status=201,
)
run_response = responses.put(
url="http://a.fake.host:12345/worker/task",
match=[matchers.json_params_matcher({"task_id": task_id})],
json={"task_id": task_id},
)
def mock_events(topic: MessageTopic, callback: Callable[[Any, Any], Any]):
if topic.name != "public.worker.event":
return
ctx = Mock()
ctx.correlation_id = task_id
callback(
WorkerEvent(
state=WorkerState.RUNNING,
task_status=TaskStatus(
task_id=task_id,
task_complete=False,
task_failed=False,
result=None,
),
),
ctx,
)
callback(ProgressEvent(task_id=task_id), ctx)
callback(DataEvent(name="event", doc={}, task_id=task_id), ctx)
callback(
WorkerEvent(
state=WorkerState.IDLE,
task_status=TaskStatus(
task_id=task_id, task_complete=False, task_failed=False, result=None
),
),
ctx,
)
callback(
WorkerEvent(
state=WorkerState.IDLE,
task_status=TaskStatus(
task_id=task_id,
task_complete=True,
task_failed=False,
result=TaskResult(result=None, type="NoneType"),
),
),
ctx,
)
stomp = stomp_client.for_broker(...) # type: ignore
stomp.subscribe.side_effect = mock_events # type: ignore
config_path = "tests/unit_tests/example_yaml/rest_and_stomp_config.yaml"
result = runner.invoke(
main,
[
"-c",
config_path,
"controller",
"run",
"-i",
"cm12345-1",
"sleep",
'{"time": 3}',
],
)
assert result.exit_code == 0
assert submit_response.call_count == 1
assert run_response.call_count == 1
@pytest.mark.parametrize(
"result,failed,message",
[
(TaskResult(result=None, type="NoneType"), False, "Plan succeeded\n"),
(TaskResult(result=32, type="int"), False, "Plan succeeded: 32\n"),
(
TaskResult(result=None, type="CustomType"),
False,
"Plan returned unserializable result of type 'CustomType'\n",
),
(
TaskError(type="ValueError", message="Error with value"),
True,
"Plan failed: ValueError: Error with value\n",
),
],
)
@patch("blueapi.cli.cli.BlueapiClient")
def test_run_plan_feedback(
mock_client: Mock,
runner: CliRunner,
result: TaskResult | TaskError | None,
failed: bool,
message: str,
):
bc = mock_client.from_config()
bc.run_task.return_value = TaskStatus(
task_id="foo_bar",
task_complete=True,
task_failed=failed,
result=result,
)
res = runner.invoke(
main,
["controller", "run", "-i", "cm12345-1", "name"],
)
bc.run_task.assert_called_once_with(
TaskRequest(name="name", params={}, instrument_session="cm12345-1"),
on_event=mock.ANY,
)
assert res.exit_code == 0
assert res.stdout == message
@responses.activate
def test_run_plan_background_without_stomp(runner: CliRunner):
submit_response = responses.post(
url="http://a.fake.host:12345/tasks",
match=[
matchers.json_params_matcher(
{
"name": "sleep",
"params": {"time": 3},
"instrument_session": "cm12345-1",
}
)
],
json={"task_id": "abcd-1234"},
status=201,
)
run_response = responses.put(
url="http://a.fake.host:12345/worker/task",
match=[matchers.json_params_matcher({"task_id": "abcd-1234"})],
json={"task_id": "abcd-1234"},
)
config_path = "tests/unit_tests/example_yaml/rest_config.yaml"
result = runner.invoke(
main,
[
"-c",
config_path,
"controller",
"run",
"-i",
"cm12345-1",
"--background",
"sleep",
'{"time": 3}',
],
)
assert result.exit_code == 0
assert result.output == "abcd-1234\n"
assert submit_response.call_count == 1
assert run_response.call_count == 1
def test_invalid_stomp_config_for_listener(runner: CliRunner):
result = runner.invoke(main, ["controller", "listen"])
assert isinstance(result.exception, BlueskyStreamingError)
assert str(result.exception) == "Message bus needs to be configured"
def test_cannot_run_plans_without_stomp_config(runner: CliRunner):
result = runner.invoke(
main,
[
"controller",
"run",
"-i",
"cm12345-1",
"sleep",
'{"time": 5}',
],
)
assert result.exit_code == 1
assert (
result.stderr
== "Error: Stomp configuration required to run plans is missing or disabled\n"
)
def test_cannot_start_a_plan_without_an_instrument_session(runner: CliRunner):
result = runner.invoke(
main,
[
"controller",
"run",
"--background",
"sleep",
'{"time": 5}',
],
)
assert result.exit_code == 2
assert "Error: Missing option '-i' / '--instrument-session'.\n" in result.stderr
@patch("blueapi.client.rest.BlueapiRestClient.update_worker_task")
@patch("blueapi.client.rest.BlueapiRestClient.create_task")
def test_can_pass_an_instrument_session_with_an_environment_variable(
mock_create_task: Mock, mock_update_worker_task: Mock, runner: CliRunner
):
mock_create_task.return_value = TaskResponse(task_id="foo")
mock_update_worker_task.return_value = TaskResponse(task_id="foo")
with patch.dict(
os.environ,
{"BLUEAPI_CONTROLLER_RUN_INSTRUMENT_SESSION": "cm12345-1"},
clear=True,
):
# assert visit passed to rest
result = runner.invoke(
main,
[
"controller",
"run",
"--background",
"sleep",
'{"time": 5.0}',
],
)
assert result.exit_code == 0, result.output
mock_create_task.assert_called_once_with(
TaskRequest(
name="sleep",
params={"time": 5.0},
instrument_session="cm12345-1",
)
)
@patch("blueapi.cli.cli.StompClient")
def test_valid_stomp_config_for_listener(
mock_stomp_client: StompClient,
runner: CliRunner,
mock_connection: Mock,
):
mock_connection.is_connected.return_value = True
result = runner.invoke(
main,
[
"-c",
"tests/unit_tests/example_yaml/valid_stomp_config.yaml",
"controller",
"listen",
],
input="\n",
)
assert result.output == dedent("""\
Subscribing to all bluesky events from localhost:61613
Press enter to exit
""")
assert result.exit_code == 0
@responses.activate
def test_get_env(runner: CliRunner):
environment_id = uuid.uuid4()
responses.add(
responses.GET,
"http://localhost:8000/environment",
json=EnvironmentResponse(
environment_id=environment_id, initialized=True
).model_dump(mode="json"),
status=200,
)
env = runner.invoke(main, ["controller", "env"])
assert (
env.output == f"environment_id=UUID('{environment_id}') "
"initialized=True "
"error_message=None\n"
)
@responses.activate
def test_get_state(runner: CliRunner):
responses.add(
responses.GET, "http://localhost:8000/worker/state", json="IDLE", status=200
)
state = runner.invoke(main, ["controller", "state"])
print(state.stderr)
assert state.exit_code == 0
assert state.output == "IDLE\n"
@responses.activate(assert_all_requests_are_fired=True)
@patch("blueapi.client.client.time.sleep", return_value=None)
def test_reset_env_client_behavior(
mock_sleep: Mock,
runner: CliRunner,
):
environment_id = uuid.uuid4()
responses.add(
responses.DELETE,
"http://localhost:8000/environment",
json=EnvironmentResponse(
environment_id=environment_id, initialized=False
).model_dump(mode="json"),
status=200,
)
env_state = [False, False, True]
environment_id = uuid.uuid4()
for state in env_state:
responses.add(
responses.GET,
"http://localhost:8000/environment",
json=EnvironmentResponse(
environment_id=environment_id, initialized=state
).model_dump(mode="json"),
status=200,
)
# Invoke the CLI command that would trigger the environment initialization check
reload_result = runner.invoke(main, ["controller", "env", "-r"])
# Verify if sleep was called between polling iterations
mock_sleep.assert_called()
for index, call in enumerate(responses.calls):
if index == 0:
assert call.request.method == "DELETE"
assert call.request.url == "http://localhost:8000/environment"
else:
assert call.request.method == "GET"
assert call.request.url == "http://localhost:8000/environment"
# Check if the final environment status is printed correctly
# assert "Environment is initialized." in result.output
assert reload_result.output == dedent(f"""\
Reloading environment
Environment is initialized
environment_id=UUID('{environment_id}') initialized=True error_message=None
""") # noqa: E501
@responses.activate
@patch("blueapi.client.client.time.sleep", return_value=None)
def test_env_timeout(mock_sleep: Mock, runner: CliRunner):
# Setup mocked responses for the REST endpoints
environment_id = uuid.uuid4()
responses.add(
responses.DELETE,
"http://localhost:8000/environment",
status=200,
json=EnvironmentResponse(
environment_id=environment_id, initialized=False
).model_dump(mode="json"),
)
# Add responses for each polling attempt, all indicating not initialized
responses.add(
responses.GET,
"http://localhost:8000/environment",
json=EnvironmentResponse(
environment_id=environment_id, initialized=False
).model_dump(mode="json"),
status=200,
)
# Run the command that should interact with these endpoints
result = runner.invoke(main, ["controller", "env", "-r", "-t", "0.1"])
if result.exception is not None:
assert isinstance(result.exception, TimeoutError), "Expected a TimeoutError"
assert (
result.exception.args[0]
== "Failed to reload the environment within 0.1 seconds, "
"a server restart is recommended"
)
else:
raise AssertionError("Expected an exception but got None")
# First call should be DELETE
assert responses.calls[0].request.method == "DELETE"
assert responses.calls[0].request.url == "http://localhost:8000/environment"
# Remaining calls should all be GET
for call in responses.calls[1:]: # Skip the first DELETE request # type: ignore
assert call.request.method == "GET"
assert call.request.url == "http://localhost:8000/environment"
# Check the output for the timeout message
assert result.output == "Reloading environment\n"
assert (
result.exit_code == 1
) # Assuming your command exits successfully even on timeout for simplicity
@responses.activate
def test_env_reload_server_side_error(runner: CliRunner):
# Setup mocked error response from the server
responses.add(
responses.DELETE, "http://localhost:8000/environment", status=500, json={}
)
result = runner.invoke(main, ["controller", "env", "-r"])
assert isinstance(result.exception, BlueskyRemoteControlError), (
"Expected a BlueskyRemoteError from cli runner"
)
assert result.exception.args[0] == "Failed to tear down the environment"
# Check if the endpoints were hit as expected
assert len(responses.calls) == 1 # +1 for the DELETE call
# Only call should be DELETE
assert responses.calls[0].request.method == "DELETE"
assert responses.calls[0].request.url == "http://localhost:8000/environment"
# Check the output for the timeout message
# TODO this seems wrong but this is the current behaviour
# There should be an error message
assert result.output == "Reloading environment\n"
assert result.exit_code == 1
@pytest.mark.parametrize(
"exception, error_message",
[
(UnknownPlanError(), "Error: Plan 'sleep' was not recognised\n"),
(UnauthorisedAccessError(), "Error: Unauthorised request\n"),
(
InvalidParametersError(
errors=[
ParameterError(
loc=["body", "params", "foo"],
type="missing",
msg="Foo is missing",
input=None,
)
]
),
"Error: Incorrect parameters supplied\n Missing value for 'foo'\n",
),
(
BlueskyRemoteControlError("Server error"),
"Error: remote control error: Server error\n",
),
(
ValueError("Error parsing parameters"),
"Error: task could not run: Error parsing parameters\n",
),
(
BlueskyStreamingError("streaming failed"),
"Error: streaming error: streaming failed\n",
),
],
ids=[
"unknown_plan",
"unauthorised_access",
"invalid_parameters",
"remote_control",
"value_error",
"streaming_error",
],
)
def test_error_handling(exception, error_message, runner: CliRunner):
# Patching the create_task method to raise different exceptions
with patch(
"blueapi.client.rest.BlueapiRestClient.create_task", side_effect=exception
):
result = runner.invoke(
main,
[
"-c",
"tests/unit_tests/example_yaml/valid_stomp_config.yaml",
"controller",
"run",
"-i",
"cm12345-1",
"sleep",
'{"time": 5}',
],
)
assert result.stderr == error_message
assert result.exit_code == 1
@pytest.mark.parametrize(
"params, error",
[
("{", "Parameters are not valid JSON"),
("[]", "Parameters must be a JSON object with string keys"),
],
)
def test_run_task_parsing_errors(params: str, error: str, runner: CliRunner):
result = runner.invoke(
main,
[
"-c",
"tests/unit_tests/example_yaml/valid_stomp_config.yaml",
"controller",
"run",
"-i",
"cm12345-1",
"sleep",
params,
],
)
assert error in result.stderr
assert result.exit_code == 2
def test_device_output_formatting():
"""Test for alternative device output formats"""
device = MyDevice("my-device")
devices = DeviceResponse(devices=[DeviceModel.from_device(device)])
compact = dedent("""\
my-device
Movable['ComplexType']
""")
_assert_matching_formatting(OutputFormat.COMPACT, devices, compact)
json_out = dedent("""\
[
{
"name": "my-device",
"protocols": [
{
"name": "Movable",
"types": [
"ComplexType"
]
}
]
}
]
""")
_assert_matching_formatting(OutputFormat.JSON, devices, json_out)
_ = json.loads(json_out)
full = dedent("""\
my-device
Movable['ComplexType']
""")
_assert_matching_formatting(OutputFormat.FULL, devices, full)
class ExtendedModel(BaseModel):
name: str
keys: list[int]
metadata: None | Mapping[str, str] = None
def test_plan_output_formatting():
"""Test for alternative plan output formats"""
plan = Plan(
name="my-plan",
description=dedent("""\
Summary of description
Rest of description
"""),
model=ExtendedModel,
)
plans = PlanResponse(plans=[PlanModel.from_plan(plan)])
compact = dedent("""\
my-plan
Summary of description
Args
name=string (Required)
keys=[integer] (Required)
metadata=object
""")
_assert_matching_formatting(OutputFormat.COMPACT, plans, compact)
json_out = dedent("""\
[
{
"name": "my-plan",
"description": "Summary of description\\n\\nRest of description\\n",
"parameter_schema": {
"properties": {
"name": {
"title": "Name",
"type": "string"
},
"keys": {
"items": {
"type": "integer"
},
"title": "Keys",
"type": "array"
},
"metadata": {
"anyOf": [
{
"additionalProperties": {
"type": "string"
},
"type": "object"
},
{
"type": "null"
}
],
"default": null,
"title": "Metadata"
}
},
"required": [
"name",
"keys"
],
"title": "ExtendedModel",
"type": "object"
}
}
]
""")
_assert_matching_formatting(OutputFormat.JSON, plans, json_out)
_ = json.loads(json_out)
full = dedent("""\
my-plan
Summary of description
Rest of description
Schema
{
"properties": {
"name": {
"title": "Name",
"type": "string"
},
"keys": {
"items": {
"type": "integer"
},
"title": "Keys",
"type": "array"
},
"metadata": {
"anyOf": [
{
"additionalProperties": {
"type": "string"
},
"type": "object"
},
{
"type": "null"
}
],
"default": null,
"title": "Metadata"
}
},
"required": [
"name",
"keys"
],
"title": "ExtendedModel",
"type": "object"
}
""")
_assert_matching_formatting(OutputFormat.FULL, plans, full)
def test_event_formatting():
data = DataEvent(
name="start",
doc={"foo": "bar", "fizz": {"buzz": (1, 2, 3), "hello": "world"}},
task_id="0000-1111",
)
worker = WorkerEvent(
state=WorkerState.RUNNING,
task_status=TaskStatus(
task_id="count", task_complete=False, task_failed=False, result=None
),
errors=[],
warnings=[],
)
progress = ProgressEvent(task_id="start", statuses={})
_assert_matching_formatting(
OutputFormat.JSON,
data,
(
"""{"name": "start", "doc": """
"""{"foo": "bar", "fizz": {"buzz": [1, 2, 3], "hello": "world"}}, """
""""task_id": "0000-1111"}\n"""
),
)
_assert_matching_formatting(OutputFormat.COMPACT, data, "Data Event: start\n")
_assert_matching_formatting(
OutputFormat.FULL,
data,
dedent("""\
Start:
foo: bar
fizz:
buzz: (1, 2, 3)
hello: world
"""),
)
_assert_matching_formatting(
OutputFormat.JSON,
worker,
(
'{"state": "RUNNING", "task_status": {'
'"task_id": "count", '
'"result": null, '
'"task_complete": false, '
'"task_failed": false'
'}, "errors": [], "warnings": []}\n'
),
)
_assert_matching_formatting(OutputFormat.COMPACT, worker, "Worker Event: RUNNING\n")
_assert_matching_formatting(
OutputFormat.FULL,