| 1 |
"""Tests for the main logic paths of aioacaia.scale.""" |
| 2 |
|
| 3 |
import asyncio |
| 4 |
from types import SimpleNamespace |
| 5 |
from unittest.mock import AsyncMock, Mock |
| 6 |
|
| 7 |
import pytest |
| 8 |
from bleak.exc import BleakDeviceNotFoundError, BleakError |
| 9 |
|
| 10 |
from aioacaia import scale as scale_module |
| 11 |
from aioacaia.const import UnitMass |
| 12 |
from aioacaia.encoder import Command |
| 13 |
from aioacaia.exceptions import AcaiaDeviceNotFound, AcaiaError |
| 14 |
from aioacaia.scale import AcaiaScale |
| 15 |
from tests.fixtures import messages as m |
| 16 |
|
| 17 |
_ADDRESS = "aa:bb:cc:dd:ee:ff" |
| 18 |
|
| 19 |
|
| 20 |
def _make_scale(**kwargs) -> AcaiaScale: |
| 21 |
"""Create a scale bound to a dummy address.""" |
| 22 |
return AcaiaScale(_ADDRESS, **kwargs) |
| 23 |
|
| 24 |
|
| 25 |
def test_auth_command_is_instance_specific(): |
| 26 |
"""Each scale selects the auth command matching its generation.""" |
| 27 |
new_style_scale = _make_scale(is_new_style_scale=True) |
| 28 |
old_style_scale = _make_scale(is_new_style_scale=False) |
| 29 |
|
| 30 |
assert new_style_scale._auth is Command.AUTH_PYXIS |
| 31 |
assert old_style_scale._auth is Command.AUTH_CLASSIC |
| 32 |
|
| 33 |
|
| 34 |
async def test_receive_settings_updates_device_state(): |
| 35 |
"""A settings notification populates the device state.""" |
| 36 |
scale = _make_scale() |
| 37 |
await scale.on_bluetooth_data_received(None, bytearray(m.SETTINGS_GRAMS)) |
| 38 |
|
| 39 |
state = scale.device_state |
| 40 |
assert state is not None |
| 41 |
assert state.battery_level == 93 |
| 42 |
assert state.units == UnitMass.GRAMS |
| 43 |
assert state.beeps is True |
| 44 |
assert state.auto_off_time == 5 |
| 45 |
|
| 46 |
|
| 47 |
async def test_receive_weight_updates_weight_and_history(): |
| 48 |
"""A weight notification updates the weight and history.""" |
| 49 |
scale = _make_scale() |
| 50 |
await scale.on_bluetooth_data_received(None, bytearray(m.WEIGHT)) |
| 51 |
|
| 52 |
assert scale.weight == pytest.approx(175.9) |
| 53 |
assert len(scale.weight_history) == 1 |
| 54 |
|
| 55 |
|
| 56 |
async def test_timer_notification_preserves_weight_and_updates_timer(monkeypatch): |
| 57 |
"""Timer-only notifications do not erase the latest weight.""" |
| 58 |
monkeypatch.setattr("aioacaia.scale.time.monotonic", lambda: 1000.0) |
| 59 |
scale = _make_scale() |
| 60 |
await scale.on_bluetooth_data_received(None, bytearray(m.WEIGHT)) |
| 61 |
|
| 62 |
await scale.on_bluetooth_data_received(None, bytearray(m.TIMER)) |
| 63 |
|
| 64 |
assert scale.weight == pytest.approx(175.9) |
| 65 |
assert scale.timer == 90 |
| 66 |
|
| 67 |
|
| 68 |
async def test_button_without_weight_preserves_latest_weight(): |
| 69 |
"""Button notifications only replace weight when they include one.""" |
| 70 |
scale = _make_scale() |
| 71 |
await scale.on_bluetooth_data_received(None, bytearray(m.WEIGHT)) |
| 72 |
|
| 73 |
await scale.on_bluetooth_data_received(None, bytearray(m.BUTTON_START)) |
| 74 |
|
| 75 |
assert scale.weight == pytest.approx(175.9) |
| 76 |
|
| 77 |
|
| 78 |
async def test_receive_start_button_starts_timer(): |
| 79 |
"""A start button notification starts the timer.""" |
| 80 |
scale = _make_scale() |
| 81 |
await scale.on_bluetooth_data_received(None, bytearray(m.BUTTON_START)) |
| 82 |
|
| 83 |
assert scale.timer_running is True |
| 84 |
assert scale._timer_start is not None |
| 85 |
|
| 86 |
|
| 87 |
async def test_receive_stop_button_stops_timer(): |
| 88 |
"""A stop button notification stops the timer.""" |
| 89 |
scale = _make_scale() |
| 90 |
scale.timer_running = True |
| 91 |
await scale.on_bluetooth_data_received(None, bytearray(m.BUTTON_STOP)) |
| 92 |
|
| 93 |
assert scale.timer_running is False |
| 94 |
assert scale._timer_stop is not None |
| 95 |
|
| 96 |
|
| 97 |
async def test_receive_reset_button_clears_timer(): |
| 98 |
"""A reset button notification clears the timer state.""" |
| 99 |
scale = _make_scale() |
| 100 |
scale.timer_running = True |
| 101 |
scale._timer_start = 100.0 |
| 102 |
scale._timer_stop = 200.0 |
| 103 |
await scale.on_bluetooth_data_received(None, bytearray(m.BUTTON_RESET)) |
| 104 |
|
| 105 |
assert scale.timer_running is False |
| 106 |
assert scale._timer_start is None |
| 107 |
assert scale._timer_stop is None |
| 108 |
|
| 109 |
|
| 110 |
async def test_receive_invokes_notify_callback(): |
| 111 |
"""Receiving a valid message triggers the notify callback.""" |
| 112 |
callback = Mock() |
| 113 |
scale = _make_scale(notify_callback=callback) |
| 114 |
await scale.on_bluetooth_data_received(None, bytearray(m.WEIGHT)) |
| 115 |
|
| 116 |
callback.assert_called_once() |
| 117 |
|
| 118 |
|
| 119 |
async def test_receive_ignores_non_header_short_message(): |
| 120 |
"""A short message without a header is ignored.""" |
| 121 |
callback = Mock() |
| 122 |
scale = _make_scale(notify_callback=callback) |
| 123 |
await scale.on_bluetooth_data_received(None, bytearray(b"\x01\x02")) |
| 124 |
|
| 125 |
assert scale.weight is None |
| 126 |
assert scale._last_short_msg is None |
| 127 |
callback.assert_not_called() |
| 128 |
|
| 129 |
|
| 130 |
def test_timer_while_running(monkeypatch): |
| 131 |
"""While running, the timer reports elapsed time since start.""" |
| 132 |
monkeypatch.setattr("aioacaia.scale.time.monotonic", lambda: 1050.0) |
| 133 |
scale = _make_scale() |
| 134 |
scale._timer_start = 1000.0 |
| 135 |
scale.timer_running = True |
| 136 |
|
| 137 |
assert scale.timer == 50 |
| 138 |
|
| 139 |
|
| 140 |
def test_timer_while_stopped(): |
| 141 |
"""While stopped, the timer reports the frozen elapsed time.""" |
| 142 |
scale = _make_scale() |
| 143 |
scale._timer_start = 1000.0 |
| 144 |
scale._timer_stop = 1042.0 |
| 145 |
scale.timer_running = False |
| 146 |
|
| 147 |
assert scale.timer == 42 |
| 148 |
|
| 149 |
|
| 150 |
def test_flow_rate_none_without_enough_history(): |
| 151 |
"""Flow rate is None with fewer than four readings.""" |
| 152 |
scale = _make_scale() |
| 153 |
scale.weight_history.extend([(0.0, 0.0), (1.0, 1.0), (2.0, 2.0)]) |
| 154 |
|
| 155 |
assert scale.flow_rate is None |
| 156 |
|
| 157 |
|
| 158 |
def test_flow_rate_computes_rate(): |
| 159 |
"""Flow rate is computed from the weight history.""" |
| 160 |
scale = _make_scale() |
| 161 |
scale.weight_history.extend([(0.0, 0.0), (1.0, 1.0), (2.0, 2.0), (3.0, 3.0)]) |
| 162 |
|
| 163 |
assert scale.flow_rate == pytest.approx(1.0) |
| 164 |
|
| 165 |
|
| 166 |
def test_flow_rate_skips_nonpositive_time_deltas(): |
| 167 |
"""Duplicate or backward timestamps do not cause invalid division.""" |
| 168 |
scale = _make_scale() |
| 169 |
scale.weight_history.extend([(1.0, 1.0), (1.0, 2.0), (1.0, 3.0), (1.0, 4.0)]) |
| 170 |
|
| 171 |
assert scale.flow_rate is None |
| 172 |
|
| 173 |
|
| 174 |
async def test_tare_enqueues_command(): |
| 175 |
"""Taring enqueues the tare command.""" |
| 176 |
scale = _make_scale() |
| 177 |
scale.connected = True |
| 178 |
await scale.tare() |
| 179 |
|
| 180 |
char_id, payload = scale._queue.get_nowait() |
| 181 |
assert char_id == scale._default_char_id |
| 182 |
assert payload == Command.TARE |
| 183 |
|
| 184 |
|
| 185 |
async def test_process_queue_acknowledges_failed_write(): |
| 186 |
"""A failed write does not leave the queue join counter blocked.""" |
| 187 |
scale = _make_scale() |
| 188 |
scale.connected = True |
| 189 |
client = AsyncMock() |
| 190 |
client.write_gatt_char.side_effect = BleakError("write failed") |
| 191 |
scale._client = client |
| 192 |
await scale._queue.put((scale._default_char_id, b"payload")) |
| 193 |
|
| 194 |
await scale.process_queue() |
| 195 |
await asyncio.wait_for(scale._queue.join(), timeout=0.1) |
| 196 |
|
| 197 |
assert scale.connected is False |
| 198 |
client.disconnect.assert_awaited_once() |
| 199 |
assert scale._client is None |
| 200 |
|
| 201 |
|
| 202 |
async def test_connect_without_background_tasks_writes_setup_directly(monkeypatch): |
| 203 |
"""A connection without workers still authenticates and disconnects cleanly.""" |
| 204 |
client = AsyncMock() |
| 205 |
establish_connection = AsyncMock(return_value=client) |
| 206 |
monkeypatch.setattr(scale_module, "establish_connection", establish_connection) |
| 207 |
device = SimpleNamespace(name="Test Scale", address=_ADDRESS) |
| 208 |
scale = AcaiaScale(device) |
| 209 |
|
| 210 |
await scale.connect(setup_tasks=False) |
| 211 |
|
| 212 |
assert scale.connected is True |
| 213 |
assert scale._queue.empty() |
| 214 |
assert client.write_gatt_char.await_count == 2 |
| 215 |
|
| 216 |
await asyncio.wait_for(scale.disconnect(), timeout=0.1) |
| 217 |
client.disconnect.assert_awaited_once() |
| 218 |
|
| 219 |
|
| 220 |
async def test_connect_subscription_failure_rolls_back(monkeypatch): |
| 221 |
"""A notification subscription failure closes the client and resets state.""" |
| 222 |
client = AsyncMock() |
| 223 |
client.start_notify.side_effect = BleakError("subscription failed") |
| 224 |
monkeypatch.setattr( |
| 225 |
scale_module, "establish_connection", AsyncMock(return_value=client) |
| 226 |
) |
| 227 |
device = SimpleNamespace(name="Test Scale", address=_ADDRESS) |
| 228 |
scale = AcaiaScale(device) |
| 229 |
|
| 230 |
with pytest.raises(AcaiaError, match="Error setting up connection"): |
| 231 |
await scale.connect(setup_tasks=False) |
| 232 |
|
| 233 |
assert scale.connected is False |
| 234 |
assert scale._client is None |
| 235 |
client.disconnect.assert_awaited_once() |
| 236 |
|
| 237 |
|
| 238 |
async def test_connect_waits_out_reconnect_cooldown(monkeypatch): |
| 239 |
"""A recent disconnect delays setup instead of returning disconnected.""" |
| 240 |
client = AsyncMock() |
| 241 |
monkeypatch.setattr( |
| 242 |
scale_module, "establish_connection", AsyncMock(return_value=client) |
| 243 |
) |
| 244 |
sleep = AsyncMock() |
| 245 |
monkeypatch.setattr(scale_module.asyncio, "sleep", sleep) |
| 246 |
monkeypatch.setattr(scale_module.time, "time", lambda: 110.0) |
| 247 |
device = SimpleNamespace(name="Test Scale", address=_ADDRESS) |
| 248 |
scale = AcaiaScale(device) |
| 249 |
scale.last_disconnect_time = 100.0 |
| 250 |
|
| 251 |
await scale.connect(setup_tasks=False) |
| 252 |
|
| 253 |
assert sleep.await_args_list[0].args == (5.0,) |
| 254 |
assert scale.connected is True |
| 255 |
|
| 256 |
|
| 257 |
async def test_connect_preserves_device_not_found(monkeypatch): |
| 258 |
"""A missing device is reported with the library's specific exception.""" |
| 259 |
monkeypatch.setattr( |
| 260 |
scale_module, |
| 261 |
"establish_connection", |
| 262 |
AsyncMock(side_effect=BleakDeviceNotFoundError(_ADDRESS)), |
| 263 |
) |
| 264 |
device = SimpleNamespace(name="Test Scale", address=_ADDRESS) |
| 265 |
scale = AcaiaScale(device) |
| 266 |
|
| 267 |
with pytest.raises(AcaiaDeviceNotFound): |
| 268 |
await scale.connect(setup_tasks=False) |
| 269 |
|
| 270 |
|
| 271 |
async def test_start_stop_timer_toggles_state(): |
| 272 |
"""start_stop_timer toggles the running state and enqueues commands.""" |
| 273 |
scale = _make_scale() |
| 274 |
scale.connected = True |
| 275 |
|
| 276 |
await scale.start_stop_timer() |
| 277 |
assert scale.timer_running is True |
| 278 |
assert scale._timer_start is not None |
| 279 |
_, payload = scale._queue.get_nowait() |
| 280 |
assert payload == Command.START_TIMER |
| 281 |
|
| 282 |
await scale.start_stop_timer() |
| 283 |
assert scale.timer_running is False |
| 284 |
assert scale._timer_stop is not None |
| 285 |
_, payload = scale._queue.get_nowait() |
| 286 |
assert payload == Command.STOP_TIMER |
| 287 |
|
| 288 |
|
| 289 |
async def test_reset_timer_clears_state_and_enqueues(): |
| 290 |
"""Resetting the timer clears state and enqueues the reset command.""" |
| 291 |
scale = _make_scale() |
| 292 |
scale.connected = True |
| 293 |
scale._timer_start = 100.0 |
| 294 |
scale._timer_stop = 200.0 |
| 295 |
|
| 296 |
await scale.reset_timer() |
| 297 |
|
| 298 |
assert scale._timer_start is None |
| 299 |
assert scale._timer_stop is None |
| 300 |
_, payload = scale._queue.get_nowait() |
| 301 |
assert payload == Command.RESET_TIMER |
| 302 |
|
| 303 |
|
| 304 |
def test_device_disconnected_handler_resets_state(): |
| 305 |
"""Disconnecting resets connection state and notifies.""" |
| 306 |
callback = Mock() |
| 307 |
scale = _make_scale(notify_callback=callback) |
| 308 |
scale.connected = True |
| 309 |
scale.timer_running = True |
| 310 |
|
| 311 |
scale.device_disconnected_handler() |
| 312 |
|
| 313 |
assert scale.connected is False |
| 314 |
assert scale.timer_running is False |
| 315 |
assert scale.last_disconnect_time is not None |
| 316 |
callback.assert_called_once() |