forked from bluesky/bluesky-queueserver
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_zmq_api_base.py
More file actions
6715 lines (5449 loc) · 259 KB
/
Copy pathtest_zmq_api_base.py
File metadata and controls
6715 lines (5449 loc) · 259 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 asyncio
import copy
import glob
import json
import os
import pprint
import re
import time as ttime
import uuid
from datetime import datetime
import msgpack
import numpy as np
import pytest
import yaml
import zmq
import bluesky_queueserver
from bluesky_queueserver import gen_list_of_plans_and_devices
from bluesky_queueserver.manager.config import get_profile_name_from_path, profile_name_to_startup_dir
from bluesky_queueserver.manager.plan_queue_ops import PlanQueueOperations
from bluesky_queueserver.manager.profile_ops import (
_prepare_devices,
_prepare_plans,
devices_from_nspace,
get_default_startup_dir,
load_allowed_plans_and_devices,
load_profile_collection,
plans_from_nspace,
)
from ..comms import (
CommTimeoutError,
ZMQCommSendAsync,
ZMQCommSendThreads,
default_zmq_control_address,
)
from .common import ( # noqa: F401
_user,
_user_group,
append_code_to_last_startup_file,
condition_environment_closed,
condition_environment_created,
condition_ip_kernel_busy,
condition_ip_kernel_idle,
condition_manager_executing_queue,
condition_manager_idle,
condition_manager_paused,
condition_queue_processing_finished,
condition_worker_executing_plan,
copy_default_profile_collection,
get_manager_status,
ip_kernel_simple_client,
re_manager,
re_manager_cmd,
re_manager_pc_copy,
remove_run_engine_config_from_startup,
use_ipykernel_for_tests,
use_zmq_encoding_for_tests,
wait_for_condition,
wait_for_task_result,
zmq_request,
)
qserver_version = bluesky_queueserver.__version__
# Plans used in most of the tests: '_plan1' and '_plan2' are quickly executed '_plan3' runs for 5 seconds.
_plan1 = {"name": "count", "args": [["det1", "det2"]], "item_type": "plan"}
_plan2 = {"name": "scan", "args": [["det1", "det2"], "motor", -1, 1, 10], "item_type": "plan"}
_plan3 = {"name": "count", "args": [["det1", "det2"]], "kwargs": {"num": 5, "delay": 1}, "item_type": "plan"}
_plan4 = {"name": "count", "args": [["det1", "det2"]], "kwargs": {"num": 10, "delay": 1}, "item_type": "plan"}
_instruction_stop = {"name": "queue_stop", "item_type": "instruction"}
# User name and user group name used throughout most of the tests.
_test_user_group = "test_user"
_existing_plans_and_devices_fln = "existing_plans_and_devices.yaml"
_user_group_permissions_fln = "user_group_permissions.yaml"
timeout_env_open = 10
# =======================================================================================
# Thread-based ZMQ API - ZMQCommSendThreads
def test_zmq_api_thread_based(re_manager): # noqa F811
"""
Communicate with the server using the thread-based API. The purpose of the test is to make
sure that the API is compatible with the client. It is sufficient to test only
the blocking call, since it is still using callbacks mechanism.
"""
encoding = use_zmq_encoding_for_tests()
client = ZMQCommSendThreads(encoding=encoding)
resp1 = client.send_message(
method="queue_item_add", params={"item": _plan1, "user": _user, "user_group": _user_group}
)
assert resp1["success"] is True, str(resp1)
assert resp1["qsize"] == 1
assert resp1["item"]["item_type"] == _plan1["item_type"]
assert resp1["item"]["name"] == _plan1["name"]
assert resp1["item"]["args"] == _plan1["args"]
assert resp1["item"]["user"] == _user
assert resp1["item"]["user_group"] == _user_group
assert "item_uid" in resp1["item"]
resp2 = client.send_message(method="queue_get")
assert resp2["items"] != []
assert len(resp2["items"]) == 1
assert resp2["items"][0] == resp1["item"]
assert resp2["running_item"] == {}
with pytest.raises(CommTimeoutError, match="timeout occurred"):
client.send_message(method="manager_kill")
# Wait until the manager is restarted
ttime.sleep(6)
resp3 = client.send_message(method="status")
assert resp3["manager_state"] == "idle"
assert resp3["items_in_queue"] == 1
assert resp3["items_in_history"] == 0
# =======================================================================================
# Thread-based ZMQ API - ZMQCommSendThreads
def test_zmq_api_asyncio_based(re_manager): # noqa F811
"""
Communicate with the server using asyncio-based API. The purpose of the test is make
sure that the API is compatible with the client.
"""
encoding = use_zmq_encoding_for_tests()
async def testing():
client = ZMQCommSendAsync(encoding=encoding)
resp1 = await client.send_message(
method="queue_item_add", params={"item": _plan1, "user": _user, "user_group": _user_group}
)
assert resp1["success"] is True, str(resp1)
assert resp1["qsize"] == 1
assert resp1["item"]["item_type"] == _plan1["item_type"]
assert resp1["item"]["name"] == _plan1["name"]
assert resp1["item"]["args"] == _plan1["args"]
assert resp1["item"]["user"] == _user
assert resp1["item"]["user_group"] == _user_group
assert "item_uid" in resp1["item"]
resp2 = await client.send_message(method="queue_get")
assert resp2["items"] != []
assert len(resp2["items"]) == 1
assert resp2["items"][0] == resp1["item"]
assert resp2["running_item"] == {}
with pytest.raises(CommTimeoutError, match="timeout occurred"):
await client.send_message(method="manager_kill")
# Wait until the manager is restarted
await asyncio.sleep(6)
resp3 = await client.send_message(method="status")
assert resp3["manager_state"] == "idle"
assert resp3["items_in_queue"] == 1
assert resp3["items_in_history"] == 0
asyncio.run(testing())
# =======================================================================================
# Requests with invalid JSON
def test_invalid_requests_1(re_manager): # noqa F811
"""
Test that RE Manager is stable when it receives invalid 0MQ requests.
"""
ctx = zmq.Context()
socket = ctx.socket(zmq.REQ)
socket.connect(default_zmq_control_address)
encoding = use_zmq_encoding_for_tests()
if encoding == "json":
socket.send(b"") # Not JSON
resp = socket.recv_json()
assert resp["success"] is False
assert "Failed to decode the request: JSON decode error:" in resp["msg"]
socket.send_string('{"method":') # Invalid JSON
resp = socket.recv_json()
assert resp["success"] is False
assert "Failed to decode the request: JSON decode error:" in resp["msg"]
socket.send_string('{"met": "status"}') # No 'method' key
resp = socket.recv_json()
assert resp["success"] is False
assert "Invalid request format: method is not specified: {'met': 'status'}" in resp["msg"]
socket.send_string('{"method": "status"}') # Valid JSON, no optional 'params'
resp = socket.recv_json()
assert "success" not in resp, str(resp)
assert "manager_state" in resp, str(resp)
assert resp["manager_state"] == "idle", str(resp)
socket.send_string('{"method": "status", "params": {}}') # Valid JSON
resp = socket.recv_json()
assert "success" not in resp, str(resp)
assert "manager_state" in resp, str(resp)
assert resp["manager_state"] == "idle", str(resp)
elif encoding == "msgpack":
socket.send(b"") # Not JSON
resp = msgpack.unpackb(socket.recv())
assert resp["success"] is False
assert "Failed to decode the request: MSGPACK decode error:" in resp["msg"]
_ = msgpack.packb({"some_key": "some_value"})
socket.send(_[:-1]) # Clipped message
resp = msgpack.unpackb(socket.recv())
assert resp["success"] is False
assert "MSGPACK decode error: Unpack failed: incomplete input" in resp["msg"]
_ = msgpack.packb({"met": "status"}) # No 'method' key
socket.send(_)
resp = msgpack.unpackb(socket.recv())
assert resp["success"] is False
assert "Invalid request format: method is not specified: {'met': 'status'}" in resp["msg"]
_ = msgpack.packb({"method": "status"}) # Valid JSON, no optional 'params'
socket.send(_)
resp = msgpack.unpackb(socket.recv())
assert "success" not in resp, str(resp)
assert "manager_state" in resp, str(resp)
assert resp["manager_state"] == "idle", str(resp)
_ = msgpack.packb({"method": "status", "params": {}}) # Valid JSON
socket.send(_)
resp = msgpack.unpackb(socket.recv())
assert "success" not in resp, str(resp)
assert "manager_state" in resp, str(resp)
assert resp["manager_state"] == "idle", str(resp)
else:
raise ValueError(f"Unknown encoding: {encoding!r}")
socket.close()
# =======================================================================================
# Methods 'ping' (currently returning status), "status"
# fmt: off
@pytest.mark.parametrize("api_name", ["ping", "status"])
# fmt: on
def test_zmq_api_ping_status_01(re_manager, api_name): # noqa F811
resp, _ = zmq_request(api_name)
assert resp["msg"] == f"RE Manager v{qserver_version}"
assert resp["manager_state"] == "idle"
assert resp["items_in_queue"] == 0
assert resp["running_item_uid"] is None
assert resp["worker_environment_exists"] is False
assert bool(resp["plan_queue_uid"])
assert isinstance(resp["plan_queue_uid"], str), type(resp["plan_queue_uid"])
assert bool(resp["plan_history_uid"])
assert isinstance(resp["plan_history_uid"], str), type(resp["plan_history_uid"])
# Run Engine state is None if RE environment does not exist. Otherwise it should
# be a string representing Run Engine state.
assert resp["re_state"] is None
assert resp["pause_pending"] is False
# Worker environment is initially 'closed'
assert resp["worker_environment_state"] == "closed"
assert isinstance(resp["plan_queue_mode"], dict)
assert resp["plan_queue_mode"]["loop"] is False
assert isinstance(resp["lock_info_uid"], str)
assert isinstance(resp["lock"], dict)
assert resp["lock"]["environment"] is False
assert resp["lock"]["queue"] is False
# fmt: off
@pytest.mark.parametrize("api_name", ["ping", "status"])
# fmt: on
def test_zmq_api_ping_status_02(re_manager, api_name): # noqa F811
"""
Check that extra parameters, such as 'reload' are ignored by the API.
"""
resp, _ = zmq_request(api_name, params={"reload": True})
assert resp["msg"] == f"RE Manager v{qserver_version}"
# =======================================================================================
# Methods 'environment_open', 'environment_close'
def test_zmq_api_environment_open_close_1(re_manager): # noqa F811
"""
Basic test for `environment_open` and `environment_close` methods.
"""
state = get_manager_status()
assert state["re_state"] is None
assert state["worker_environment_state"] == "closed"
resp1, _ = zmq_request("environment_open")
assert resp1["success"] is True
assert resp1["msg"] == ""
assert wait_for_condition(time=timeout_env_open, condition=condition_environment_created)
state = get_manager_status()
assert state["re_state"] == "idle"
assert state["worker_environment_state"] == "idle"
resp2, _ = zmq_request("environment_close")
assert resp2["success"] is True
assert resp2["msg"] == ""
assert wait_for_condition(time=3, condition=condition_environment_closed)
state = get_manager_status()
assert state["re_state"] is None
assert state["worker_environment_state"] == "closed"
def test_zmq_api_environment_open_close_2(re_manager): # noqa F811
"""
Test for `environment_open` and `environment_close` methods.
Opening/closing the environment while it is being opened/closed.
Opening the environment that already exists.
Closing the environment that does not exist.
"""
resp1a, _ = zmq_request("environment_open")
assert resp1a["success"] is True
# Attempt to open the environment before the previous operation is completed
resp1b, _ = zmq_request("environment_open")
assert resp1b["success"] is False
assert "in the process of creating the RE Worker environment" in resp1b["msg"]
assert wait_for_condition(time=timeout_env_open, condition=condition_environment_created)
# Attempt to open the environment while it already exists
resp2, _ = zmq_request("environment_open")
assert resp2["success"] is False
assert "RE Worker environment already exists" in resp2["msg"]
resp3a, _ = zmq_request("environment_close")
assert resp3a["success"] is True
# The environment is being closed.
resp3b, _ = zmq_request("environment_close")
assert resp3b["success"] is False
assert "in the process of closing the RE Worker environment" in resp3b["msg"]
assert wait_for_condition(time=3, condition=condition_environment_closed)
# The environment is already closed.
resp4, _ = zmq_request("environment_close")
assert resp4["success"] is False
assert "RE Worker environment does not exist" in resp4["msg"]
def test_zmq_api_environment_open_close_3(re_manager): # noqa F811
"""
Test for `environment_open` and `environment_close` methods.
Closing the environment while a plan is running.
"""
resp1, _ = zmq_request("environment_open")
assert resp1["success"] is True
assert resp1["msg"] == ""
assert wait_for_condition(time=timeout_env_open, condition=condition_environment_created)
# Start a plan
resp2, _ = zmq_request("queue_item_add", {"item": _plan3, "user": _user, "user_group": _user_group})
assert resp2["success"] is True
resp3, _ = zmq_request("queue_start")
assert resp3["success"] is True
# Try to close the environment while the plan is running
resp4, _ = zmq_request("environment_close")
assert resp4["success"] is False
assert "Queue execution is in progress" in resp4["msg"]
assert wait_for_condition(time=20, condition=condition_queue_processing_finished)
resp2, _ = zmq_request("environment_close")
assert resp2["success"] is True
assert resp2["msg"] == ""
assert wait_for_condition(time=3, condition=condition_environment_closed)
# fmt: off
@pytest.mark.parametrize("startup_with_re", [True, False])
# fmt: on
def test_zmq_api_environment_open_close_4(tmp_path, re_manager_cmd, startup_with_re): # noqa F811
"""
Basic test for `environment_open` and `environment_close` methods.
"""
pc_path = copy_default_profile_collection(tmp_path)
if not startup_with_re:
# Delete file with RE config
remove_run_engine_config_from_startup(pc_path)
re_manager_cmd(["--startup-dir", pc_path])
state = get_manager_status()
assert state["re_state"] is None
assert state["worker_environment_state"] == "closed"
resp1, _ = zmq_request("environment_open")
assert resp1["success"] is True
assert resp1["msg"] == ""
assert wait_for_condition(time=timeout_env_open, condition=condition_environment_created)
state = get_manager_status()
assert state["re_state"] == ("idle" if startup_with_re else None)
assert state["worker_environment_state"] == "idle"
# Test if the queue can be started
resp2, _ = zmq_request("queue_item_add", {"item": _plan3, "user": _user, "user_group": _user_group})
assert resp2["success"] is True
resp3, _ = zmq_request("queue_start")
if startup_with_re:
assert resp3["success"] is True
assert wait_for_condition(time=20, condition=condition_queue_processing_finished)
else:
assert resp3["success"] is False
assert "Run Engine is not found in the RE Worker environment" in resp3["msg"]
# Test if a single plan can be executed
params4 = {"item": _plan3, "user": _user, "user_group": _user_group}
resp4, _ = zmq_request("queue_item_execute", params4)
if startup_with_re:
assert resp4["success"] is True
assert wait_for_condition(time=20, condition=condition_queue_processing_finished)
else:
assert resp4["success"] is False
assert "Run Engine is not found in the RE Worker environment" in resp4["msg"]
resp5, _ = zmq_request("environment_close")
assert resp5["success"] is True
assert resp5["msg"] == ""
assert wait_for_condition(time=3, condition=condition_environment_closed)
state = get_manager_status()
assert state["re_state"] is None
assert state["worker_environment_state"] == "closed"
# =======================================================================================
# Method 'history_clear'
# fmt: off
@pytest.mark.parametrize("params, n_expected, success, err_msg", [
({}, 0, True, ""),
({"size": -1}, 0, True, ""),
({"size": 0}, 0, True, ""),
({"size": 1}, 1, True, ""),
({"size": 3}, 3, True, ""),
({"size": 4}, 4, True, ""),
({"size": 5}, 4, True, ""),
({"item_uid": 0}, 3, True, ""),
({"item_uid": 1}, 2, True, ""),
({"item_uid": 2}, 1, True, ""),
({"item_uid": 3}, 0, True, ""),
({"item_uid": -1}, 4, True, ""), # Random UUID - nothing is deleted
({"size": "ab"}, 4, False, "Error: The 'size' parameter must be an integer: size='ab'"),
({"item_uid": 1.5}, 4, False, "Error: The 'item_uid' parameter must be a string: item_uid=1.5"),
({"size": 2, "item_uid": 2}, 4, False, "Error: Parameters 'size' and 'item_uid' are mutually exclusive."),
])
# fmt: on
def test_zmq_api_history_clear_1(re_manager, params, n_expected, success, err_msg): # noqa: F811
"""
Basic test for ``history_clear`` API.
"""
# Add 4 plans to queue
for n in range(4):
params1a = {"item": _plan1, "user": _user, "user_group": _user_group}
resp1a, _ = zmq_request("queue_item_add", params1a)
assert resp1a["success"] is True, f"resp={resp1a}"
resp2, _ = zmq_request("environment_open")
assert resp2["success"] is True
assert wait_for_condition(time=timeout_env_open, condition=condition_environment_created)
resp3, _ = zmq_request("queue_start")
assert resp3["success"] is True
assert wait_for_condition(time=30, condition=condition_manager_idle)
resp4, _ = zmq_request("status")
assert resp4["items_in_queue"] == 0
assert resp4["items_in_history"] == 4
history, _ = zmq_request("history_get")
h_items_1 = history["items"]
assert len(h_items_1) == 4, pprint.pformat(h_items_1)
h_uids_1 = [_["item_uid"] for _ in h_items_1]
# Replace index with UUID if integer is provided
if "item_uid" in params and isinstance(params["item_uid"], int):
n = params["item_uid"]
if n >= 0:
# Select UUID based on the index of the item in the history
params["item_uid"] = h_uids_1[params["item_uid"]]
else:
# Generate random UUID
params["item_uid"] = str(uuid.uuid4())
resp5, _ = zmq_request("history_clear", params=params)
history_clear_success = resp5["success"]
assert history_clear_success is success, f"params={pprint.pformat(params)}\n{pprint.pformat(resp5)}"
assert resp5["msg"] == err_msg
resp4, _ = zmq_request("status")
assert resp4["items_in_queue"] == 0
assert resp4["items_in_history"] == n_expected
history, _ = zmq_request("history_get")
h_items_2 = history["items"]
assert len(h_items_2) == n_expected, pprint.pformat(h_items_2)
if len(h_items_2) > 0:
h_uids_2 = [_["item_uid"] for _ in h_items_2]
assert h_uids_2 == h_uids_1[-n_expected:], pprint.pformat(h_uids_2)
resp6, _ = zmq_request("environment_close")
assert resp6["success"] is True, f"resp={resp6}"
assert wait_for_condition(time=5, condition=condition_environment_closed)
# =======================================================================================
# Method 'queue_item_add'
def test_zmq_api_queue_item_add_01(re_manager): # noqa F811
"""
Basic test for `queue_item_add` method.
"""
status0 = get_manager_status()
resp1, _ = zmq_request("queue_item_add", {"item": _plan1, "user": _user, "user_group": _user_group})
assert resp1["success"] is True
assert resp1["qsize"] == 1
assert resp1["item"]["name"] == _plan1["name"]
assert resp1["item"]["args"] == _plan1["args"]
assert resp1["item"]["user"] == _user
assert resp1["item"]["user_group"] == _user_group
assert "item_uid" in resp1["item"]
status1 = get_manager_status()
assert status1["plan_queue_uid"] != status0["plan_queue_uid"]
assert status1["plan_history_uid"] == status0["plan_history_uid"]
resp2, _ = zmq_request("queue_get")
assert resp2["items"] != []
assert len(resp2["items"]) == 1
assert resp2["items"][0] == resp1["item"]
assert resp2["running_item"] == {}
assert resp2["plan_queue_uid"] == status1["plan_queue_uid"]
# fmt: off
@pytest.mark.parametrize("pos, pos_result, success", [
(None, 2, True),
("back", 2, True),
("front", 0, True),
("some", None, False),
(0, 0, True),
(1, 1, True),
(2, 2, True),
(3, 2, True),
(100, 2, True),
(-1, 2, True),
(-2, 1, True),
(-3, 0, True),
(-4, 0, True),
(-100, 0, True),
])
# fmt: on
def test_zmq_api_queue_item_add_02(re_manager, pos, pos_result, success): # noqa F811
plan1 = {"name": "count", "args": [["det1"]], "item_type": "plan"}
plan2 = {"name": "count", "args": [["det1", "det2"]], "item_type": "plan"}
# Create the queue with 2 entries
params1 = {"item": plan1, "user": _user, "user_group": _user_group}
resp0a, _ = zmq_request("queue_item_add", params1)
assert resp0a["success"] is True
resp0b, _ = zmq_request("queue_item_add", params1)
assert resp0b["success"] is True
# Add another entry at the specified position
params2 = {"item": plan2, "user": _user, "user_group": _user_group}
if pos is not None:
params2.update({"pos": pos})
resp1, _ = zmq_request("queue_item_add", params2)
assert resp1["success"] is success
assert resp1["qsize"] == (3 if success else None)
assert resp1["item"]["item_type"] == "plan"
assert resp1["item"]["name"] == "count"
assert resp1["item"]["args"] == plan2["args"]
assert resp1["item"]["user"] == _user
assert resp1["item"]["user_group"] == _user_group
assert "item_uid" in resp1["item"]
resp2, _ = zmq_request("queue_get")
assert len(resp2["items"]) == (3 if success else 2)
assert resp2["running_item"] == {}
print(f"QUEUE ITEMS: {pprint.pformat(resp2['items'])}")
if success:
assert resp2["items"][pos_result]["args"] == plan2["args"]
def test_zmq_api_queue_item_add_03(re_manager): # noqa F811
plan1 = {"name": "count", "args": [["det1"]], "item_type": "plan"}
plan2 = {"name": "count", "args": [["det1", "det2"]], "item_type": "plan"}
plan3 = {"name": "count", "args": [["det2"]], "item_type": "plan"}
params = {"item": plan1, "user": _user, "user_group": _user_group}
resp0a, _ = zmq_request("queue_item_add", params)
assert resp0a["success"] is True
params = {"item": plan2, "user": _user, "user_group": _user_group}
resp0b, _ = zmq_request("queue_item_add", params)
assert resp0b["success"] is True
base_plans = zmq_request("queue_get")[0]["items"]
params = {"item": plan3, "after_uid": base_plans[0]["item_uid"], "user": _user, "user_group": _user_group}
resp1, _ = zmq_request("queue_item_add", params)
assert resp1["success"] is True
assert resp1["qsize"] == 3
uid1 = resp1["item"]["item_uid"]
resp1a, _ = zmq_request("queue_get")
assert len(resp1a["items"]) == 3
assert resp1a["items"][1]["item_uid"] == uid1
resp1b, _ = zmq_request("queue_item_remove", {"uid": uid1})
assert resp1b["success"] is True
params = {"item": plan3, "before_uid": base_plans[1]["item_uid"], "user": _user, "user_group": _user_group}
resp2, _ = zmq_request("queue_item_add", params)
assert resp2["success"] is True
uid2 = resp2["item"]["item_uid"]
resp2a, _ = zmq_request("queue_get")
assert len(resp2a["items"]) == 3
assert resp2a["items"][1]["item_uid"] == uid2
resp2b, _ = zmq_request("queue_item_remove", {"uid": uid2})
assert resp2b["success"] is True
# Non-existing uid
params = {"item": plan3, "before_uid": "non-existing-uid", "user": _user, "user_group": _user_group}
resp2, _ = zmq_request("queue_item_add", params)
assert resp2["success"] is False
assert "is not in the queue" in resp2["msg"]
# Ambiguous parameters
params = {"item": plan3, "pos": 1, "before_uid": uid2, "user": _user, "user_group": _user_group}
resp2, _ = zmq_request("queue_item_add", params)
assert resp2["success"] is False
assert "Ambiguous parameters" in resp2["msg"]
# Ambiguous parameters
params = {"item": plan3, "before_uid": uid2, "after_uid": uid2, "user": _user, "user_group": _user_group}
resp2, _ = zmq_request("queue_item_add", params)
assert resp2["success"] is False
assert "Ambiguous parameters" in resp2["msg"]
def test_zmq_api_queue_item_add_04(re_manager): # noqa F811
"""
Try inserting plans before and after the running plan
"""
params = {"item": _plan3, "user": _user, "user_group": _user_group}
resp0a, _ = zmq_request("queue_item_add", params)
assert resp0a["success"] is True
params = {"item": _plan3, "user": _user, "user_group": _user_group}
resp0b, _ = zmq_request("queue_item_add", params)
assert resp0b["success"] is True
base_plans = zmq_request("queue_get")[0]["items"]
uid = base_plans[0]["item_uid"]
# Start the first plan (this removes it from the queue)
# Also the rest of the operations will be performed on a running queue.
resp1, _ = zmq_request("environment_open")
assert resp1["success"] is True
assert wait_for_condition(
time=timeout_env_open, condition=condition_environment_created
), "Timeout while waiting for environment to be opened"
resp2, _ = zmq_request("queue_start")
assert resp2["success"] is True
ttime.sleep(1)
# Try to insert a plan before the running plan
params = {"item": _plan3, "before_uid": uid, "user": _user, "user_group": _user_group}
resp3, _ = zmq_request("queue_item_add", params)
assert resp3["success"] is False
assert "Can not insert a plan in the queue before a currently running plan" in resp3["msg"]
# Insert the plan after the running plan
params = {"item": _plan3, "after_uid": uid, "user": _user, "user_group": _user_group}
resp4, _ = zmq_request("queue_item_add", params)
assert resp4["success"] is True
assert wait_for_condition(
time=20, condition=condition_queue_processing_finished
), "Timeout while waiting for environment to be opened"
state = get_manager_status()
assert state["items_in_queue"] == 0
assert state["items_in_history"] == 3
# Close the environment
resp5, _ = zmq_request("environment_close")
assert resp5["success"] is True
assert wait_for_condition(time=5, condition=condition_environment_closed)
# fmt: off
@pytest.mark.parametrize("plan_to_add, ugroup, success_submit, success_run, msg", [
# 'count' plan does not have restrictions on the name of devices, so all
# the following plans can be submitted, but some of them will fail during
# execution.
({"name": "count",
"args": [["sim_bundle_A.dets.det_A", "sim_bundle_B.dets.det_B"]],
"kwargs": {"num": 1, "delay": 1}, "item_type": "plan"},
_user_group, True, True, ""),
({"name": "count",
"kwargs": {"detectors": ["sim_bundle_A.dets.det_A", "sim_bundle_B.dets.det_B"],
"num": 1, "delay": 1}, "item_type": "plan"},
_user_group, True, True, ""),
({"name": "count",
"args": [["sim_bundle_A.dets", "sim_bundle_A"]],
"kwargs": {"num": 1, "delay": 1}, "item_type": "plan"},
_user_group, True, True, ""),
({"name": "count",
"args": [["sim_bundle_A.dets", "sim_bundle_B"]],
"kwargs": {"num": 1, "delay": 1}, "item_type": "plan"},
_test_user_group, True, False, ""),
({"name": "count",
"args": [["sim_bundle_A.dets", "sim_bundle_B.dets"]],
"kwargs": {"num": 1, "delay": 1}, "item_type": "plan"},
_test_user_group, True, False, ""),
({"name": "count",
"args": [["sim_bundle_A.dets", "sim_bundle_B.dets.det_A"]],
"kwargs": {"num": 1, "delay": 1}, "item_type": "plan"},
_test_user_group, True, False, ""),
# Specially designed test plan with defined set of items. Plan validation
# fails at submission if a parameter is not in the list
({"name": "count_bundle_test",
"args": [["sim_bundle_A.dets.det_A", "sim_bundle_B.dets.det_B"]],
"kwargs": {"num": 1, "delay": 1}, "item_type": "plan"},
_user_group, True, True, ""),
({"name": "count_bundle_test",
"kwargs": {"detectors": ["sim_bundle_A.dets.det_A", "sim_bundle_B"],
"num": 1, "delay": 1}, "item_type": "plan"},
_user_group, True, True, ""),
({"name": "count_bundle_test",
"args": [["sim_bundle_A.dets.det_A", "sim_bundle_A.dets.det_B"]],
"kwargs": {"num": 1, "delay": 1}, "item_type": "plan"},
_test_user_group, True, True, ""),
({"name": "count_bundle_test",
"args": [["sim_bundle_A.dets.det_A", "sim_bundle_B.dets.det_B"]],
"kwargs": {"num": 1, "delay": 1}, "item_type": "plan"},
_test_user_group, False, False, "Failed to add an item: Plan validation failed"),
({"name": "count_bundle_test",
"kwargs": {"detectors": ["sim_bundle_A.dets.det_A", "sim_bundle_B.dets.det_B"],
"num": 1, "delay": 1}, "item_type": "plan"},
_test_user_group, False, False, "Failed to add an item: Plan validation failed"),
({"name": "count_bundle_test",
"args": [["sim_bundle_A.dets.det_A", "sim_bundle_B"]],
"kwargs": {"num": 1, "delay": 1}, "item_type": "plan"},
_test_user_group, False, False, "Failed to add an item: Plan validation failed"),
])
# fmt: on
def test_zmq_api_queue_item_add_05(re_manager, plan_to_add, ugroup, success_submit, success_run, msg): # noqa F811
"""
Check if subdevice names could be passed to plans
"""
params = {"item": plan_to_add, "user": _user, "user_group": ugroup}
resp0a, _ = zmq_request("queue_item_add", params)
assert resp0a["success"] is success_submit
response_msg = resp0a["msg"]
state = get_manager_status()
assert state["items_in_queue"] == (1 if success_submit else 0)
assert state["items_in_history"] == 0
if not success_submit:
assert msg in response_msg, pprint.pformat(resp0a)
else:
# Now execute the plan
resp1, _ = zmq_request("environment_open")
assert resp1["success"] is True
assert wait_for_condition(
time=timeout_env_open, condition=condition_environment_created
), "Timeout while waiting for environment to be opened"
resp2, _ = zmq_request("queue_start")
assert resp2["success"] is True
assert wait_for_condition(time=10, condition=condition_manager_idle)
state = get_manager_status()
assert state["items_in_queue"] == (0 if success_run else 1)
assert state["items_in_history"] == 1
# Close the environment
resp5, _ = zmq_request("environment_close")
assert resp5["success"] is True
assert wait_for_condition(time=5, condition=condition_environment_closed)
_script_queue_item_add_06_a = """
def unannotated_plan(p):
# This plan always fails. Error message should return printed object that was passed
# to the plan for execution.
yield from bps.sleep(0.01)
raise Exception(f"Passed object: {p!r} Type={type(p)}")
"""
# fmt: off
@pytest.mark.parametrize("value, err_msg", [
("abc", "'abc' Type=<class 'str'>"),
("a", "'a' Type=<class 'str'>"),
("a-b-c", "'a-b-c' Type=<class 'str'>"),
(":^a.*", "':^a.*' Type=<class 'str'>"),
(50, "50 Type=<class 'int'>"), # An integer
("det", "Type=<class 'ophyd.sim.SynGauss'>"), # Existing detector
("motor", "Type=<class 'ophyd.sim.SynAxis'>"), # Existing motor
("count", "Type=<class 'function'>"), # Existing motor
])
# fmt: on
def test_zmq_api_queue_item_add_06(re_manager, value, err_msg): # noqa: F811
"""
Check that arbitrary strings may be passed as unannotated parameter. The existing plans
and devices are converted to objects
"""
# Open the environment
resp1, _ = zmq_request("environment_open")
assert resp1["success"] is True
assert wait_for_condition(time=timeout_env_open, condition=condition_environment_created)
resp2, _ = zmq_request("script_upload", params={"script": _script_queue_item_add_06_a})
assert resp2["success"] is True
assert wait_for_condition(time=3, condition=condition_manager_idle)
plan_to_add = {"item_type": "plan", "name": "unannotated_plan", "args": [value]}
params = {"item": plan_to_add, "user": _user, "user_group": _user_group}
resp3, _ = zmq_request("queue_item_add", params=params)
assert resp3["success"] is True, resp3
state = get_manager_status()
assert state["items_in_queue"] == 1
assert state["items_in_history"] == 0
resp4, _ = zmq_request("queue_start")
assert resp4["success"] is True
assert wait_for_condition(time=10, condition=condition_manager_idle)
state = get_manager_status()
assert state["items_in_queue"] == 1
assert state["items_in_history"] == 1
resp5, _ = zmq_request("history_get")
history = resp5["items"]
last_plan = history[-1]
assert last_plan["result"]["exit_status"] == "failed", pprint.pformat(last_plan)
assert err_msg in last_plan["result"]["msg"], pprint.pformat(last_plan)
# Close the environment
resp5, _ = zmq_request("environment_close")
assert resp5["success"] is True
assert wait_for_condition(time=5, condition=condition_environment_closed)
def test_zmq_api_queue_item_add_07(re_manager): # noqa: F811
"""
Make sure that the new plan UID is generated when the plan is added
"""
plan1 = {"name": "count", "args": [["det1", "det2"]], "item_type": "plan"}
# Set plan UID. This UID is expected to be replaced when the plan is added
plan1["item_uid"] = PlanQueueOperations.new_item_uid()
params1 = {"item": plan1, "user": _user, "user_group": _user_group}
resp1, _ = zmq_request("queue_item_add", params1)
assert resp1["success"] is True
assert resp1["msg"] == ""
assert resp1["item"]["item_uid"] != plan1["item_uid"]
def test_zmq_api_queue_item_add_08(re_manager): # noqa: F811
"""
Add instruction ('queue_stop') to the queue.
"""
params1a = {"item": _plan1, "user": _user, "user_group": _user_group}
resp1a, _ = zmq_request("queue_item_add", params1a)
assert resp1a["success"] is True, f"resp={resp1a}"
params1 = {"item": _instruction_stop, "user": _user, "user_group": _user_group}
resp1, _ = zmq_request("queue_item_add", params1)
assert resp1["success"] is True, f"resp={resp1}"
assert resp1["msg"] == ""
assert resp1["item"]["name"] == "queue_stop"
params1c = {"item": _plan2, "user": _user, "user_group": _user_group}
resp1c, _ = zmq_request("queue_item_add", params1c)
assert resp1c["success"] is True, f"resp={resp1c}"
resp2, _ = zmq_request("queue_get")
assert len(resp2["items"]) == 3
assert resp2["items"][0]["item_type"] == "plan"
assert resp2["items"][1]["item_type"] == "instruction"
assert resp2["items"][2]["item_type"] == "plan"
_script_save_start_docs = """
start_docs = []
def unit_test_get_start_docs():
# Call this function to return saved start docs
return start_docs
from bluesky.callbacks.core import CallbackBase
class CallbackSaveStartDocs(CallbackBase):
def start(self, doc):
start_docs.append(doc)
cb_save_start_docs = CallbackSaveStartDocs()
RE.subscribe(cb_save_start_docs)
"""
# fmt: off
@pytest.mark.parametrize("meta_param, meta_saved", [
# 'meta' is dictionary, all keys are saved
({"test_key": "test_value"}, {"test_key": "test_value"}),
# 'meta' - array with two elements. Merging dictionaries with distinct keys.
([{"test_key1": 10}, {"test_key2": 20}], {"test_key1": 10, "test_key2": 20}),
# ' meta' - array. Merging dictionaries with identical keys.
([{"test_key": 10}, {"test_key": 20}], {"test_key": 10}),
])
# fmt: on
def test_zmq_api_queue_item_add_09(tmp_path, re_manager_cmd, meta_param, meta_saved): # noqa: F811
"""
Add plan with metadata.
"""
re_manager_cmd()
# Plan
plan = copy.deepcopy(_plan2)
plan["meta"] = meta_param
params1 = {"item": plan, "user": _user, "user_group": _user_group}
resp1, _ = zmq_request("queue_item_add", params1)
assert resp1["success"] is True, f"resp={resp1}"
resp2, _ = zmq_request("status")
assert resp2["items_in_queue"] == 1
assert resp2["items_in_history"] == 0
# Open the environment.
resp3, _ = zmq_request("environment_open")
assert resp3["success"] is True
assert wait_for_condition(time=timeout_env_open, condition=condition_environment_created)
resp, _ = zmq_request("script_upload", params={"script": _script_save_start_docs})
assert resp["success"] is True, pprint.pformat(resp)
assert wait_for_condition(time=3, condition=condition_manager_idle)
resp4, _ = zmq_request("queue_start")
assert resp4["success"] is True
assert wait_for_condition(time=5, condition=condition_manager_idle)
resp5, _ = zmq_request("status")
assert resp5["items_in_queue"] == 0
assert resp5["items_in_history"] == 1
resp6, _ = zmq_request("history_get")
history = resp6["items"]