Debian Codegraph @

tests/adapters/test_serial_with_loopback.py

raw
1 import pytest
2
3 from serial import Serial
4 from time import time
5 from pymeasure.adapters import SerialAdapter
6
7
8 class TestSerialLoopback:
9 """Test serial adapter with two real but looped COM ports.
10
11 A pair of COM ports that are looped will read the written data from the other.
12 This looping needs to be done outside this script. One suggestion is using the application
13 `com0com <https://com0com.sourceforge.net/>`_.
14 Alternatively two UART adapters could be used, that have their RX/TX physically connected.
15
16 Call PyTest with the argument``--device-address="COM1,COM2"`` to specify the serial addresses,
17 minding the comma for the separation of the two ports.
18 """
19
20 ADAPTER_TIMEOUT = 1.0 # Seconds
21
22 @pytest.fixture()
23 def adapter(self, connected_device_address):
24 device = connected_device_address.split(",")[0]
25 return SerialAdapter(
26 device,
27 baudrate=19200,
28 timeout=self.ADAPTER_TIMEOUT,
29 read_termination=chr(0x0F),
30 )
31
32 @pytest.fixture()
33 def loopback(self, connected_device_address):
34 """See `adapter()`."""
35 device = connected_device_address.split(",")[1]
36 return Serial(device, baudrate=19200)
37
38 def test_read(self, adapter, loopback):
39 """Regular read with fixed number of bytes."""
40 loopback.write(b"abc")
41 result = adapter.read_bytes(3)
42
43 assert len(result) == 3
44
45 @pytest.mark.parametrize("data", [
46 b"a", # Short data
47 b"aaaaabbbbbccccceeeee" * 50, # A lot data
48 b"a" * 256, # Exactly one chunk size
49 b"aaaaabbbbb\nccccceeeee" * 50, # With a newline (should be ignored)
50 ])
51 def test_read_all(self, adapter, loopback, data):
52 """Read with undefined number of bytes - also confirm timeout duration is correct."""
53 loopback.write(data)
54 start = time()
55 result = adapter.read_bytes(-1)
56 elapsed = time() - start
57
58 assert result == data
59 assert self.ADAPTER_TIMEOUT == pytest.approx(elapsed, abs=0.1)
60
61 @pytest.mark.parametrize("chunk", [1, 256, 10000])
62 def test_read_varied_chunk_size(self, adapter, loopback, chunk):
63 """Read with undefined number of bytes with non-default chunk size."""
64 data = b"abcde" * 10
65 loopback.write(data)
66 result = adapter.read_bytes(-1)
67
68 assert result == data