Debian Codegraph @

tests/instruments/test_all_instruments.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 importlib
26 from pathlib import Path
27 from unittest.mock import MagicMock
28
29 import pytest
30
31 from pymeasure import instruments
32 from pymeasure.instruments import Instrument, Channel, generic_types
33
34
35 # Collect all instruments
36 def find_devices_in_module(module):
37 devices = set()
38 channels = set()
39 base_dir = Path(module.__path__[0])
40 base_import = module.__package__ + "."
41 for inst_file in Path(base_dir).rglob("*.py"):
42 relative_path = inst_file.relative_to(base_dir)
43 if inst_file == "__init__.py":
44 # import parent module when filename __init__.py
45 relative_import = ".".join(relative_path.parts[:-1])[:-3]
46 else:
47 relative_import = ".".join(relative_path.parts)[:-3]
48 try:
49 submodule = importlib.import_module(base_import + relative_import)
50 for dev in dir(submodule):
51 if dev.startswith("__"):
52 continue
53 d = getattr(submodule, dev)
54 try:
55 i = issubclass(d, Instrument)
56 c = issubclass(d, Channel)
57 except TypeError:
58 # d is no class
59 continue
60 else:
61 if i:
62 devices.add(d)
63 elif c:
64 channels.add(d)
65 except ModuleNotFoundError:
66 # Some non-required driver dependencies may not be installed on test computer,
67 # for example ni.VirtualBench
68 pass
69 except (OSError, AttributeError):
70 # On Windows instruments.ni.daqmx can raise an OSError before ModuleNotFoundError
71 # when checking installed driver files
72 # it raises an AttributeError under Python 312
73 pass
74 return devices, channels
75
76
77 devices, channels = find_devices_in_module(instruments)
78
79 # Collect all properties
80 properties = []
81 for device in devices.union(channels):
82 for property_name in dir(device):
83 prop = getattr(device, property_name)
84 if isinstance(prop, property):
85 properties.append((device, property_name, prop))
86 for mixin in dir(generic_types):
87 if mixin in ("Instrument", "Channel", "CommonBase"): # exclucion list.
88 continue
89 elif mixin[0].isupper():
90 # filter only classes
91 device = getattr(generic_types, mixin)
92 for property_name in dir(device):
93 prop = getattr(device, property_name)
94 if isinstance(prop, property):
95 properties.append((device, property_name, prop))
96
97 # Instruments unable to accept an Adapter instance.
98 proper_adapters = []
99 # Instruments with communication in their __init__, which consequently fails.
100 need_init_communication = [
101 "SwissArmyFake",
102 "FakeInstrument",
103 "ThorlabsPM100USB",
104 "Keithley2700",
105 "TC038",
106 "Agilent34450A",
107 "AWG401x_AWG",
108 "AWG401x_AFG",
109 "VARX",
110 "HP8116A",
111 "IBeamSmart",
112 "ANC300Controller",
113 ]
114 # Channels which are still an Instrument subclass
115 channel_as_instrument_subclass = [
116 "SMU", # agilent/agilent4156
117 "VMU", # agilent/agilent4156
118 "VSU", # agilent/agilent4156
119 "VARX", # agilent/agilent4156
120 "VAR1", # agilent/agilent4156
121 "VAR2", # agilent/agilent4156
122 "VARD", # agilent/agilent4156
123 ]
124 # Instruments whose property docstrings are not YET in accordance with the style (Get, Set, Control)
125 grandfathered_docstring_instruments = [
126 "AWG401x_AFG",
127 "AWG401x_AWG",
128 "AdvantestR624X",
129 "SMUChannel", # AdvantestR624X
130 "AdvantestR6245",
131 "AdvantestR6246",
132 "Agilent33220A",
133 "Agilent33500",
134 "Agilent33500Channel",
135 "Agilent33521A",
136 "Agilent34450A",
137 "Agilent4156",
138 "SMU", # agilent/agilent4156
139 "VMU", # agilent/agilent4156
140 "VSU", # agilent/agilent4156
141 "VARX", # agilent/agilent4156
142 "VAR1", # agilent/agilent4156
143 "VAR2", # agilent/agilent4156
144 "VARD", # agilent/agilent4156
145 "Agilent8257D",
146 "Agilent8722ES",
147 "AgilentB1500",
148 "AgilentE4408B",
149 "AgilentE4980",
150 "Ametek7270",
151 "DPSeriesMotorController",
152 "AnritsuMS2090A",
153 "SM7045D",
154 "HP3437A",
155 "HP34401A",
156 "HP3478A",
157 "HP6632A",
158 "HP6633A",
159 "HP6634A",
160 "Keithley2000",
161 "Keithley2306",
162 "Keithley2306Channel",
163 "BatteryChannel", # Keithley2306
164 "Step", # Keithley2306
165 "Relay", # Keithley2306
166 "Keithley2400",
167 "Keithley2450",
168 "Keithley2600",
169 "Keithley2700",
170 "Keithley2750",
171 "Keithley6221",
172 "Keithley6517B",
173 "KeysightDSOX1102G",
174 "LakeShore421",
175 "LakeShoreTemperatureChannel",
176 "LakeShoreHeaterChannel",
177 "IPS120_10",
178 "ITC503",
179 "PS120_10",
180 "ParkerGV6",
181 "FSL",
182 "SFM",
183 "DSP7265",
184 "SG380",
185 "SR510",
186 "SR570",
187 "SR830",
188 "SR860",
189 "ATS525",
190 "ATS545",
191 "ATSBase",
192 "ECO560",
193 "TexioPSW360L30",
194 "IonGaugeAndPressureChannel",
195 "PressureChannel",
196 "SequenceEntry",
197 "ChannelBase",
198 "ChannelAWG",
199 "ChannelAFG",
200 ]
201
202
203 @pytest.mark.parametrize("cls", devices)
204 def test_adapter_arg(cls):
205 "Test that every instrument has adapter as their input argument."
206 if cls.__name__ in proper_adapters:
207 pytest.skip(f"{cls.__name__} does not accept an Adapter instance.")
208 elif cls.__name__ in need_init_communication:
209 pytest.skip(f"{cls.__name__} requires communication in init.")
210 elif cls.__name__ in channel_as_instrument_subclass:
211 pytest.skip(f"{cls.__name__} is a channel, not an instrument.")
212 elif cls.__name__ == "Instrument":
213 pytest.skip("`Instrument` requires a `name` parameter.")
214 cls(adapter=MagicMock())
215
216
217 @pytest.mark.parametrize("cls", devices)
218 def test_name_argument(cls):
219 "Test that every instrument accepts a name argument."
220 if cls.__name__ in (*proper_adapters, *need_init_communication):
221 pytest.skip(f"{cls.__name__} cannot be tested without communication.")
222 elif cls.__name__ in channel_as_instrument_subclass:
223 pytest.skip(f"{cls.__name__} is a channel, not an instrument.")
224 inst = cls(adapter=MagicMock(), name="Name_Test")
225 assert inst.name == "Name_Test"
226
227
228 # This uses a pyvisa-sim default instrument, we could also define our own.
229 SIM_RESOURCE = "ASRL2::INSTR"
230 is_pyvisa_sim_not_installed = not bool(importlib.util.find_spec("pyvisa_sim"))
231
232
233 @pytest.mark.skipif(
234 is_pyvisa_sim_not_installed, reason="PyVISA tests require the pyvisa-sim library"
235 )
236 @pytest.mark.parametrize("cls", devices)
237 def test_kwargs_to_adapter(cls):
238 """Verify that kwargs are accepted and handed to the adapter."""
239 if cls.__name__ in (*proper_adapters, *need_init_communication):
240 pytest.skip(f"{cls.__name__} cannot be tested without communication.")
241 elif cls.__name__ in channel_as_instrument_subclass:
242 pytest.skip(f"{cls.__name__} is a channel, not an instrument.")
243 elif cls.__name__ == "Instrument":
244 pytest.skip("`Instrument` requires a `name` parameter.")
245
246 with pytest.raises(
247 ValueError, match="'kwarg_test' is not a valid attribute for type SerialInstrument"
248 ):
249 cls(SIM_RESOURCE, visa_library="@sim", kwarg_test=True)
250
251
252 @pytest.mark.parametrize("cls", devices)
253 @pytest.mark.filterwarnings(
254 "error:It is deprecated to specify `includeSCPI` implicitly:FutureWarning")
255 def test_includeSCPI_explicitly_set(cls):
256 if cls.__name__ in (*proper_adapters, *need_init_communication):
257 pytest.skip(f"{cls.__name__} cannot be tested without communication.")
258 elif cls.__name__ in channel_as_instrument_subclass:
259 pytest.skip(f"{cls.__name__} is a channel, not an instrument.")
260 elif cls.__name__ == "Instrument":
261 pytest.skip("`Instrument` requires a `name` parameter.")
262
263 cls(adapter=MagicMock())
264 # assert that no error is raised
265
266
267 @pytest.mark.parametrize("cls", devices)
268 @pytest.mark.filterwarnings(
269 "error:Defining SCPI base functionality with `includeSCPI=True` is deprecated:FutureWarning")
270 def test_includeSCPI_not_set_to_True(cls):
271 if cls.__name__ in (*proper_adapters, *need_init_communication):
272 pytest.skip(f"{cls.__name__} cannot be tested without communication.")
273 elif cls.__name__ in channel_as_instrument_subclass:
274 pytest.skip(f"{cls.__name__} is a channel, not an instrument.")
275 elif cls.__name__ == "Instrument":
276 pytest.skip("`Instrument` requires a `name` parameter.")
277
278 cls(adapter=MagicMock())
279 # assert that no error is raised
280
281
282 def property_name_to_id(value):
283 """Create a test id from `value`."""
284 device, property_name, prop = value
285 return f"{device.__name__}.{property_name}"
286
287
288 @pytest.mark.parametrize("prop_set", properties, ids=property_name_to_id)
289 def test_property_docstrings(prop_set):
290 device, property_name, prop = prop_set
291 if device.__name__ in grandfathered_docstring_instruments:
292 pytest.skip(f"{device.__name__} is in the codebase and has to be refactored later on.")
293 start = prop.__doc__.split(maxsplit=1)[0]
294 assert start in ("Control", "Measure", "Set", "Get"), (
295 f"'{device.__name__}.{property_name}' docstring does start with '{start}', not 'Control', "
296 "'Measure', 'Get', or 'Set'."
297 )