Debian Codegraph @

tests/instruments/test_common_base.py

raw
1 #
2 # This file is part of the PyMeasure package.
3 #
4 # Copyright (c) 2013-2024 PyMeasure Developers
5 #
6 # Permission is hereby granted, free of charge, to any person obtaining a copy
7 # of this software and associated documentation files (the "Software"), to deal
8 # in the Software without restriction, including without limitation the rights
9 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 # copies of the Software, and to permit persons to whom the Software is
11 # furnished to do so, subject to the following conditions:
12 #
13 # The above copyright notice and this permission notice shall be included in
14 # all copies or substantial portions of the Software.
15 #
16 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 # THE SOFTWARE.
23 #
24
25 import logging
26
27 import pytest
28
29 from pymeasure.units import ureg
30 from pymeasure.test import expected_protocol
31 from pymeasure.instruments.common_base import DynamicProperty, CommonBase
32 from pymeasure.adapters import FakeAdapter, ProtocolAdapter
33 from pymeasure.instruments.validators import strict_discrete_set, strict_range, truncated_range
34
35
36 class CommonBaseTesting(CommonBase):
37 """Add read/write methods in order to use the ProtocolAdapter."""
38
39 def __init__(self, parent, id=None, *args, **kwargs):
40 if "test" in kwargs:
41 self.test = kwargs.pop("test")
42 super().__init__(*args, **kwargs)
43 self.parent = parent
44 self.id = id
45 self.args = args
46 self.kwargs = kwargs
47
48 def wait_for(self, query_delay=0):
49 pass
50
51 def write(self, command):
52 self.parent.write(command)
53
54 def read(self):
55 return self.parent.read()
56
57
58 class GenericBase(CommonBaseTesting):
59 # Use truncated_range as this easily lets us test for the range boundaries
60 fake_ctrl = CommonBase.control(
61 "C{ch}:control?", "C{ch}:control %d", "docs",
62 validator=truncated_range,
63 values=(1, 10),
64 dynamic=True,
65 )
66 fake_setting = CommonBase.setting(
67 "C{ch}:setting %d", "docs",
68 validator=truncated_range,
69 values=(1, 10),
70 dynamic=True,
71 )
72 fake_measurement = CommonBase.measurement(
73 "C{ch}:measurement?", "docs",
74 values={'X': 1, 'Y': 2, 'Z': 3},
75 map_values=True,
76 dynamic=True,
77 )
78 special_control = CommonBase.control(
79 "SOUR{ch}:special?", "OUTP{ch}:special %s",
80 """A special control with different channel specifiers for get and set.""",
81 cast=str,
82 )
83
84
85 @pytest.fixture()
86 def generic():
87 return GenericBase()
88
89
90 class FakeBase(CommonBaseTesting):
91 def __init__(self, *args, **kwargs):
92 super().__init__(FakeAdapter(), *args, **kwargs)
93
94 fake_ctrl = CommonBase.control(
95 "", "%d", "docs",
96 validator=truncated_range,
97 values=(1, 10),
98 dynamic=True,
99 )
100 fake_setting = CommonBase.setting(
101 "%d", "docs",
102 validator=truncated_range,
103 values=(1, 10),
104 dynamic=True,
105 )
106 fake_measurement = CommonBase.measurement(
107 "", "docs",
108 values={'X': 1, 'Y': 2, 'Z': 3},
109 map_values=True,
110 dynamic=True,
111 )
112 fake_ctrl_errors = CommonBase.control(
113 "ge", "se %d", "Fake control for getting errors after getting/setting values.",
114 validator=truncated_range,
115 values=(1, 10),
116 dynamic=True,
117 check_get_errors=True,
118 check_set_errors=True
119 )
120
121
122 @pytest.fixture()
123 def fake():
124 return FakeBase()
125
126
127 class ExtendedBase(FakeBase):
128 # Keep values unchanged, just derive another instrument, e.g. to add more properties
129 fake_ctrl2 = CommonBase.control(
130 "", "%d", "docs",
131 validator=strict_range,
132 values=(1, 10),
133 dynamic=True,
134 )
135
136 fake_ctrl2_values = (5, 20)
137
138
139 class StrictExtendedBase(ExtendedBase):
140 # Use strict instead of truncated range validator
141 fake_ctrl_validator = strict_range
142 fake_setting_validator = strict_range
143
144
145 class NewRangeBase(FakeBase):
146 # Choose different properties' values, like you would for another device model
147 fake_ctrl_values = (10, 20)
148 fake_setting_values = (10, 20)
149 fake_measurement_values = {'X': 4, 'Y': 5, 'Z': 6}
150
151
152 class Child(CommonBase):
153 """A child, which accepts parent and id arguments."""
154
155 def __init__(self, parent, id=None, *args, **kwargs):
156 super().__init__()
157
158
159 class MultiChannelParent(CommonBaseTesting):
160 """A Base as a parent"""
161 channels = CommonBase.MultiChannelCreator(GenericBase, ("A", "B", "C"))
162 analog = CommonBase.MultiChannelCreator(GenericBase, [1, 2], prefix="an_", test=True)
163
164
165 class SingleChannelParent(CommonBaseTesting):
166 """A Base as a parent"""
167 ch_A = CommonBase.ChannelCreator(GenericBase, "A")
168 ch_B = CommonBase.ChannelCreator(GenericBase, "B")
169 ch_C = CommonBase.ChannelCreator(GenericBase, "C")
170 an_1 = CommonBase.ChannelCreator(GenericBase, 1, collection="analog", test=True)
171 an_2 = CommonBase.ChannelCreator(GenericBase, 2, collection="analog", test=True)
172 function = CommonBase.ChannelCreator(Child)
173
174
175 class MixChannelParent(CommonBaseTesting):
176 """A Base as a parent"""
177 channels = CommonBase.MultiChannelCreator(GenericBase, ("A", "B", "C"))
178 ch_D = CommonBase.ChannelCreator(GenericBase, "D")
179 output_Z = CommonBase.ChannelCreator(GenericBase, "Z")
180 analog = CommonBase.MultiChannelCreator(GenericBase, list(range(0, 10)), prefix="an_",
181 test=True)
182
183
184 # Test dynamic properties
185 def test_dynamic_property_fget_unset():
186 d = DynamicProperty()
187 with pytest.raises(AttributeError, match="Unreadable attribute"):
188 d.__get__(5)
189
190
191 def test_dynamic_property_fset_unset():
192 d = DynamicProperty()
193 with pytest.raises(AttributeError, match="set attribute"):
194 d.__set__(5, 7)
195
196
197 # Test CommonBase.MultipleChannelCreator child management
198 class TestInitWithMultipleChannelCreator:
199 @pytest.fixture()
200 def parent(self):
201 return MultiChannelParent(ProtocolAdapter())
202
203 def test_channels(self, parent):
204 assert len(parent.channels) == 3
205 assert parent.ch_A == parent.channels['A']
206 assert isinstance(parent.ch_A, GenericBase)
207
208 def test_analog(self, parent):
209 assert len(parent.analog) == 2
210 assert parent.an_1 == parent.analog[1]
211 assert isinstance(parent.analog[1], GenericBase)
212
213 def test_removal_of_protected_children_fails(self, parent):
214 with pytest.raises(TypeError, match="cannot remove channels defined at class"):
215 parent.remove_child(parent.ch_A)
216
217 def test_channel_creation_works_more_than_once(self):
218 """A zipper object works just once, ensure that a class may be used more often."""
219 p1 = MultiChannelParent(ProtocolAdapter()) # first instance of that class
220 assert isinstance(p1.analog[1], GenericBase) # verify that it worked once
221 p2 = MultiChannelParent(ProtocolAdapter()) # second instance of that class
222 assert isinstance(p2.analog[1], GenericBase) # verify that it worked a second time
223
224 def test_channel_pairs_length(self, parent):
225 assert len(parent.get_channel_pairs(parent.__class__)) == 5
226
227 def test_channel_creator_remains_unchanged_as_class_attribute(self, parent):
228 assert isinstance(parent.__class__.channels, CommonBase.MultiChannelCreator)
229
230
231 # Test CommonBase.ChannelCreator child management
232 class TestInitWithChannelCreator:
233 @pytest.fixture()
234 def parent(self):
235 return SingleChannelParent(ProtocolAdapter())
236
237 def test_channels(self, parent):
238 assert len(parent.channels) == 3
239 assert parent.ch_A == parent.channels['A']
240 assert isinstance(parent.ch_A, GenericBase)
241
242 def test_analog(self, parent):
243 assert len(parent.analog) == 2
244 assert parent.an_1 == parent.analog[1]
245 assert isinstance(parent.analog[1], GenericBase)
246
247 def test_function(self, parent):
248 assert isinstance(parent.function, Child)
249
250 def test_removal_of_protected_children_fails(self, parent):
251 with pytest.raises(TypeError, match="cannot remove channels defined at class"):
252 parent.remove_child(parent.ch_A)
253
254 def test_removal_of_protected_single_children_fails(self, parent):
255 with pytest.raises(TypeError, match="cannot remove channels defined at class"):
256 parent.remove_child(parent.function)
257
258 def test_channel_creation_works_more_than_once(self):
259 """A zipper object works just once, ensure that a class may be used more often."""
260 p1 = SingleChannelParent(ProtocolAdapter()) # first instance of that class
261 assert isinstance(p1.analog[1], GenericBase) # verify that it worked once
262 p2 = SingleChannelParent(ProtocolAdapter()) # second instance of that class
263 assert isinstance(p2.analog[1], GenericBase) # verify that it worked a second time
264
265 def test_channel_pairs_length(self, parent):
266 assert len(parent.get_channel_pairs(parent.__class__)) == 6
267
268 def test_channel_creator_remains_unchanged_as_class_attribute(self, parent):
269 assert isinstance(parent.__class__.ch_A, CommonBase.ChannelCreator)
270 assert isinstance(parent.__class__.an_1, CommonBase.ChannelCreator)
271 assert isinstance(parent.__class__.function, CommonBase.ChannelCreator)
272
273
274 # Test combination CommonBase.MultipleChannelCreator and CommonBase.ChannelCreator
275 # child management
276 class TestInitWithMixChannelCreator:
277 @pytest.fixture()
278 def parent(self):
279 return MixChannelParent(ProtocolAdapter())
280
281 def test_channels(self, parent):
282 assert len(parent.channels) == 5
283 assert parent.ch_A == parent.channels['A']
284 assert parent.output_Z == parent.channels['Z']
285 assert isinstance(parent.ch_A, GenericBase)
286 assert isinstance(parent.output_Z, GenericBase)
287
288 def test_analog(self, parent):
289 assert len(parent.analog) == 10
290 assert parent.an_1 == parent.analog[1]
291 assert isinstance(parent.analog[1], GenericBase)
292
293 def test_removal_of_protected_children_fails(self, parent):
294 with pytest.raises(TypeError, match="cannot remove channels defined at class"):
295 parent.remove_child(parent.ch_A)
296
297 def test_channel_creation_works_more_than_once(self):
298 """A zipper object works just once, ensure that a class may be used more often."""
299 p1 = MixChannelParent(ProtocolAdapter()) # first instance of that class
300 assert isinstance(p1.analog[1], GenericBase) # verify that it worked once
301 assert isinstance(p1.output_Z, GenericBase)
302 p2 = MixChannelParent(ProtocolAdapter()) # second instance of that class
303 assert isinstance(p2.analog[1], GenericBase) # verify that it worked a second time
304 assert isinstance(p2.output_Z, GenericBase)
305
306 def test_channel_pairs_length(self, parent):
307 assert len(parent.get_channel_pairs(parent.__class__)) == 15
308
309 def test_channel_creator_remains_unchanged_as_class_attribute(self, parent):
310 assert isinstance(parent.__class__.channels, CommonBase.MultiChannelCreator)
311 assert isinstance(parent.__class__.analog, CommonBase.MultiChannelCreator)
312 assert isinstance(parent.__class__.output_Z, CommonBase.ChannelCreator)
313
314
315 class TestAddChild:
316 """Test the `add_child` method"""
317
318 @pytest.fixture()
319 def parent(self):
320 parent = CommonBaseTesting(ProtocolAdapter())
321 parent.add_child(GenericBase, "A", test=5)
322 parent.add_child(GenericBase, "B")
323 parent.add_child(GenericBase, prefix=None, collection="function")
324 return parent
325
326 def test_correct_class(self, parent):
327 assert isinstance(parent.ch_A, GenericBase)
328
329 def test_arguments(self, parent):
330 assert parent.channels["A"].id == "A"
331 assert parent.channels["A"].test == 5
332
333 def test_attribute_access(self, parent):
334 assert parent.ch_B == parent.channels["B"]
335
336 def test_len(self, parent):
337 assert len(parent.channels) == 2
338
339 def test_attributes(self, parent):
340 assert parent.ch_A._name == "ch_A"
341 assert parent.ch_B._collection == "channels"
342
343 def test_overwriting_list_raises_error(self, parent):
344 """A single channel is only allowed, if there is no list of that name."""
345 with pytest.raises(ValueError, match="already exists"):
346 parent.add_child(GenericBase, prefix=None)
347
348 def test_single_channel(self, parent):
349 """Test, that id=None creates a single channel."""
350 assert isinstance(parent.function, GenericBase)
351 assert parent.function._name == "function"
352
353 def test_evaluating_false_id_creates_channels(self, parent):
354 """Test that an id evaluating false (e.g. 0) creates a channels list."""
355 parent.add_child(GenericBase, 0, collection="special")
356 assert isinstance(parent.special, dict)
357
358
359 class TestRemoveChild:
360 @pytest.fixture()
361 def parent_without_children(self):
362 parent = CommonBaseTesting(ProtocolAdapter())
363 parent.add_child(GenericBase, "A")
364 parent.add_child(GenericBase, "B")
365 parent.add_child(GenericBase, prefix=None, collection="function")
366 parent.remove_child(parent.ch_A)
367 parent.remove_child(parent.channels["B"])
368 parent.remove_child(parent.function)
369 return parent
370
371 def test_remove_child_leaves_channels_empty(self, parent_without_children):
372 assert parent_without_children.channels == {}
373
374 def test_remove_child_clears_attributes(self, parent_without_children):
375 assert getattr(parent_without_children, "ch_A", None) is None
376 assert getattr(parent_without_children, "ch_B", None) is None
377 assert getattr(parent_without_children, "function", None) is None
378
379
380 class TestInheritanceWithChildren:
381 class InstrumentSubclass(MultiChannelParent):
382 """Override one channel group, inherit other groups."""
383 function = CommonBase.ChannelCreator(GenericBase, "overridden", prefix=None)
384
385 @pytest.fixture()
386 def parent(self):
387 return self.InstrumentSubclass(ProtocolAdapter())
388
389 def test_inherited_children_are_present(self, parent):
390 assert isinstance(parent.ch_A, GenericBase)
391
392 def test_ChannelCreator_is_replaced_by_channel_collection(self, parent):
393 assert not isinstance(parent.channels, CommonBase.ChannelCreator)
394
395 def test_overridden_child_is_present(self, parent):
396 assert parent.function.id == "overridden"
397
398
399 # Test MultiChannelCreator
400 @pytest.mark.parametrize("args, pairs, kwargs", (
401 ((Child, ["A", "B"]), [(Child, "A"), (Child, "B")], {'prefix': "ch_"}),
402 (((Child, GenericBase, Child), (1, 2, 3)),
403 [(Child, 1), (GenericBase, 2), (Child, 3)], {'prefix': "ch_"}),
404 ))
405 def test_MultiChannelCreator(args, pairs, kwargs):
406 """Test whether the channel creator receives the right arguments."""
407 d = CommonBase.MultiChannelCreator(*args)
408 i = 0
409 for pair in d.pairs:
410 assert pair == pairs[i]
411 i += 1
412 assert d.kwargs == kwargs
413
414
415 def test_MultiChannelCreator_different_list_lengths():
416 with pytest.raises(AssertionError, match="Lengths"):
417 CommonBase.MultiChannelCreator(("A", "B", "C"), (Child,) * 2)
418
419
420 def test_ChannelCreator_invalid_input():
421 with pytest.raises(ValueError, match="Invalid"):
422 CommonBase.ChannelCreator("A", {})
423
424
425 # Test CommonBase communication
426 def test_ask_writes_and_reads():
427 with expected_protocol(CommonBaseTesting, [("Sent", "Received")]) as inst:
428 assert inst.ask("Sent") == "Received"
429
430
431 @pytest.mark.parametrize("value, kwargs, result",
432 (("5,6,7", {}, [5, 6, 7]),
433 ("5.6.7", {'separator': '.'}, [5, 6, 7]),
434 ("5,6,7", {'cast': str}, ['5', '6', '7']),
435 ("X,Y,Z", {}, ['X', 'Y', 'Z']),
436 ("X,Y,Z", {'cast': str}, ['X', 'Y', 'Z']),
437 ("X.Y.Z", {'separator': '.'}, ['X', 'Y', 'Z']),
438 ("0,5,7.1", {'cast': bool}, [False, True, True]),
439 ("x5x", {'preprocess_reply': lambda v: v.strip("x")}, [5]),
440 ("X,Y,Z", {'maxsplit': 1}, ["X", "Y,Z"]),
441 ("X,Y,Z", {'maxsplit': 0}, ["X,Y,Z"]),
442 ))
443 def test_values(value, kwargs, result):
444 cb = CommonBaseTesting(FakeAdapter(), "test")
445 assert cb.values(value, **kwargs) == result
446
447
448 def test_global_preprocess_reply():
449 with pytest.warns(FutureWarning, match="deprecated"):
450 cb = CommonBaseTesting(FakeAdapter(), preprocess_reply=lambda v: v.strip("x"))
451 assert cb.values("x5x") == [5]
452
453
454 def test_values_global_preprocess_reply():
455 cb = CommonBaseTesting(FakeAdapter())
456 cb.preprocess_reply = lambda v: v.strip("x")
457 assert cb.values("x5x") == [5]
458
459
460 def test_binary_values(fake):
461 fake.read_binary_values = fake.read
462 assert fake.binary_values("123") == "123"
463
464
465 # Test CommonBase property creators
466 @pytest.mark.parametrize("dynamic", [False, True])
467 def test_control_doc(dynamic):
468 doc = """ X property """
469
470 class Fake(CommonBaseTesting):
471 x = CommonBase.control(
472 "", "%d", doc,
473 dynamic=dynamic
474 )
475
476 expected_doc = doc + "(dynamic)" if dynamic else doc
477 assert Fake.x.__doc__ == expected_doc
478
479
480 def test_check_errors_not_implemented(fake):
481 with pytest.raises(NotImplementedError):
482 fake.check_errors()
483
484
485 def test_check_get_errors_not_implemented(fake):
486 with pytest.raises(NotImplementedError):
487 fake.check_get_errors()
488
489
490 def test_control_check_get_errors(fake, caplog):
491 def checking():
492 fake.error = True
493 return [(7, "some error")]
494
495 fake.check_get_errors = checking
496 fake.fake_ctrl_errors
497 assert fake.error is True
498 assert caplog.record_tuples[-1] == (
499 "pymeasure.instruments.common_base",
500 logging.ERROR,
501 "Error received after trying to get a property with the command 'ge': '(7, 'some error')'."
502 )
503
504
505 def test_control_check_get_errors_multiple_errors(fake, caplog):
506 def checking():
507 fake.error = True
508 return [15, (19, "x")]
509
510 fake.check_get_errors = checking
511 fake.fake_ctrl_errors
512 assert caplog.record_tuples[-1] == (
513 "pymeasure.instruments.common_base",
514 logging.ERROR,
515 "Error received after trying to get a property with the command 'ge': '15', '(19, 'x')'." # noqa: E501
516 )
517
518
519 def test_control_check_get_errors_log_exception(fake, caplog):
520 with pytest.raises(NotImplementedError):
521 fake.fake_ctrl_errors
522 assert caplog.record_tuples[-1] == (
523 "pymeasure.instruments.common_base",
524 logging.ERROR,
525 "Exception raised while getting a property with the command 'ge': 'Implement it in a subclass.'." # noqa: E501
526 )
527
528
529 def test_check_set_errors_not_implemented(fake):
530 with pytest.raises(NotImplementedError):
531 fake.check_set_errors()
532
533
534 def test_control_check_set_errors(fake, caplog):
535 def checking():
536 fake.error = True
537 return [(7, "Error!")]
538
539 fake.check_set_errors = checking
540 fake.fake_ctrl_errors = 7
541 assert fake.error is True
542 assert caplog.record_tuples[-1] == (
543 "pymeasure.instruments.common_base",
544 logging.ERROR,
545 "Error received after trying to set a property with the command 'se 7': '(7, 'Error!')'."
546 )
547
548
549 def test_control_check_set_errors_log_exception(fake, caplog):
550 with pytest.raises(NotImplementedError):
551 fake.fake_ctrl_errors = 7
552 assert caplog.record_tuples[-1] == (
553 "pymeasure.instruments.common_base",
554 logging.ERROR,
555 "Exception raised while setting a property with the command 'se 7': 'Implement it in a subclass.'." # noqa: E501
556 )
557
558
559 @pytest.mark.parametrize("dynamic", [False, True])
560 def test_control_validator(dynamic):
561 class Fake(FakeBase):
562 x = CommonBase.control(
563 "", "%d", "",
564 validator=strict_discrete_set,
565 values=range(10),
566 dynamic=dynamic
567 )
568
569 fake = Fake()
570 fake.x = 5
571 assert fake.read() == '5'
572 fake.x = 5
573 assert fake.x == 5
574 with pytest.raises(ValueError):
575 fake.x = 20
576
577
578 @pytest.mark.parametrize("dynamic", [False, True])
579 def test_control_validator_map(dynamic):
580 class Fake(FakeBase):
581 x = CommonBase.control(
582 "", "%d", "",
583 validator=strict_discrete_set,
584 values=[4, 5, 6, 7],
585 map_values=True,
586 dynamic=dynamic
587 )
588
589 fake = Fake()
590 fake.x = 5
591 assert fake.read() == '1'
592 fake.x = 5
593 assert fake.x == 5
594 with pytest.raises(ValueError):
595 fake.x = 20
596
597
598 @pytest.mark.parametrize("dynamic", [False, True])
599 def test_control_dict_map(dynamic):
600 class Fake(FakeBase):
601 x = CommonBase.control(
602 "", "%d", "",
603 validator=strict_discrete_set,
604 values={5: 1, 10: 2, 20: 3},
605 map_values=True,
606 dynamic=dynamic
607 )
608
609 fake = Fake()
610 fake.x = 5
611 assert fake.read() == '1'
612 fake.x = 5
613 assert fake.x == 5
614 fake.x = 20
615 assert fake.read() == '3'
616
617
618 @pytest.mark.parametrize("dynamic", [False, True])
619 def test_control_dict_str_map(dynamic):
620 class Fake(FakeBase):
621 x = CommonBase.control(
622 "", "%d", "",
623 validator=strict_discrete_set,
624 values={'X': 1, 'Y': 2, 'Z': 3},
625 map_values=True,
626 dynamic=dynamic,
627 )
628
629 fake = Fake()
630 fake.x = 'X'
631 assert fake.read() == '1'
632 fake.x = 'Y'
633 assert fake.x == 'Y'
634 fake.x = 'Z'
635 assert fake.read() == '3'
636
637
638 def test_value_not_in_map(fake):
639 fake.parent._buffer = "123"
640 with pytest.raises(KeyError, match="not found in mapped values"):
641 fake.fake_measurement
642
643
644 def test_control_invalid_values_get():
645 class Fake(FakeBase):
646 x = CommonBase.control(
647 "", "%d", "",
648 values=b"abasdfe", map_values=True)
649
650 with pytest.raises(ValueError, match="Values of type"):
651 Fake().x
652
653
654 def test_control_invalid_values_set():
655 class Fake(FakeBase):
656 x = CommonBase.control(
657 "", "%d", "",
658 values=b"abasdfe", map_values=True)
659
660 with pytest.raises(ValueError, match="Values of type"):
661 Fake().x = 7
662
663
664 @pytest.mark.parametrize("dynamic", [False, True])
665 def test_control_process(dynamic):
666 class Fake(FakeBase):
667 x = CommonBase.control(
668 "", "%d", "",
669 validator=strict_range,
670 values=[5e-3, 120e-3],
671 get_process=lambda v: v * 1e-3,
672 set_process=lambda v: v * 1e3,
673 dynamic=dynamic,
674 )
675
676 fake = Fake()
677 fake.x = 10e-3
678 assert fake.read() == '10'
679 fake.x = 30e-3
680 assert fake.x == 30e-3
681
682
683 @pytest.mark.parametrize("dynamic", [False, True])
684 def test_control_get_process(dynamic):
685 class Fake(FakeBase):
686 x = CommonBase.control(
687 "", "JUNK%d", "",
688 validator=strict_range,
689 values=[0, 10],
690 get_process=lambda v: int(v.replace('JUNK', '')),
691 dynamic=dynamic,
692 )
693
694 fake = Fake()
695 fake.x = 5
696 assert fake.read() == 'JUNK5'
697 fake.x = 5
698 assert fake.x == 5
699
700
701 @pytest.mark.parametrize("dynamic", [False, True])
702 def test_control_preprocess_reply_property(dynamic):
703 # test setting preprocess_reply at property-level
704 class Fake(FakeBase):
705 x = CommonBase.control(
706 "", "JUNK%d",
707 "",
708 preprocess_reply=lambda v: v.replace('JUNK', ''),
709 dynamic=dynamic,
710 cast=int,
711 )
712
713 fake = Fake()
714 fake.x = 5
715 assert fake.read() == 'JUNK5'
716 # notice that read returns the full reply since preprocess_reply is only
717 # called inside CommonBase.values()
718 fake.x = 5
719 assert fake.x == 5
720 fake.x = 5
721 assert type(fake.x) == int
722
723
724 def test_control_kwargs_handed_to_values():
725 """Test that kwargs parameters are handed to `values` method."""
726 with pytest.warns(FutureWarning, match="Do not use keyword arguments"):
727 class Fake(FakeBase):
728 x = CommonBase.control(
729 "", "JUNK%d",
730 "",
731 preprocess_reply=lambda v: v.replace('JUNK', ''),
732 cast=int,
733 testing=True,
734 )
735
736 def values(self, cmd, testing=False, **kwargs):
737 self.testing = testing
738 return super().values(cmd, **kwargs)
739
740 fake = Fake()
741 fake.x = 5
742 fake.x
743 assert fake.testing is True
744
745
746 def test_control_warning_at_kwargs():
747 """Test whether a control kwarg raises a warning."""
748 with pytest.warns(FutureWarning, match="Do not use keyword arguments"):
749 class Fake(CommonBase):
750 x = CommonBase.control("", "", "", testing=True)
751
752
753 def test_measurement_warning_at_kwargs():
754 """Test whether a measurement kwarg raises a warning."""
755 with pytest.warns(FutureWarning, match="Do not use keyword arguments"):
756 class Fake2(CommonBase):
757 x2 = CommonBase.measurement("", "", testing=True)
758
759
760 def test_control_parameters_for_values():
761 """Test how to hand a parameter to `values` method."""
762
763 class Fake(FakeBase):
764 x = CommonBase.control(
765 "", "JUNK%d",
766 "",
767 preprocess_reply=lambda v: v.replace('JUNK', ''),
768 cast=int,
769 values_kwargs={'testing': True},
770 )
771
772 def values(self, cmd, testing=False, **kwargs):
773 self.testing = testing
774 return super().values(cmd, **kwargs)
775
776 fake = Fake()
777 fake.x = 5
778 fake.x
779 assert fake.testing is True
780
781
782 def test_measurement_parameters_for_values():
783 """Test how to hand a parameter to `values` method."""
784
785 class Fake(FakeBase):
786 x = CommonBase.measurement(
787 "JUNK%d",
788 "",
789 preprocess_reply=lambda v: v.replace('JUNK', ''),
790 cast=int,
791 values_kwargs={'testing': True},
792 )
793
794 def values(self, cmd, testing=False, **kwargs):
795 self.testing = testing
796 return super().values(cmd, **kwargs)
797
798 fake = Fake()
799 fake.write("5")
800 fake.x
801 assert fake.testing is True
802
803
804 @pytest.mark.parametrize("cast, expected", ((float, 5.5),
805 (ureg.Quantity, ureg.Quantity(5.5)),
806 (str, "5.5"),
807 (lambda v: int(float(v)), 5)
808 ))
809 def test_measurement_cast(cast, expected):
810 class Fake(CommonBaseTesting):
811 x = CommonBase.measurement(
812 "x", "doc", cast=cast)
813
814 with expected_protocol(Fake, [("x", "5.5")]) as instr:
815 assert instr.x == expected
816
817
818 def test_measurement_cast_int():
819 class Fake(CommonBaseTesting):
820 def __init__(self, adapter, **kwargs):
821 super().__init__(adapter, "test", **kwargs)
822
823 x = CommonBase.measurement(
824 "x", "doc", cast=int)
825
826 with expected_protocol(Fake, [("x", "5")]) as instr:
827 y = instr.x
828 assert y == 5
829 assert type(y) is int
830
831
832 def test_measurement_unitful_property():
833 class Fake(CommonBaseTesting):
834 def __init__(self, adapter, **kwargs):
835 super().__init__(adapter, "test", **kwargs)
836
837 x = CommonBase.measurement(
838 "x", "doc", get_process=lambda v: ureg.Quantity(v, ureg.m))
839
840 with expected_protocol(Fake, [("x", "5.5")]) as instr:
841 y = instr.x
842 assert y.m_as(ureg.m) == 5.5
843
844
845 @pytest.mark.parametrize("dynamic", [False, True])
846 def test_measurement_dict_str_map(dynamic):
847 class Fake(FakeBase):
848 x = CommonBase.measurement(
849 "", "",
850 values={'X': 1, 'Y': 2, 'Z': 3},
851 map_values=True,
852 dynamic=dynamic,
853 )
854
855 fake = Fake()
856 fake.write('1')
857 assert fake.x == 'X'
858 fake.write('2')
859 assert fake.x == 'Y'
860 fake.write('3')
861 assert fake.x == 'Z'
862
863
864 def test_measurement_set(fake):
865 with pytest.raises(LookupError, match="Property can not be set."):
866 fake.fake_measurement = 7
867
868
869 def test_setting_get(fake):
870 with pytest.raises(LookupError, match="Property can not be read."):
871 fake.fake_setting
872
873
874 @pytest.mark.parametrize("dynamic", [False, True])
875 def test_setting_process(dynamic):
876 class Fake(FakeBase):
877 x = CommonBase.setting(
878 "OUT %d", "",
879 set_process=lambda v: int(bool(v)),
880 dynamic=dynamic,
881 )
882
883 fake = Fake()
884 fake.x = False
885 assert fake.read() == 'OUT 0'
886 fake.x = 2
887 assert fake.read() == 'OUT 1'
888
889
890 @pytest.mark.parametrize("dynamic", [False, True])
891 def test_control_multivalue(dynamic):
892 class Fake(FakeBase):
893 x = CommonBase.control(
894 "", "%d,%d", "",
895 dynamic=dynamic,
896 )
897
898 fake = Fake()
899 fake.x = (5, 6)
900 assert fake.read() == '5,6'
901
902
903 @pytest.mark.parametrize(
904 'set_command, given, expected, dynamic',
905 [("%d", 5, 5, False),
906 ("%d", 5, 5, True),
907 ("%d, %d", (5, 6), [5, 6], False), # input has to be a tuple, not a list
908 ("%d, %d", (5, 6), [5, 6], True), # input has to be a tuple, not a list
909 ])
910 def test_FakeBase_control(set_command, given, expected, dynamic):
911 """FakeBase's custom simple control needs to process values correctly.
912 """
913
914 class Fake(FakeBase):
915 x = FakeBase.control(
916 "", set_command, "",
917 dynamic=dynamic,
918 )
919
920 fake = Fake()
921 fake.x = given
922 assert fake.x == expected
923
924
925 def test_dynamic_property_unchanged_by_inheritance():
926 generic = FakeBase()
927 extended = ExtendedBase()
928
929 generic.fake_ctrl = 50
930 assert generic.fake_ctrl == 10
931 extended.fake_ctrl = 50
932 assert extended.fake_ctrl == 10
933
934 generic.fake_setting = 50
935 assert generic.read() == '10'
936 extended.fake_setting = 50
937 assert extended.read() == '10'
938
939 generic.write('1')
940 assert generic.fake_measurement == 'X'
941 extended.write('1')
942 assert extended.fake_measurement == 'X'
943
944
945 def test_dynamic_property_strict_raises():
946 # Tests also that dynamic properties can be changed at class level.
947 strict = StrictExtendedBase()
948
949 with pytest.raises(ValueError):
950 strict.fake_ctrl = 50
951 with pytest.raises(ValueError):
952 strict.fake_setting = 50
953
954
955 def test_dynamic_property_values_update_in_subclass():
956 newrange = NewRangeBase()
957
958 newrange.fake_ctrl = 50
959 assert newrange.fake_ctrl == 20
960
961 newrange.fake_setting = 50
962 assert newrange.read() == '20'
963
964 newrange.write('4')
965 assert newrange.fake_measurement == 'X'
966
967
968 def test_dynamic_property_values_update_in_instance(fake):
969 fake.fake_ctrl_values = (0, 33)
970 fake.fake_ctrl = 50
971 assert fake.fake_ctrl == 33
972
973 fake.fake_setting_values = (0, 33)
974 fake.fake_setting = 50
975 assert fake.read() == '33'
976
977 fake.fake_measurement_values = {'X': 7}
978 fake.write('7')
979 assert fake.fake_measurement == 'X'
980
981
982 def test_dynamic_property_values_update_in_one_instance_leaves_other_unchanged():
983 generic1 = FakeBase()
984 generic2 = FakeBase()
985
986 generic1.fake_ctrl_values = (0, 33)
987 generic1.fake_ctrl = 50
988 generic2.fake_ctrl = 50
989 assert generic1.fake_ctrl == 33
990 assert generic2.fake_ctrl == 10
991
992
993 def test_dynamic_property_reading_special_attributes_forbidden(fake):
994 with pytest.raises(AttributeError):
995 fake.fake_ctrl_validator
996
997
998 def test_dynamic_property_with_inheritance():
999 inst = ExtendedBase()
1000 # Test for inherited attribute
1001 with pytest.raises(AttributeError):
1002 inst.fake_ctrl_validator
1003 # Test for new attribute
1004 with pytest.raises(AttributeError):
1005 inst.fake_ctrl2_validator
1006
1007
1008 def test_dynamic_property_values_defined_at_superclass_level():
1009 """Test whether a dynamic property can be changed a superclass level"""
1010 inst = StrictExtendedBase()
1011 # Test whether the change of values from (1, 10) to (5, 20) succeeded:
1012 inst.fake_ctrl2 = 17 # should raise an error if change unsuccessful
1013 with pytest.raises(ValueError):
1014 inst.fake_ctrl2 = 2 # should not raise an error if change unsuccessful