|
| 1 | +from typing import Callable, Any |
| 2 | +import re |
| 3 | + |
| 4 | +from geocompy import GeoComProtocol |
| 5 | +from geocompy.communication import Connection |
| 6 | +from geocompy.data import ( |
| 7 | + Byte |
| 8 | +) |
| 9 | + |
| 10 | +from helpers import faulty_parser |
| 11 | + |
| 12 | + |
| 13 | +class DummyGeoComConnection(Connection): |
| 14 | + _RESP = re.compile( |
| 15 | + r"^%R1P," |
| 16 | + r"(?P<comrc>\d+)," |
| 17 | + r"(?P<tr>\d+):" |
| 18 | + r"(?P<rc>\d+)" |
| 19 | + r"(?:,(?P<params>.*))?$" |
| 20 | + ) |
| 21 | + |
| 22 | + _CMD = re.compile( |
| 23 | + r"^%R1Q," |
| 24 | + r"(?P<rpc>\d+):" |
| 25 | + r"(?:(?P<params>.*))?$" |
| 26 | + ) |
| 27 | + |
| 28 | + def send(self, message: str): |
| 29 | + return |
| 30 | + |
| 31 | + def exchange1(self, cmd: str) -> str: |
| 32 | + if not self._CMD.match(cmd): |
| 33 | + return "%R1P,0,0:2" |
| 34 | + |
| 35 | + if cmd == "%R1Q,5008:": |
| 36 | + return "%R1P,0,0:0,1996,'07','19','10','13','2f'" |
| 37 | + |
| 38 | + return "%R1P,0,0:0" |
| 39 | + |
| 40 | + |
| 41 | +class GeoComTester: |
| 42 | + @staticmethod |
| 43 | + def test_parse_response(instrument: GeoComProtocol): |
| 44 | + cmd = "%R1Q,5008:" |
| 45 | + answer = "%R1P,0,0:0,1996,'07','19','10','13','2f'" |
| 46 | + parsers: dict[str, Callable[[str], Any]] = { |
| 47 | + "year": int, |
| 48 | + "month": Byte.parse, |
| 49 | + "day": Byte.parse, |
| 50 | + "hour": Byte.parse, |
| 51 | + "minute": Byte.parse, |
| 52 | + "second": Byte.parse |
| 53 | + } |
| 54 | + response = instrument.parse_response( |
| 55 | + cmd, |
| 56 | + answer, |
| 57 | + parsers |
| 58 | + ) |
| 59 | + assert response.params["year"] == 1996 |
| 60 | + |
| 61 | + response = instrument.parse_response( |
| 62 | + cmd, |
| 63 | + "%R1P,1,0:", |
| 64 | + parsers |
| 65 | + ) |
| 66 | + assert len(response.params) == 0 |
| 67 | + |
| 68 | + parsers_faulty = parsers.copy() |
| 69 | + parsers_faulty["year"] = faulty_parser |
| 70 | + response = instrument.parse_response( |
| 71 | + cmd, |
| 72 | + answer, |
| 73 | + parsers_faulty |
| 74 | + ) |
| 75 | + assert len(response.params) == 0 |
| 76 | + |
| 77 | + @staticmethod |
| 78 | + def test_request(instrument: GeoComProtocol): |
| 79 | + response = instrument.request( |
| 80 | + 5008, |
| 81 | + parsers={ |
| 82 | + "year": int, |
| 83 | + "month": Byte.parse, |
| 84 | + "day": Byte.parse, |
| 85 | + "hour": Byte.parse, |
| 86 | + "minute": Byte.parse, |
| 87 | + "second": Byte.parse |
| 88 | + } |
| 89 | + ) |
| 90 | + assert response.params["year"] == 1996 |
| 91 | + |
| 92 | + response = instrument.request( |
| 93 | + 1, |
| 94 | + (1, 2.0) |
| 95 | + ) |
| 96 | + assert response.cmd == "%R1Q,1:1,2.0" |
| 97 | + assert response.response == "%R1P,0,0:0" |
0 commit comments