Files
seismo-relay/tests/test_device_access.py
T

245 lines
8.4 KiB
Python

"""DeviceAccess: dispatch by serial, sessions, the lock, the reaper -- and the
contract that both series answer in the same shape."""
from __future__ import annotations
import dataclasses
import os
import sys
import threading
import pytest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from device_access_fakes import FakeMiniMateClient, FakeMicromateClient # noqa: E402
from sfm.device_access.access import DeviceAccess # noqa: E402
import micromate.protocol as mm_proto # noqa: E402
from sfm.device_access.errors import ( # noqa: E402
BadRequest, CallHomeInProgress, ConnectFailed, UnitBusy, WrongUnit,
)
from sfm.device_access.models import UnitAddress # noqa: E402
from sfm.device_access.s4 import RingDetected # noqa: E402
ADDR = UnitAddress(host="10.0.0.5", tcp_port=9034, port=None, baud=None)
class Clock:
def __init__(self, t=1000.0):
self.t = t
def __call__(self):
return self.t
def access(s3=(), s4=(), clock=None, lock_timeout=0.2):
s3q, s4q = list(s3), list(s4)
return DeviceAccess(
s3_client_factory=lambda a: s3q.pop(0),
s4_client_factory=lambda a: s4q.pop(0),
clock=clock or Clock(), lock_timeout=lock_timeout, start_reaper=False,
)
def test_the_serial_prefix_picks_the_adapter():
da = access(s3=[FakeMiniMateClient()], s4=[FakeMicromateClient()])
assert da.identify(ADDR, "be18193").series == 3
assert da.identify(ADDR, " um20147").series == 4
def test_an_unknown_prefix_never_touches_a_unit():
da = access()
with pytest.raises(BadRequest):
da.identify(ADDR, "XX123")
def test_a_micromate_stays_on_the_line_between_requests():
fake = FakeMicromateClient()
da = access(s4=[fake])
da.identify(ADDR, "UM20147")
da.status(ADDR, "UM20147")
da.settings(ADDR, "UM20147")
assert fake.opened == 1 # one call-up, three requests
assert fake.calls[0] == "connect"
def test_a_minimate_reconnects_per_request():
a, b = FakeMiniMateClient(), FakeMiniMateClient()
da = access(s3=[a, b])
da.status(ADDR, "BE18193")
da.status(ADDR, "BE18193")
assert a.closed == 1 and b.closed == 1
def test_a_dropped_line_is_called_up_again_quietly():
first, second = FakeMicromateClient(), FakeMicromateClient()
da = access(s4=[first, second])
da.status(ADDR, "UM20147")
first._open = False # the modem dropped the idle line
st = da.status(ADDR, "UM20147")
assert st.series == 4 and second.opened == 1
def test_a_different_serial_at_a_held_address_is_refused_without_io():
first, second = FakeMicromateClient(), FakeMicromateClient(serial="UM12947")
da = access(s4=[first, second])
da.status(ADDR, "UM20147")
with pytest.raises(WrongUnit, match="hangup"):
da.status(ADDR, "UM12947")
assert first.closed == 0 and second.opened == 0
assert da.held_serial(ADDR) == "UM20147"
def test_a_different_serial_replaces_a_session_that_is_no_longer_open():
first, second = FakeMicromateClient(), FakeMicromateClient(serial="UM12947")
da = access(s4=[first, second])
da.status(ADDR, "UM20147")
first.close()
da.status(ADDR, "UM12947")
assert second.opened == 1
def test_a_busy_unit_answers_423_without_a_second_connection():
fake = FakeMicromateClient()
da = access(s4=[fake], lock_timeout=0.2)
entered, release = threading.Event(), threading.Event()
def slow_request():
with da._locks.hold(ADDR.key): # simulate a request in flight
entered.set()
release.wait(2)
t = threading.Thread(target=slow_request)
t.start()
entered.wait(2)
try:
with pytest.raises(UnitBusy):
da.status(ADDR, "UM20147")
assert fake.opened == 0 # no second connection was opened
finally:
release.set()
t.join()
def test_hang_up_closes_a_held_line():
fake = FakeMicromateClient()
da = access(s4=[fake])
da.status(ADDR, "UM20147")
assert da.hang_up(ADDR) is True
assert fake.closed == 1
assert da.hang_up(ADDR) is False # nothing left to hang up
def test_a_peer_dropped_line_that_still_reads_open_is_retried_once():
first, second = FakeMicromateClient(), FakeMicromateClient()
da = access(s4=[first, second])
da.status(ADDR, "UM20147")
first.fail = [mm_proto.TimeoutError("quiet")] # _open untouched: looks open
st = da.status(ADDR, "UM20147")
assert st.series == 4 and first.closed == 1 and second.opened == 1
def test_a_failed_fresh_call_up_is_not_retried():
da = access(s4=[FakeMicromateClient(open_error=ConnectionRefusedError("no"))])
with pytest.raises(ConnectFailed):
da.status(ADDR, "UM20147") # a 2nd attempt would pop an empty queue
def test_a_ring_on_a_held_line_is_not_retried():
first, second = FakeMicromateClient(), FakeMicromateClient()
da = access(s4=[first, second])
da.status(ADDR, "UM20147")
first.fail = [RingDetected("RADIO RING")]
with pytest.raises(CallHomeInProgress):
da.status(ADDR, "UM20147")
assert second.opened == 0
def test_series3_beside_a_held_series4_line_is_refused_without_io():
micro, mini = FakeMicromateClient(), FakeMiniMateClient()
da = access(s3=[mini], s4=[micro])
da.status(ADDR, "UM20147")
with pytest.raises(WrongUnit):
da.status(ADDR, "BE18193")
assert mini.opened == 0 and micro.closed == 0 and micro.is_open()
# ── the reaper ────────────────────────────────────────────────────────────────
def test_tick_listens_then_keeps_alive_then_hangs_up_when_idle():
clock = Clock(1000.0)
fake = FakeMicromateClient()
da = access(s4=[fake], clock=clock)
da.status(ADDR, "UM20147")
fake.calls.clear()
clock.t = 1030.0
da.tick() # quiet: listen only
assert fake.calls == ["read_unsolicited"]
clock.t = 1061.0
da.tick() # 60 s since traffic: keep-alive
assert fake.calls[-1] == "poll"
clock.t = 1301.0
da.tick() # 300 s since last USE: hang up
assert fake.closed == 1
assert da.hang_up(ADDR) is False
def test_tick_releases_the_line_on_a_ring_while_idle():
clock = Clock(1000.0)
fake = FakeMicromateClient()
da = access(s4=[fake], clock=clock)
da.status(ADDR, "UM20147")
fake.fail = [RingDetected("RADIO RING")]
clock.t = 1010.0
da.tick()
assert fake.closed == 1
def test_tick_skips_a_unit_that_is_busy():
clock = Clock(1000.0)
fake = FakeMicromateClient()
da = access(s4=[fake], clock=clock)
da.status(ADDR, "UM20147")
fake.calls.clear()
clock.t = 1400.0
with da._locks.hold(ADDR.key):
da.tick() # must not block or hang up mid-request
assert fake.calls == [] and fake.closed == 0
def test_a_ring_mid_request_is_a_clear_error():
fake = FakeMicromateClient()
da = access(s4=[fake])
da.status(ADDR, "UM20147")
fake.fail = [RingDetected("RADIO RING")]
with pytest.raises(CallHomeInProgress):
da.status(ADDR, "UM20147")
# ── the contract: both series answer in the same shape ────────────────────────
@pytest.mark.parametrize("op", ["identify", "status", "settings"])
def test_both_series_return_the_same_model_with_the_same_fields(op):
da = access(s3=[FakeMiniMateClient()], s4=[FakeMicromateClient()])
s3 = getattr(da, op)(ADDR, "BE18193")
s4 = getattr(da, op)(ADDR, "UM20147")
assert type(s3) is type(s4)
assert [f.name for f in dataclasses.fields(s3)] == [f.name for f in dataclasses.fields(s4)]
assert (s3.series, s4.series) == (3, 4)
for name in (f.name for f in dataclasses.fields(s3)):
a, b = getattr(s3, name), getattr(s4, name)
if a is not None and b is not None and name != "detail":
assert type(a) is type(b) or {type(a), type(b)} <= {int, float}, name
def test_held_serial_reports_an_open_line_only():
fake = FakeMicromateClient()
da = access(s4=[fake])
assert da.held_serial(ADDR) is None
da.status(ADDR, "UM20147")
assert da.held_serial(ADDR) == "UM20147"
da.hang_up(ADDR)
assert da.held_serial(ADDR) is None