-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathtest_records.py
More file actions
1644 lines (1213 loc) · 50.2 KB
/
Copy pathtest_records.py
File metadata and controls
1644 lines (1213 loc) · 50.2 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 numpy
import os
import pytest
from enum import Enum
from conftest import (
aioca_cleanup,
log,
create_random_prefix,
requires_cothread,
WAVEFORM_LENGTH,
TIMEOUT,
select_and_recv,
get_multiprocessing_context,
in_records
)
from softioc import alarm, asyncio_dispatcher, builder, softioc
from softioc.builder import ClearRecords
from softioc.device import SetBlocking
from softioc.device_core import LookupRecord, LookupRecordList
# Test file for miscellaneous tests related to records
# Test parameters
DEVICE_NAME = "RECORD-TESTS"
def test_records(tmp_path):
# Ensure we definitely unload all records that may be hanging over from
# previous tests, then create exactly one instance of expected records.
from sim_records import create_records
ClearRecords()
create_records()
path = str(tmp_path / "records.db")
builder.WriteRecords(path)
expected = os.path.join(os.path.dirname(__file__), "expected_records.db")
assert open(path).readlines()[5:] == open(expected).readlines()
def test_enum_length_restriction():
with pytest.raises(AssertionError):
builder.mbbIn(
"ManyLabels",
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine",
"ten",
"eleven",
"twelve",
"thirteen",
"fourteen",
"fifteen",
"sixteen",
"seventeen",
)
@pytest.mark.parametrize("creation_func", in_records)
def test_DISP_defaults_on(creation_func):
"""Test that all IN record types have DISP=1 set by default"""
kwargs = {}
if creation_func == builder.WaveformIn:
kwargs = {"length": 1}
record = creation_func("RECORD", **kwargs)
# Note: DISP attribute won't exist if field not specified
assert record.DISP.Value() == 1
def test_DISP_can_be_overridden():
"""Test that DISP can be forced off for In records"""
record = builder.longIn("DISP-OFF", DISP=0)
# Note: DISP attribute won't exist if field not specified
assert record.DISP.Value() == 0
def test_waveform_construction():
"""Test the various ways to construct a Waveform records all produce
correct results"""
wi = builder.WaveformIn("WI1", [1, 2, 3])
assert wi.NELM.Value() == 3
wi = builder.WaveformIn("WI2", initial_value=[1, 2, 3, 4])
assert wi.NELM.Value() == 4
wi = builder.WaveformIn("WI3", length=5)
assert wi.NELM.Value() == 5
wi = builder.WaveformIn("WI4", NELM=6)
assert wi.NELM.Value() == 6
wi = builder.WaveformIn("WI5", [1, 2, 3], length=7)
assert wi.NELM.Value() == 7
wi = builder.WaveformIn("WI6", initial_value=[1, 2, 3], length=8)
assert wi.NELM.Value() == 8
wi = builder.WaveformIn("WI7", [1, 2, 3], NELM=9)
assert wi.NELM.Value() == 9
wi = builder.WaveformIn("WI8", initial_value=[1, 2, 3], NELM=10)
assert wi.NELM.Value() == 10
# Specifying neither value nor length should produce an error
with pytest.raises(AssertionError):
builder.WaveformIn("WI9")
# Specifying both value and initial_value should produce an error
with pytest.raises(AssertionError):
builder.WaveformIn("WI10", [1, 2, 4], initial_value=[5, 6])
# Specifying both length and NELM should produce an error
with pytest.raises(AssertionError):
builder.WaveformIn("WI11", length=11, NELM=12)
def test_drvhl_hlopr_defaults():
"""Test the DRVH/L and H/LOPR default settings"""
# DRVH/L doesn't exist on In records
ai = builder.aIn("FOO")
# KeyError as fields with no value are simply not present in
# epicsdbbuilder's dictionary of fields
with pytest.raises(KeyError):
assert ai.LOPR.Value() is None
with pytest.raises(KeyError):
assert ai.HOPR.Value() is None
ao = builder.aOut("BAR")
with pytest.raises(KeyError):
assert ao.LOPR.Value() is None
with pytest.raises(KeyError):
assert ao.HOPR.Value() is None
with pytest.raises(KeyError):
assert ao.DRVH.Value() is None
with pytest.raises(KeyError):
assert ao.DRVL.Value() is None
def test_hlopr_inherits_drvhl():
"""Test that H/LOPR values are set to the DRVH/L values"""
lo = builder.longOut("ABC", DRVH=5, DRVL=10)
assert lo.DRVH.Value() == 5
assert lo.HOPR.Value() == 5
assert lo.DRVL.Value() == 10
assert lo.LOPR.Value() == 10
def test_hlopr_dvrhl_different_values():
"""Test you can set H/LOPR and DRVH/L to different values"""
ao = builder.aOut("DEF", DRVL=1, LOPR=2, HOPR=3, DRVH=4)
assert ao.DRVL.Value() == 1
assert ao.LOPR.Value() == 2
assert ao.HOPR.Value() == 3
assert ao.DRVH.Value() == 4
def test_pini_always_on():
"""Test that PINI is always on for in records regardless of initial_value"""
bi = builder.boolIn("AAA")
assert bi.PINI.Value() == "YES"
mbbi = builder.mbbIn("BBB", initial_value=5)
assert mbbi.PINI.Value() == "YES"
@pytest.mark.parametrize("creation_func", in_records)
def test_setting_alarm_in_records(creation_func):
"""Test that In records can have a custom alarm value set using the "status"
and "severity" keywords"""
kwargs = {}
if creation_func == builder.WaveformIn:
kwargs["length"] = 1
record = creation_func(
"NEW_RECORD",
severity=alarm.MINOR_ALARM,
status=alarm.LOLO_ALARM,
**kwargs
)
assert record.STAT.Value() == "LOLO"
assert record.SEVR.Value() == "MINOR"
@pytest.mark.parametrize("creation_func", in_records)
def test_setting_alarm_invalid_keywords(creation_func):
"""Test that In records correctly block specifying both STAT and status,
and SEVR and severity"""
kwargs = {}
if creation_func == builder.WaveformIn:
kwargs["length"] = 1
with pytest.raises(AssertionError) as e:
creation_func(
"NEW_RECORD",
severity=alarm.MINOR_ALARM,
SEVR="MINOR",
status=alarm.LOLO_ALARM,
**kwargs
)
assert e.value.args[0] == 'Can\'t specify both severity and SEVR'
with pytest.raises(AssertionError) as e:
creation_func(
"NEW_RECORD",
severity=alarm.MINOR_ALARM,
status=alarm.LOLO_ALARM,
STAT="LOLO",
**kwargs
)
assert e.value.args[0] == 'Can\'t specify both status and STAT'
def test_clear_records():
"""Test that clearing the known records allows creation of a record of the
same name afterwards"""
device_name = create_random_prefix()
builder.SetDeviceName(device_name)
record_name = "NEW-RECORD"
builder.aOut(record_name)
# First check that we cannot create two of the same name
with pytest.raises(AssertionError):
builder.aOut(record_name)
builder.ClearRecords()
# Then confirm we can create one of this name
builder.aOut(record_name)
# Finally prove that the underlying record holder contains only one record
# Records are stored as full device:record name
full_name = device_name + ":" + record_name
assert LookupRecord(full_name)
assert len(LookupRecordList()) == 1
for key, val in LookupRecordList():
assert key == full_name
def clear_records_runner(child_conn):
"""Tests ClearRecords after loading the database"""
builder.aOut("Some-Record")
builder.LoadDatabase()
try:
builder.ClearRecords()
except AssertionError:
# Expected error
child_conn.send("D") # "Done"
child_conn.send("F") # "Fail"
def test_clear_records_too_late():
"""Test that calling ClearRecords after a database has been loaded raises
an exception"""
ctx = get_multiprocessing_context()
parent_conn, child_conn = ctx.Pipe()
process = ctx.Process(
target=clear_records_runner,
args=(child_conn,),
)
process.start()
try:
select_and_recv(parent_conn, "D")
finally:
process.join(timeout=TIMEOUT)
if process.exitcode is None:
pytest.fail("Process did not terminate")
def str_ioc_test_func(device_name, conn):
builder.SetDeviceName(device_name)
record_name = "MyAI"
full_name = device_name + ":" + record_name
ai = builder.aIn(record_name)
log("CHILD: Created ai record: ", ai.__str__())
assert (
ai.__str__() == full_name
), f"Record name {ai.__str__()} before LoadDatabase did not match " \
f"expected string {full_name}"
builder.LoadDatabase()
assert (
ai.__str__() == full_name
), f"Record name {ai.__str__()} after LoadDatabase did not match " \
f"expected string {full_name}"
dispatcher = asyncio_dispatcher.AsyncioDispatcher()
softioc.iocInit(dispatcher)
assert (
ai.__str__() == full_name
), f"Record name {ai.__str__()} after iocInit did not match expected " \
f"string {full_name}"
conn.send("R") # "Ready"
log("CHILD: Sent R over Connection to Parent")
def test_record_wrapper_str():
"""Test that the __str__ method on the RecordWrapper behaves as expected,
both before and after loading the record database"""
ctx = get_multiprocessing_context()
parent_conn, child_conn = ctx.Pipe()
device_name = create_random_prefix()
ioc_process = ctx.Process(
target=str_ioc_test_func,
args=(device_name, child_conn),
)
ioc_process.start()
# Wait for message that IOC has started
# If we never receive R it probably means an assert failed
select_and_recv(parent_conn, "R")
def test_waveform_values_not_modifiable():
"""Test that arrays returned from waveform records are not modifiable"""
wi = builder.WaveformIn("WI", [1, 2, 3])
wo = builder.WaveformOut("WO", [1, 2, 3])
with pytest.raises(ValueError):
wi.get()[0] = 5
with pytest.raises(ValueError):
wo.get()[0] = 5
def validate_fixture_names(params):
"""Provide nice names for the out_records fixture in TestValidate class"""
return params[0].__name__
class TestValidate:
"""Tests related to the validate callback"""
@pytest.fixture(
params=[
(builder.aOut, 7.89, 0),
(builder.boolOut, 1, 0),
(builder.Action, 1, 0),
(builder.longOut, 7, 0),
(builder.int64Out, 54, 0),
(builder.stringOut, "HI", ""),
(builder.mbbOut, 2, 0),
(builder.WaveformOut, [10, 11, 12], []),
(builder.longStringOut, "A LONGER HELLO", ""),
],
ids=validate_fixture_names
)
def out_records(self, request):
"""The list of Out records and an associated value to set """
return request.param
def validate_always_pass(self, record, new_val):
"""Validation method that always allows changes"""
log("VALIDATE: Returning True")
return True
def validate_always_fail(self, record, new_val):
"""Validation method that always rejects changes"""
log("VALIDATE: Returning False")
return False
def validate_ioc_test_func(
self,
device_name,
record_func,
child_conn,
validate_pass: bool):
"""Start the IOC with the specified validate method"""
builder.SetDeviceName(device_name)
kwarg = {}
if record_func in [builder.WaveformIn, builder.WaveformOut]:
kwarg = {"length": WAVEFORM_LENGTH} # Must specify when no value
kwarg["validate"] = (
self.validate_always_pass
if validate_pass
else self.validate_always_fail
)
record_func("VALIDATE-RECORD", **kwarg)
dispatcher = asyncio_dispatcher.AsyncioDispatcher()
builder.LoadDatabase()
softioc.iocInit(dispatcher)
child_conn.send("R")
# Keep process alive while main thread runs CAGET
if child_conn.poll(TIMEOUT):
val = child_conn.recv()
assert val == "D", "Did not receive expected Done character"
def validate_test_runner(
self,
creation_func,
new_value,
expected_value,
validate_pass: bool):
ctx = get_multiprocessing_context()
parent_conn, child_conn = ctx.Pipe()
device_name = create_random_prefix()
process = ctx.Process(
target=self.validate_ioc_test_func,
args=(device_name, creation_func, child_conn, validate_pass),
)
process.start()
from cothread.catools import caget, caput, _channel_cache
try:
# Wait for message that IOC has started
select_and_recv(parent_conn, "R")
# Suppress potential spurious warnings
_channel_cache.purge()
kwargs = {}
if creation_func in [builder.longStringIn, builder.longStringOut]:
from cothread.dbr import DBR_CHAR_STR
kwargs.update({"datatype": DBR_CHAR_STR})
put_ret = caput(
device_name + ":VALIDATE-RECORD",
new_value,
wait=True,
**kwargs,
)
assert put_ret.ok, "caput did not succeed"
ret_val = caget(
device_name + ":VALIDATE-RECORD",
timeout=TIMEOUT,
**kwargs
)
if creation_func in [builder.WaveformOut, builder.WaveformIn]:
assert numpy.array_equal(ret_val, expected_value)
else:
assert ret_val == expected_value
finally:
# Suppress potential spurious warnings
_channel_cache.purge()
parent_conn.send("D") # "Done"
process.join(timeout=TIMEOUT)
@requires_cothread
def test_validate_allows_updates(self, out_records):
"""Test that record values are updated correctly when validate
method allows it """
creation_func, value, _ = out_records
self.validate_test_runner(creation_func, value, value, True)
@requires_cothread
def test_validate_blocks_updates(self, out_records):
"""Test that record values are not updated when validate method
always blocks updates"""
creation_func, value, default = out_records
self.validate_test_runner(creation_func, value, default, False)
class TestOnUpdate:
"""Tests related to the on_update callback, with and without
always_update set"""
@pytest.fixture(
params=[
builder.aOut,
builder.boolOut,
# builder.Action, This is just boolOut + always_update
builder.longOut,
builder.int64Out,
builder.stringOut,
builder.mbbOut,
builder.WaveformOut,
builder.longStringOut,
]
)
def out_records(self, request):
"""The list of Out records to test """
return request.param
def on_update_test_func(
self, device_name, record_func, conn, always_update
):
log("CHILD: Child started")
builder.SetDeviceName(device_name)
li = builder.longIn("ON-UPDATE-COUNTER-RECORD", initial_value=0)
def on_update_func(new_val):
"""Increments li record each time main out record receives caput"""
li.set(li.get() + 1)
kwarg = {}
if record_func is builder.WaveformOut:
kwarg = {"length": WAVEFORM_LENGTH} # Must specify when no value
record_func(
"ON-UPDATE-RECORD",
on_update=on_update_func,
always_update=always_update,
**kwarg)
def on_update_done(_):
conn.send("C") # "Complete"
# Put to the action record after we've done all other Puts, so we know
# all the callbacks have finished processing
builder.Action("ON-UPDATE-DONE", on_update=on_update_done)
dispatcher = asyncio_dispatcher.AsyncioDispatcher()
builder.LoadDatabase()
softioc.iocInit(dispatcher)
conn.send("R") # "Ready"
log("CHILD: Sent R over Connection to Parent")
# Keep process alive while main thread runs CAGET
if conn.poll(TIMEOUT):
val = conn.recv()
assert val == "D", "Did not receive expected Done character"
log("CHILD: Received exit command, child exiting")
def on_update_runner(self, creation_func, always_update, put_same_value):
ctx = get_multiprocessing_context()
parent_conn, child_conn = ctx.Pipe()
device_name = create_random_prefix()
process = ctx.Process(
target=self.on_update_test_func,
args=(device_name, creation_func, child_conn, always_update),
)
process.start()
log("PARENT: Child started, waiting for R command")
from cothread.catools import caget, caput, _channel_cache
try:
# Wait for message that IOC has started
select_and_recv(parent_conn, "R")
log("PARENT: received R command")
# Suppress potential spurious warnings
_channel_cache.purge()
# Use this number to put to records - don't start at 0 as many
# record types default to 0 and we usually want to put a different
# value to force processing to occur
count = 1
log("PARENT: begining While loop")
while count < 4:
put_ret = caput(
device_name + ":ON-UPDATE-RECORD",
9 if put_same_value else count,
wait=True,
)
assert put_ret.ok, f"caput did not succeed: {put_ret.errorcode}"
log(f"PARENT: completed caput with count {count}")
count += 1
log("PARENT: Put'ing to DONE record")
caput(
device_name + ":ON-UPDATE-DONE",
1,
wait=True,
)
log("PARENT: Waiting for C command")
# Wait for action record to process, so we know all the callbacks
# have finished processing (This assumes record callbacks are not
# re-ordered, and will run in the same order as the caputs we sent)
select_and_recv(parent_conn, "C")
log("PARENT: Received C command")
ret_val = caget(
device_name + ":ON-UPDATE-COUNTER-RECORD",
timeout=TIMEOUT,
)
assert ret_val.ok, \
f"caget did not succeed: {ret_val.errorcode}, {ret_val}"
log(f"PARENT: Received val from COUNTER: {ret_val}")
# Expected value is either 3 (incremented once per caput)
# or 1 (incremented on first caput and not subsequent ones)
expected_val = 3
if put_same_value and not always_update:
expected_val = 1
assert ret_val == expected_val
finally:
# Suppress potential spurious warnings
_channel_cache.purge()
log("PARENT:Sending Done command to child")
parent_conn.send("D") # "Done"
process.join(timeout=TIMEOUT)
log(f"PARENT: Join completed with exitcode {process.exitcode}")
if process.exitcode is None:
pytest.fail("Process did not terminate")
@requires_cothread
def test_on_update_false_false(self, out_records):
"""Test that on_update works correctly for all out records when
always_update is False and the put'ed value is always different"""
self.on_update_runner(out_records, False, False)
@requires_cothread
def test_on_update_false_true(self, out_records):
"""Test that on_update works correctly for all out records when
always_update is False and the put'ed value is always the same"""
self.on_update_runner(out_records, False, True)
@requires_cothread
def test_on_update_true_true(self, out_records):
"""Test that on_update works correctly for all out records when
always_update is True and the put'ed value is always the same"""
self.on_update_runner(out_records, True, True)
@requires_cothread
def test_on_update_true_false(self, out_records):
"""Test that on_update works correctly for all out records when
always_update is True and the put'ed value is always different"""
self.on_update_runner(out_records, True, False)
def on_update_recursive_set_test_func(
self, device_name, conn
):
log("CHILD: Child started")
builder.SetDeviceName(device_name)
async def on_update_func(new_val):
log("CHILD: on_update_func started")
record.set(0, process=False)
conn.send("C") # "Callback"
log("CHILD: on_update_func ended")
record = builder.Action(
"ACTION",
on_update=on_update_func,
blocking=True,
initial_value=1 # A non-zero value, to check it changes
)
dispatcher = asyncio_dispatcher.AsyncioDispatcher()
builder.LoadDatabase()
softioc.iocInit(dispatcher)
conn.send("R") # "Ready"
log("CHILD: Sent R over Connection to Parent")
# Keep process alive while main thread runs CAGET
if conn.poll(TIMEOUT):
val = conn.recv()
assert val == "D", "Did not receive expected Done character"
log("CHILD: Received exit command, child exiting")
async def test_on_update_recursive_set(self):
"""Test that on_update functions correctly when the on_update
callback sets the value of the record again (with process=False).
See issue #201"""
ctx = get_multiprocessing_context()
parent_conn, child_conn = ctx.Pipe()
device_name = create_random_prefix()
process = ctx.Process(
target=self.on_update_recursive_set_test_func,
args=(device_name, child_conn),
)
process.start()
log("PARENT: Child started, waiting for R command")
from aioca import caget, caput
try:
# Wait for message that IOC has started
select_and_recv(parent_conn, "R")
log("PARENT: received R command")
record = f"{device_name}:ACTION"
val = await caget(record)
assert val == 1, "ACTION record did not start with value 1"
await caput(record, 1, wait=True)
val = await caget(record)
assert val == 0, "ACTION record did not return to zero value"
# Expect one "C"
select_and_recv(parent_conn, "C")
# ...But if we receive another we know there's a problem
if parent_conn.poll(5): # Shorter timeout to make this quicker
pytest.fail("Received unexpected second message")
finally:
log("PARENT:Sending Done command to child")
parent_conn.send("D") # "Done"
process.join(timeout=TIMEOUT)
log(f"PARENT: Join completed with exitcode {process.exitcode}")
if process.exitcode is None:
pytest.fail("Process did not terminate")
class TestBlocking:
"""Tests related to the Blocking functionality"""
def check_record_blocking_attributes(self, record):
"""Helper function to assert expected attributes exist for a blocking
record"""
assert record._blocking is True
assert record._callback != 0
def test_blocking_creates_attributes(self):
"""Test that setting the blocking flag on record creation creates the
expected attributes"""
ao1 = builder.aOut("OUTREC1", blocking=True)
self.check_record_blocking_attributes(ao1)
ao2 = builder.aOut("OUTREC2", blocking=False)
assert ao2._blocking is False
def test_blocking_global_flag_creates_attributes(self):
"""Test that the global blocking flag creates the expected attributes"""
SetBlocking(True)
bo1 = builder.boolOut("OUTREC1")
self.check_record_blocking_attributes(bo1)
SetBlocking(False)
bo2 = builder.boolOut("OUTREC2")
assert bo2._blocking is False
bo3 = builder.boolOut("OUTREC3", blocking=True)
self.check_record_blocking_attributes(bo3)
def test_blocking_returns_old_state(self):
"""Test that SetBlocking returns the previously set value"""
old_val = SetBlocking(True)
assert old_val is False # Default is False
old_val = SetBlocking(False)
assert old_val is True
# Test it correctly maintains state when passed the current value
old_val = SetBlocking(False)
assert old_val is False
old_val = SetBlocking(False)
assert old_val is False
def blocking_test_func(self, device_name, conn):
builder.SetDeviceName(device_name)
count_rec = builder.longIn("BLOCKING-COUNTER", initial_value=0)
async def blocking_update_func(new_val):
"""A function that will block for some time"""
log("CHILD: blocking_update_func starting")
await asyncio.sleep(0.5)
log("CHILD: Finished sleep!")
completed_count = count_rec.get() + 1
count_rec.set(completed_count)
log(
"CHILD: blocking_update_func finished, completed ",
completed_count
)
builder.longOut(
"BLOCKING-REC",
on_update=blocking_update_func,
always_update=True,
blocking=True
)
dispatcher = asyncio_dispatcher.AsyncioDispatcher()
builder.LoadDatabase()
softioc.iocInit(dispatcher)
conn.send("R") # "Ready"
log("CHILD: Sent R over Connection to Parent")
# Keep process alive while main thread runs CAGET
if conn.poll(TIMEOUT):
val = conn.recv()
assert val == "D", "Did not receive expected Done character"
log("CHILD: Received exit command, child exiting")
@requires_cothread
def test_blocking_single_thread_multiple_calls(self):
"""Test that a blocking record correctly causes multiple caputs from
a single thread to wait for the expected time"""
ctx = get_multiprocessing_context()
parent_conn, child_conn = ctx.Pipe()
device_name = create_random_prefix()
process = ctx.Process(
target=self.blocking_test_func,
args=(device_name, child_conn),
)
process.start()
log("PARENT: Child started, waiting for R command")
from cothread.catools import caget, caput, _channel_cache
try:
# Wait for message that IOC has started
select_and_recv(parent_conn, "R")
log("PARENT: received R command")
# Suppress potential spurious warnings
_channel_cache.purge()
# Track number of puts sent
count = 1
MAX_COUNT = 4
log("PARENT: begining While loop")
while count <= MAX_COUNT:
put_ret = caput(
device_name + ":BLOCKING-REC",
5, # Arbitrary value
wait=True,
timeout=TIMEOUT
)
assert put_ret.ok, f"caput did not succeed: {put_ret.errorcode}"
log(f"PARENT: completed caput with count {count}")
count += 1
log("PARENT: Getting value from counter")
ret_val = caget(
device_name + ":BLOCKING-COUNTER",
timeout=TIMEOUT,
)
assert ret_val.ok, \
f"caget did not succeed: {ret_val.errorcode}, {ret_val}"
log(f"PARENT: Received val from COUNTER: {ret_val}")
assert ret_val == MAX_COUNT
finally:
# Suppress potential spurious warnings
_channel_cache.purge()
log("PARENT: Sending Done command to child")
parent_conn.send("D") # "Done"
process.join(timeout=TIMEOUT)
log(f"PARENT: Join completed with exitcode {process.exitcode}")
if process.exitcode is None:
pytest.fail("Process did not terminate")
@pytest.mark.asyncio
async def test_blocking_multiple_threads(self):
"""Test that a blocking record correctly causes caputs from multiple
threads to wait for the expected time"""
ctx = get_multiprocessing_context()
parent_conn, child_conn = ctx.Pipe()
device_name = create_random_prefix()
process = ctx.Process(
target=self.blocking_test_func,
args=(device_name, child_conn),
)
process.start()
log("PARENT: Child started, waiting for R command")
from aioca import caget, caput
try:
# Wait for message that IOC has started
select_and_recv(parent_conn, "R")
log("PARENT: received R command")
MAX_COUNT = 4
async def query_record(index):
log("SPAWNED: beginning blocking caput ", index)
await caput(
device_name + ":BLOCKING-REC",
5, # Arbitrary value
wait=True,
timeout=TIMEOUT
)
log("SPAWNED: caput complete ", index)
queries = [query_record(i) for i in range(MAX_COUNT)] * MAX_COUNT
log("PARENT: Gathering list of queries")
await asyncio.gather(*queries)
log("PARENT: Getting value from counter")
ret_val = await caget(
device_name + ":BLOCKING-COUNTER",
timeout=TIMEOUT,
)
assert ret_val.ok, \
f"caget did not succeed: {ret_val.errorcode}, {ret_val}"
log(f"PARENT: Received val from COUNTER: {ret_val}")
assert ret_val == MAX_COUNT
finally:
# Clear the cache before stopping the IOC stops
# "channel disconnected" error messages
aioca_cleanup()
log("PARENT: Sending Done command to child")
parent_conn.send("D") # "Done"
process.join(timeout=TIMEOUT)