Debian Codegraph @

tests/instruments/test_instrument.py

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
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
26 import time
27 from unittest import mock
28
29 import pytest
30
31 from pymeasure.test import expected_protocol
32 from pymeasure.instruments import Instrument, Channel
33 from pymeasure.adapters import FakeAdapter, ProtocolAdapter
34 from pymeasure.instruments.fakes import FakeInstrument
35 from pymeasure.instruments.validators import truncated_range
36
37
38 class GenericInstrument(FakeInstrument):
39 # Use truncated_range as this easily lets us test for the range boundaries
40 fake_ctrl = Instrument.control(
41 "", "%d", "docs",
42 validator=truncated_range,
43 values=(1, 10),
44 dynamic=True,
45 )
46 fake_setting = Instrument.setting(
47 "%d", "docs",
48 validator=truncated_range,
49 values=(1, 10),
50 dynamic=True,
51 )
52 fake_measurement = Instrument.measurement(
53 "", "docs",
54 values={'X': 1, 'Y': 2, 'Z': 3},
55 map_values=True,
56 dynamic=True,
57 )
58
59
60 @pytest.fixture()
61 def generic():
62 return GenericInstrument()
63
64
65 class GenericChannel(Channel):
66 # Use truncated_range as this easily lets us test for the range boundaries
67 fake_ctrl = Instrument.control(
68 "C{ch}:control?", "C{ch}:control %d", "docs",
69 validator=truncated_range,
70 values=(1, 10),
71 dynamic=True,
72 )
73 fake_setting = Instrument.setting(
74 "C{ch}:setting %d", "docs",
75 validator=truncated_range,
76 values=(1, 10),
77 dynamic=True,
78 )
79 fake_measurement = Instrument.measurement(
80 "C{ch}:measurement?", "docs",
81 values={'X': 1, 'Y': 2, 'Z': 3},
82 map_values=True,
83 dynamic=True,
84 )
85 special_control = Instrument.control(
86 "SOUR{ch}:special?", "OUTP{ch}:special %s",
87 """A special control with different channel specifiers for get and set.""",
88 cast=str,
89 )
90
91
92 class ChannelInstrument(Instrument):
93 def __init__(self, adapter, name="ChannelInstrument", **kwargs):
94 super().__init__(adapter, name, **kwargs)
95 self.add_child(GenericChannel, "A")
96 self.add_child(GenericChannel, "B")
97
98
99 def test_fake_instrument():
100 fake = FakeInstrument()
101 fake.write("Testing")
102 assert fake.read() == "Testing"
103 assert fake.read() == ""
104 assert fake.values("5") == [5]
105
106
107 class Test_includeSCPI_parameter:
108 def test_not_defined_includeSCPI_raises_warning(self):
109 with pytest.warns(FutureWarning) as record:
110 Instrument(name="test", adapter=ProtocolAdapter())
111 msg = str(record[0].message)
112 assert msg == ("It is deprecated to specify `includeSCPI` implicitly, use "
113 "`includeSCPI=False` or inherit the `SCPIMixin` class instead.")
114
115 def test_not_defined_includeSCPI_is_interpreted_as_true(self):
116 inst = Instrument(name="test", adapter=ProtocolAdapter())
117 assert inst.SCPI is True
118
119
120 @pytest.mark.parametrize("adapter", (("COM1", 87, "USB")))
121 def test_init_visa(adapter):
122 Instrument(adapter, "def", visa_library="@sim")
123 pass # Test that no error is raised
124
125
126 @pytest.mark.xfail() # I do not know, when this error is raised
127 def test_init_visa_fail():
128 with pytest.raises(Exception, match="Invalid adapter"):
129 Instrument("abc", "def", visa_library="@xyz")
130
131
132 def test_init_includeSCPI_implicit_warning():
133 with pytest.warns(FutureWarning, match="includeSCPI"):
134 Instrument("COM1", "def", visa_library="@sim")
135
136
137 def test_init_includeSCPI_explicit_warning():
138 with pytest.warns(FutureWarning, match="includeSCPI"):
139 Instrument("COM1", "def", visa_library="@sim", includeSCPI=True)
140
141
142 def test_global_preprocess_reply():
143 with pytest.warns(FutureWarning, match="deprecated"):
144 inst = Instrument(FakeAdapter(), "name", preprocess_reply=lambda v: v.strip("x"))
145 assert inst.values("x5x") == [5]
146
147
148 def test_instrument_in_context():
149 with Instrument("abc", "def", visa_library="@sim") as instr:
150 pass
151 assert instr.isShutdown is True
152
153
154 def test_with_statement():
155 """ Test the with-statement-behaviour of the instruments. """
156 with FakeInstrument() as fake:
157 # Check if fake is an instance of FakeInstrument
158 assert isinstance(fake, FakeInstrument)
159
160 # Check whether the shutdown function is already called
161 assert fake.isShutdown is False
162
163 # Check whether the shutdown function is called upon
164 assert fake.isShutdown is True
165
166
167 class TestInstrumentCommunication:
168 @pytest.fixture()
169 def instr(self):
170 a = mock.MagicMock(return_value="5")
171 return Instrument(a, "abc")
172
173 def test_write(self, instr):
174 instr.write("abc")
175 assert instr.adapter.method_calls == [mock.call.write('abc')]
176
177 def test_read(self, instr):
178 instr.read()
179 assert instr.adapter.method_calls == [mock.call.read()]
180
181 def test_write_bytes(self, instr):
182 instr.write_bytes(b"abc")
183 assert instr.adapter.method_calls == [mock.call.write_bytes(b"abc")]
184
185 def test_read_bytes(self, instr):
186 instr.read_bytes(5)
187 assert instr.adapter.method_calls == [mock.call.read_bytes(5)]
188
189 def test_write_binary_values(self, instr):
190 instr.write_binary_values("abc", [5, 6, 7])
191 assert instr.adapter.method_calls == [mock.call.write_binary_values("abc", [5, 6, 7])]
192
193
194 class TestWaiting:
195 @pytest.fixture()
196 def instr(self):
197 class Faked(Instrument):
198 def wait_for(self, query_delay=None):
199 self.waited = query_delay
200 return Faked(ProtocolAdapter(), name="faked")
201
202 def test_waiting(self):
203 instr = Instrument(ProtocolAdapter(), "faked")
204 stop = time.perf_counter() + 100
205 instr.wait_for(0.1)
206 assert time.perf_counter() < stop
207
208 def test_ask_calls_wait(self, instr):
209 instr.adapter.comm_pairs = [("abc", "resp")]
210 instr.ask("abc")
211 assert instr.waited is None
212
213 def test_ask_calls_wait_with_delay(self, instr):
214 instr.adapter.comm_pairs = [("abc", "resp")]
215 instr.ask("abc", query_delay=10)
216 assert instr.waited == 10
217
218 def test_binary_values_calls_wait(self, instr):
219 instr.adapter.comm_pairs = [("abc", "abcdefgh")]
220 instr.binary_values("abc")
221 assert instr.waited is None
222
223
224 @pytest.mark.parametrize("method, write, reply", (("id", "*IDN?", "xyz"),
225 ("complete", "*OPC?", "1"),
226 ("status", "*STB?", "189"),
227 ("options", "*OPT?", "a9"),
228 ))
229 def test_SCPI_properties(method, write, reply):
230 with expected_protocol(
231 Instrument,
232 [(write, reply)],
233 name="test") as instr:
234 assert getattr(instr, method) == reply
235
236
237 @pytest.mark.parametrize("method, write", (("clear", "*CLS"),
238 ("reset", "*RST")
239 ))
240 def test_SCPI_write_commands(method, write):
241 with expected_protocol(
242 Instrument,
243 [(write, None)],
244 name="test") as instr:
245 getattr(instr, method)()
246
247
248 def test_instrument_check_errors():
249 with expected_protocol(
250 Instrument,
251 [("SYST:ERR?", "17,funny stuff"),
252 ("SYST:ERR?", "0")],
253 name="test") as instr:
254 assert instr.check_errors() == [[17, "funny stuff"]]
255
256
257 @pytest.mark.parametrize("method", ("id", "complete", "status", "options",
258 "clear", "reset", "check_errors"
259 ))
260 def test_SCPI_false_raises_errors(method):
261 with pytest.raises(NotImplementedError):
262 getattr(Instrument(FakeAdapter(), "abc", includeSCPI=False), method)()
263
264
265 # Channel
266 class TestMultiFunctionality:
267 """Test the usage of children for different functionalities."""
268 class SomeFunctionality(Channel):
269 """This Functionality needs a prepended `id`."""
270
271 def insert_id(self, command, **kwargs):
272 return f"{self.id}:{command}"
273
274 voltage = Channel.control("Volt?", "Volt %f", "Set voltage in Volts.")
275
276 class InstrumentWithFunctionality(ChannelInstrument):
277 """Instrument with some functionality."""
278
279 def __init__(self, adapter, **kwargs):
280 super().__init__(adapter, **kwargs)
281 self.add_child(TestMultiFunctionality.SomeFunctionality, "X",
282 collection="functions", prefix="f_")
283
284 def test_functionality_dict(self):
285 inst = TestMultiFunctionality.InstrumentWithFunctionality(ProtocolAdapter())
286 assert isinstance(inst.functions["X"], TestMultiFunctionality.SomeFunctionality)
287 assert inst.functions["X"] == inst.f_X
288
289 def test_functions_voltage_getter(self):
290 with expected_protocol(
291 TestMultiFunctionality.InstrumentWithFunctionality,
292 [("X:Volt?", "123.456")]
293 ) as inst:
294 assert inst.f_X.voltage == 123.456
295
296 def test_functions_voltage_setter(self):
297 with expected_protocol(
298 TestMultiFunctionality.InstrumentWithFunctionality,
299 [("X:Volt 123.456000", None)]
300 ) as inst:
301 inst.f_X.voltage = 123.456