Debian Codegraph @

tests/adapters/test_adapter.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 from unittest import mock
27
28 import pytest
29
30 from pymeasure.adapters import Adapter, FakeAdapter, ProtocolAdapter
31
32
33 @pytest.fixture()
34 def adapter():
35 return Adapter()
36
37
38 @pytest.fixture()
39 def fake():
40 return FakeAdapter()
41
42
43 def test_init(adapter):
44 assert adapter.connection is None
45 assert adapter.log == logging.getLogger("Adapter")
46
47
48 def test_init_log():
49 adapter = Adapter(log=logging.getLogger("parent"))
50 assert adapter.log == logging.getLogger("parent.Adapter")
51
52
53 def test_deprecated_preprocess_reply():
54 with pytest.warns(FutureWarning):
55 adapter = Adapter(preprocess_reply=lambda v: v)
56 assert adapter.preprocess_reply is not None
57
58
59 def test_del(adapter):
60 adapter.connection = mock.MagicMock()
61 adapter.__del__()
62 assert adapter.connection.method_calls == [mock.call.close()]
63
64
65 def test_write(fake):
66 fake.write("abc")
67 assert fake._buffer == "abc"
68
69
70 def test_write_bytes(fake):
71 fake.write_bytes(b"abc")
72 assert fake._buffer == "abc"
73
74
75 def test_read(fake):
76 fake._buffer = "abc"
77 assert fake.read() == "abc"
78
79
80 def test_read_bytes(fake):
81 fake._buffer = "abc"
82 assert fake.read_bytes(5) == b"abc"
83
84
85 @pytest.mark.parametrize("method, args", (['_write', ['5']],
86 ['_read', []],
87 ['_write_bytes', ['8']],
88 ['_read_bytes', ['5', False]],
89 ))
90 def test_not_implemented_methods(adapter, method, args):
91 with pytest.raises(NotImplementedError):
92 getattr(adapter, method)(*args)
93
94
95 def test_ask_deprecation_warning():
96 a = FakeAdapter()
97 with pytest.warns(FutureWarning):
98 assert a.ask("abc") == "abc"
99
100
101 @pytest.mark.parametrize("value, kwargs, result",
102 (("5,6,7", {}, [5, 6, 7]),
103 ("5.6.7", {'separator': '.'}, [5, 6, 7]),
104 ("5,6,7", {'cast': str}, ['5', '6', '7']),
105 ("X,Y,Z", {}, ['X', 'Y', 'Z']),
106 ("X,Y,Z", {'cast': str}, ['X', 'Y', 'Z']),
107 ("X.Y.Z", {'separator': '.'}, ['X', 'Y', 'Z']),
108 ("0,5,7.1", {'cast': bool}, [False, True, True]),
109 ))
110 def test_adapter_values(value, kwargs, result):
111 a = FakeAdapter()
112 with pytest.warns(FutureWarning):
113 assert a.values(value, **kwargs) == result
114
115
116 def test_read_binary_values():
117 a = ProtocolAdapter([(None, "1 2")])
118 assert list(a.read_binary_values(dtype=int, sep=" ")) == pytest.approx([1, 2])
119
120
121 def test_write_binary_values():
122 """Test write_binary_values in the ieee header format."""
123 a = ProtocolAdapter([(b'CMD#212\x00\x00\x80?\x00\x00\x00@\x00\x00@@\n', None)])
124 a.write_binary_values("CMD", [1, 2, 3], termination="\n")
125
126
127 def test_adapter_preprocess_reply():
128 with pytest.warns(FutureWarning):
129 a = FakeAdapter(preprocess_reply=lambda v: v[1:])
130 assert str(a) == "<FakeAdapter>"
131 assert a.values("R42.1") == [42.1]
132 assert a.values("A4,3,2") == [4, 3, 2]
133 assert a.values("TV 1", preprocess_reply=lambda v: v.split()[0]) == ['TV']
134 assert a.values("15", preprocess_reply=lambda v: v) == [15]
135 a = FakeAdapter()
136 assert a.values("V 3.4", preprocess_reply=lambda v: v.split()[1]) == [3.4]
137
138
139 def test_binary_values_deprecation_warning():
140 a = FakeAdapter()
141 with pytest.warns(FutureWarning):
142 a.binary_values("abcdefgh")
143
144
145 class TestLoggingForTestGenerator:
146 """The test Generator relies on specific logging in the adapter, these tests ensure that."""
147 message = b"some written message"
148
149 @pytest.fixture
150 def adapter(self, caplog):
151 adapter = ProtocolAdapter()
152 caplog.set_level(logging.DEBUG)
153 return adapter
154
155 def test_write(self, adapter, caplog):
156 adapter.comm_pairs = [(self.message, None)]
157 written = self.message.decode()
158 adapter.write(written)
159 record = caplog.records[0]
160 assert record.msg == "WRITE:%s"
161 assert record.args == (written,)
162
163 def test_write_bytes(self, adapter, caplog):
164 adapter.comm_pairs = [(self.message, None)]
165 adapter.write(self.message)
166 record = caplog.records[0]
167 assert record.msg == "WRITE:%s"
168 assert record.args == (self.message,)
169
170 def test_read(self, adapter, caplog):
171 adapter.comm_pairs = [(None, self.message)]
172 read = adapter.read()
173 assert read == self.message.decode()
174 record = caplog.records[0]
175 assert record.msg == "READ:%s"
176 assert record.args == (read,)
177
178 def test_read_bytes(self, adapter, caplog):
179 adapter.comm_pairs = [(None, self.message)]
180 read = adapter.read_bytes(-1)
181 assert read == self.message
182 record = caplog.records[0]
183 assert record.msg == "READ:%s"
184 assert record.args == (read,)