#!/usr/bin/env python3 import os import sys import tempfile import unittest from pathlib import Path from unittest import mock sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from settings import ( # noqa: E402 load_names, load_report_interval_min, save_names, save_report_interval_min, ) class SettingsTests(unittest.TestCase): def test_interval_default(self): with tempfile.TemporaryDirectory() as td: p = Path(td) / "sensors-settings.json" self.assertEqual(load_report_interval_min(p), 30) def test_interval_roundtrip(self): with tempfile.TemporaryDirectory() as td: p = Path(td) / "sensors-settings.json" self.assertEqual(save_report_interval_min(45, p), 45) self.assertEqual(load_report_interval_min(p), 45) def test_interval_clamp(self): with tempfile.TemporaryDirectory() as td: p = Path(td) / "sensors-settings.json" self.assertEqual(save_report_interval_min(0, p), 1) self.assertEqual(save_report_interval_min(999999, p), 65535) def test_names_roundtrip(self): with tempfile.TemporaryDirectory() as td: p = Path(td) / "sensors-names.json" saved = save_names({"aa:bb:cc:dd:ee:01": " Коридор ", "": "x"}, p) self.assertEqual(saved, {"AA:BB:CC:DD:EE:01": "Коридор"}) self.assertEqual(load_names(p), saved) class WritePathLatencyTests(unittest.TestCase): def test_gatt_write_does_not_call_registry_save(self): from gatt import CollectorGatt from registry import Registry reg = Registry(n=4) reg.assign("AA:BB:CC:DD:EE:01") gatt = CollectorGatt(reg) gatt.set_current_addr("AA:BB:CC:DD:EE:01") called = {"save": 0, "write": 0} def on_write(addr, data): called["write"] += 1 reg.update_report(addr, data[0], data[1], data[2] | (data[3] << 8)) gatt.on_write = on_write with mock.patch.object(reg, "save", side_effect=lambda: called.__setitem__("save", called["save"] + 1)): class Char: uuid = "0000a001-0000-1000-8000-00805f9b34fb" gatt.handle_write(Char(), bytearray(b"\x50\x00\x34\x12")) self.assertEqual(called["write"], 1) self.assertEqual(called["save"], 0) if __name__ == "__main__": unittest.main()