"""线架注册模型(80/81 口径:保活/两级绑定/换架接管/冲突防抢占)单元测试。 图解口径(严格): - 已绑定地址: 0x80 保活带绑定 UID -> 收到匹配 81 才在线 - 连续 PANEL_KEEPALIVE_MISS_LIMIT(=2) 次无匹配 81 -> 离线并停止 0x03 读卡 - 重新上线/换机/新注册: 先经 0x10 重下绑定②,再恢复读卡 - 同址不同 UID: 原机在线=冲突不替换;原机离线=自动换架接管 - 未绑定地址: 全 0 的 0x80 探测 -> 收到 81 本地建立绑定①(不发 82/83) """ import sys import os import time from unittest.mock import patch import pytest sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import app as app_module # noqa: E402 from app import app # noqa: E402 def make_cards(port_map): """构造 24 路读卡结果;port_map: {port_id: 'hex12'}""" cards = [] for ant in range(1, 25): hex_str = (port_map.get(ant) or '').lower() cards.append({ 'antenna': ant, 'card_str': hex_str, 'present': bool(hex_str), 'uid': '' if not hex_str else ':'.join(hex_str[i:i + 2] for i in range(0, 12, 2)), }) return cards def read_result(cards, addr=1): """V5 批量读结果(不再包含 panel_uid)。""" return { 'success': True, 'device_address': addr, 'function_code': 3, 'cards': cards, 'raw_data': 'TEST', } class TestPanelRegistration: def setup_method(self): self._saved = { 'stored': dict(app_module.address_config.stored_devices), 'panel_config': dict(app_module.panel_config), 'port_state': dict(app_module.port_state), 'ka_miss': dict(app_module.panel_keepalive_miss), 'synced': set(app_module.panel_mappings_synced), 'conflict': dict(app_module.panel_conflict), 'address_range': app_module.dtu_config.get('address_range'), 'port_mappings': app_module.dtu_config.get('port_mappings'), 'last_seen': dict(app_module.device_last_seen), 'config_addr': dict(app_module._panel_config_addr_state), 'read_fallback': app_module.PANEL_READ_FALLBACK_KEEPALIVE, } self.mock_modbus = patch.object(app_module, 'modbus_client').start() self.mock_save_dev = patch.object(app_module, 'save_device_config').start() self.mock_save_dtu = patch.object(app_module, 'save_dtu_config').start() self.mock_register = patch.object(app_module, 'dtu_register').start() self.mock_panel_status = patch.object(app_module, 'dtu_publish_panel_status').start() # 读卡默认无卡;写卡默认成功(82/83 已废弃,自动流程不再调用 confirm_address) self.mock_modbus.read_all_antenna_cards.return_value = read_result(make_cards({})) self.mock_modbus.set_card_mapping.return_value = {'success': True} app_module.address_config.stored_devices.clear() app_module.panel_config.clear() app_module.port_state.clear() app_module.panel_keepalive_miss.clear() app_module.panel_mappings_synced.clear() app_module.panel_conflict.clear() app_module.device_last_seen.clear() app_module._panel_config_addr_state.update( {'pending_address': None, 'pending_until': None}) def teardown_method(self): patch.stopall() app_module.address_config.stored_devices.clear() app_module.address_config.stored_devices.update(self._saved['stored']) app_module.panel_config.clear() app_module.panel_config.update(self._saved['panel_config']) app_module.port_state.clear() app_module.port_state.update(self._saved['port_state']) app_module.panel_keepalive_miss.clear() app_module.panel_keepalive_miss.update(self._saved['ka_miss']) app_module.panel_mappings_synced.clear() app_module.panel_mappings_synced.update(self._saved['synced']) app_module.panel_conflict.clear() app_module.panel_conflict.update(self._saved['conflict']) app_module.device_last_seen.clear() app_module.device_last_seen.update(self._saved['last_seen']) app_module._panel_config_addr_state.clear() app_module._panel_config_addr_state.update(self._saved['config_addr']) if self._saved['address_range'] is None: app_module.dtu_config.pop('address_range', None) else: app_module.dtu_config['address_range'] = self._saved['address_range'] if self._saved['port_mappings'] is None: app_module.dtu_config.pop('port_mappings', None) else: app_module.dtu_config['port_mappings'] = self._saved['port_mappings'] app_module.PANEL_READ_FALLBACK_KEEPALIVE = self._saved['read_fallback'] def _query_map(self, uid_by_addr): """按地址返回 0x80 查询结果(不在 map 中的地址视为无应答)""" def fake(addr, uid=None, timeout=None): value = uid_by_addr.get(addr) if value is None: return {'error': 'response timeout or too short', 'raw_data': ''} return {'success': True, 'device_address': addr, 'uid': value, 'raw_data': 'TEST'} self.mock_modbus.query_address.side_effect = fake def test_takeover_rebinds_uid_and_inherits_mappings(self): """换架(原机离线): 81 回新 UID -> 重绑地址、保留 panel_id/映射;先 0x10 再读卡,不发 82。""" old_uid = 'a1' * 12 new_uid = 'b2' * 12 pid = 'PANEL_dtu_001_5' app_module.dtu_config['address_range'] = {'start': 5, 'end': 5} app_module.dtu_config['port_mappings'] = {pid: {'3': 'AABBCCDDEEFF'}} app_module.address_config.stored_devices[old_uid] = 5 app_module.panel_config[pid] = {'address': 5, 'position': 5, 'panel_uid': old_uid, 'status': 'offline'} app_module.panel_keepalive_miss[pid] = 2 self._query_map({5: new_uid}) self.mock_modbus.read_all_antenna_cards.return_value = read_result( make_cards({3: 'aabbccddeeff'}), addr=5) app_module._sweep_panel_addresses() devices = app_module.address_config.stored_devices assert devices.get(new_uid) == 5 assert old_uid not in devices assert app_module.panel_config[pid]['panel_uid'] == new_uid assert app_module.panel_config[pid]['status'] == 'online' assert pid not in app_module.panel_keepalive_miss # 82/83 已废弃:自动接管不得发 confirm_address assert self.mock_modbus.confirm_address.called is False # 先 0x10 下发绑定②(继承原面板数据),再读卡 args, _ = self.mock_modbus.set_card_mapping.call_args assert args[0] == 5 assert args[1].get(3) == 'AABBCCDDEEFF' assert self.mock_modbus.read_all_antenna_cards.called assert self.mock_save_dev.called assert self.mock_register.called def test_healthy_query_same_uid_reads_cards(self): """正常轮次: 「地址+绑定 UID」80 -> 匹配 81 -> 0x03 读卡,绑定不变,稳态不再重发 0x10。""" uid = 'aa' * 12 pid = 'PANEL_dtu_001_6' app_module.dtu_config['address_range'] = {'start': 6, 'end': 6} app_module.address_config.stored_devices[uid] = 6 app_module.panel_config[pid] = {'address': 6, 'position': 6, 'panel_uid': uid, 'status': 'online'} app_module.panel_mappings_synced.add(pid) # 本会话已下发过绑定② self._query_map({6: uid}) self.mock_modbus.read_all_antenna_cards.return_value = read_result(make_cards({}), addr=6) app_module._sweep_panel_addresses() assert app_module.address_config.stored_devices == {uid: 6} assert self.mock_modbus.confirm_address.called is False assert self.mock_modbus.set_card_mapping.called is False # 稳态在线不重发 0x10 assert self.mock_modbus.query_address.call_count == 1 query_args, query_kwargs = self.mock_modbus.query_address.call_args assert query_args[0] == 6 assert query_kwargs.get('uid') == uid assert self.mock_modbus.read_all_antenna_cards.called def test_first_online_pushes_mapping_before_read(self): """服务重启后首次匹配 81(cfg=online 但本会话未同步)-> 先 0x10 再读卡。""" uid = 'ad' * 12 pid = 'PANEL_dtu_001_9' app_module.dtu_config['address_range'] = {'start': 9, 'end': 9} app_module.address_config.stored_devices[uid] = 9 app_module.panel_config[pid] = {'address': 9, 'position': 9, 'panel_uid': uid, 'status': 'online'} app_module.dtu_config['port_mappings'] = {pid: {'1': '111111111111'}} self._query_map({9: uid}) self.mock_modbus.read_all_antenna_cards.return_value = read_result(make_cards({}), addr=9) app_module._sweep_panel_addresses() # 下发 0x10 与业务读卡都发生 assert self.mock_modbus.set_card_mapping.called # 顺序:最后一次 set_card_mapping(0x10) 在最后一次业务 read(0x03) 之前 # (_hardware_card_base 取硬件基底的那次 read 不计,它在 set_card_mapping 之前) names = [c[0] for c in self.mock_modbus.method_calls] last_set = len(names) - 1 - names[::-1].index('set_card_mapping') last_read = len(names) - 1 - names[::-1].index('read_all_antenna_cards') assert last_set > names.index('read_all_antenna_cards') assert last_set < last_read def test_one_miss_still_reads_two_miss_offline_stops_read(self): """严格模式:第1次无81仍读卡并计1;连续第2次无81(读卡也失败)判离线、停止读卡。""" app_module.PANEL_READ_FALLBACK_KEEPALIVE = False uid = 'ab' * 12 pid = 'PANEL_dtu_001_7' app_module.dtu_config['address_range'] = {'start': 7, 'end': 7} app_module.address_config.stored_devices[uid] = 7 app_module.panel_config[pid] = {'address': 7, 'position': 7, 'panel_uid': uid, 'status': 'online'} app_module.panel_mappings_synced.add(pid) self.mock_modbus.query_address.return_value = { 'error': 'response timeout or too short', 'raw_data': ''} self.mock_modbus.read_all_antenna_cards.return_value = {'error': 'read timeout'} # 第 1 次:仍在线,本轮仍读卡,计数=1 app_module._sweep_panel_addresses() assert app_module.panel_keepalive_miss[pid] == 1 assert app_module.panel_config[pid]['status'] == 'online' assert self.mock_modbus.read_all_antenna_cards.call_count == 1 # 第 2 次:判离线,停止读卡(读卡调用数不再增加) app_module._sweep_panel_addresses() assert app_module.panel_config[pid]['status'] == 'offline' assert self.mock_modbus.read_all_antenna_cards.call_count == 1 self.mock_panel_status.assert_any_call(pid, 7, None, online=False) def test_fallback_read_ok_keeps_panel_online_without_81(self): """兼容模式(默认开):从不回 81,但 0x03 读卡持续成功 -> 始终在线、不累计离线。""" uid = 'b0' * 12 pid = 'PANEL_dtu_001_20' app_module.dtu_config['address_range'] = {'start': 20, 'end': 20} app_module.address_config.stored_devices[uid] = 20 app_module.panel_config[pid] = {'address': 20, 'position': 20, 'panel_uid': uid, 'status': 'online'} app_module.panel_mappings_synced.add(pid) assert app_module.PANEL_READ_FALLBACK_KEEPALIVE is True self.mock_modbus.query_address.return_value = {'error': 'no 81', 'raw_data': ''} self.mock_modbus.read_all_antenna_cards.return_value = read_result(make_cards({}), addr=20) for _ in range(4): # 远超 2 次阈值 app_module._sweep_panel_addresses() assert app_module.panel_config[pid]['status'] == 'online' assert app_module.panel_keepalive_miss.get(pid, 0) == 0 def test_fallback_read_fail_then_recover_by_read(self): """兼容模式:读卡也连续失败会判离线;之后读卡恢复即救回在线(先 0x10 再处理)。""" uid = 'b1' * 12 pid = 'PANEL_dtu_001_21' app_module.dtu_config['address_range'] = {'start': 21, 'end': 21} app_module.dtu_config['port_mappings'] = {pid: {'1': 'AAAAAAAAAAAAAAAA'}} app_module.address_config.stored_devices[uid] = 21 app_module.panel_config[pid] = {'address': 21, 'position': 21, 'panel_uid': uid, 'status': 'online'} app_module.panel_mappings_synced.add(pid) self.mock_modbus.query_address.return_value = {'error': 'no 81', 'raw_data': ''} # 连续 2 轮读卡也失败 -> 离线 self.mock_modbus.read_all_antenna_cards.return_value = {'error': 'read timeout'} app_module._sweep_panel_addresses() app_module._sweep_panel_addresses() assert app_module.panel_config[pid]['status'] == 'offline' # 第 3 轮:81 仍缺失,但读卡恢复 -> 兼容救回在线 self.mock_modbus.read_all_antenna_cards.return_value = read_result(make_cards({}), addr=21) app_module._sweep_panel_addresses() assert app_module.panel_config[pid]['status'] == 'online' assert app_module.panel_keepalive_miss.get(pid, 0) == 0 # 离线恢复先经 0x10 重下绑定② assert self.mock_modbus.set_card_mapping.called def test_offline_keeps_polling_80_but_never_reads(self): """严格模式:已离线机继续发带 UID 的 80 探测恢复,但在收到匹配 81 前不再读卡。""" app_module.PANEL_READ_FALLBACK_KEEPALIVE = False uid = 'ae' * 12 pid = 'PANEL_dtu_001_10' app_module.dtu_config['address_range'] = {'start': 10, 'end': 10} app_module.address_config.stored_devices[uid] = 10 app_module.panel_config[pid] = {'address': 10, 'position': 10, 'panel_uid': uid, 'status': 'offline'} app_module.panel_keepalive_miss[pid] = 2 self.mock_modbus.query_address.return_value = {'error': 'timeout', 'raw_data': ''} app_module._sweep_panel_addresses() assert self.mock_modbus.query_address.call_count == 1 assert self.mock_modbus.query_address.call_args.kwargs.get('uid') == uid assert self.mock_modbus.read_all_antenna_cards.called is False assert app_module.panel_config[pid]['status'] == 'offline' def test_recovery_pushes_mapping_then_reads(self): """离线后重新收到匹配 81 -> 恢复在线;先 0x10 重下绑定②再读卡,查询仍带绑定 UID。""" uid = 'c3' * 12 pid = 'PANEL_dtu_001_2' app_module.dtu_config['address_range'] = {'start': 2, 'end': 2} app_module.dtu_config['port_mappings'] = {pid: {'2': '222222222222'}} app_module.address_config.stored_devices[uid] = 2 app_module.panel_config[pid] = {'address': 2, 'position': 2, 'panel_uid': uid, 'status': 'offline'} app_module.panel_keepalive_miss[pid] = 2 self._query_map({2: uid}) self.mock_modbus.read_all_antenna_cards.return_value = read_result(make_cards({}), addr=2) app_module._sweep_panel_addresses() assert app_module.address_config.stored_devices == {uid: 2} assert app_module.panel_config[pid]['status'] == 'online' assert pid not in app_module.panel_keepalive_miss assert self.mock_modbus.query_address.call_count == 1 assert self.mock_modbus.query_address.call_args.kwargs.get('uid') == uid # 重新上线先 0x10 再业务读卡(基底 read 不计) names = [c[0] for c in self.mock_modbus.method_calls] last_set = len(names) - 1 - names[::-1].index('set_card_mapping') last_read = len(names) - 1 - names[::-1].index('read_all_antenna_cards') assert last_set > names.index('read_all_antenna_cards') assert last_set < last_read def test_unbound_probe_registers_new_panel_without_confirm(self): """未绑定地址全 0 探测收到 81 -> 本地建立绑定①并上线;不发 82,先 0x10 再读卡。""" new_uid = 'd4' * 12 app_module.dtu_config['address_range'] = {'start': 4, 'end': 4} self._query_map({4: new_uid}) self.mock_modbus.read_all_antenna_cards.return_value = read_result(make_cards({}), addr=4) app_module._sweep_panel_addresses() assert app_module.address_config.stored_devices.get(new_uid) == 4 assert 'PANEL_dtu_001_4' in app_module.panel_config assert self.mock_modbus.confirm_address.called is False # 注册时探测用全 0 assert self.mock_modbus.query_address.call_args.kwargs.get('uid') is None assert self.mock_save_dev.called def test_offline_panel_still_probes_unbound(self): """严格模式:即使有绑定线架离线,地址段内未绑定地址仍照常全 0 顺序探测。""" app_module.PANEL_READ_FALLBACK_KEEPALIVE = False old_uid = 'e5' * 12 pid = 'PANEL_dtu_001_2' app_module.dtu_config['address_range'] = {'start': 2, 'end': 3} app_module.address_config.stored_devices[old_uid] = 2 app_module.panel_config[pid] = {'address': 2, 'position': 2, 'panel_uid': old_uid, 'status': 'offline'} app_module.panel_keepalive_miss[pid] = 2 self._query_map({}) # 所有地址无应答 self.mock_modbus.read_all_antenna_cards.return_value = {'error': 'timeout'} app_module._sweep_panel_addresses() probed = [c.args[0] for c in self.mock_modbus.query_address.call_args_list] # 绑定地址 2 带 UID 查询,未绑定地址 3 也必须探测(顺序 2、3) assert probed == [2, 3] assert self.mock_modbus.query_address.call_args_list[0].kwargs.get('uid') == old_uid assert self.mock_modbus.query_address.call_args_list[1].kwargs.get('uid') is None # 离线机不读卡 assert self.mock_modbus.read_all_antenna_cards.called is False def test_keepalive_miss_limit_marks_offline(self): """连续 PANEL_KEEPALIVE_MISS_LIMIT 次无匹配 81 -> 离线并发布离线状态。""" uid = 'f6' * 12 pid = 'PANEL_dtu_001_3' app_module.dtu_config['address_range'] = {'start': 3, 'end': 3} app_module.address_config.stored_devices[uid] = 3 app_module.panel_config[pid] = {'address': 3, 'position': 3, 'panel_uid': uid, 'status': 'online'} app_module.panel_mappings_synced.add(pid) self.mock_modbus.query_address.return_value = {'error': 'timeout'} self.mock_modbus.read_all_antenna_cards.return_value = {'error': 'timeout'} for _ in range(app_module.PANEL_KEEPALIVE_MISS_LIMIT): app_module._sweep_panel_addresses() assert app_module.panel_config[pid]['status'] == 'offline' assert app_module.panel_keepalive_miss[pid] == app_module.PANEL_KEEPALIVE_MISS_LIMIT self.mock_panel_status.assert_any_call(pid, 3, None, online=False) def test_conflict_does_not_replace_while_old_online(self): """原机仍在线(首次探测到不同 UID,原机未离线)-> 冲突:不替换/不下发/不读卡。""" old_uid = '11' * 12 new_uid = '22' * 12 pid = 'PANEL_dtu_001_11' app_module.dtu_config['address_range'] = {'start': 11, 'end': 11} app_module.address_config.stored_devices[old_uid] = 11 app_module.panel_config[pid] = {'address': 11, 'position': 11, 'panel_uid': old_uid, 'status': 'online'} app_module.dtu_config['port_mappings'] = {pid: {'1': '333333333333'}} self._query_map({11: new_uid}) # 同地址回了不同 UID,原机计数=0(仍在线) app_module._sweep_panel_addresses() # 绑定①不变 assert app_module.address_config.stored_devices.get(old_uid) == 11 assert new_uid not in app_module.address_config.stored_devices assert app_module.panel_config[pid]['panel_uid'] == old_uid # 记冲突 assert app_module.panel_conflict.get(pid) == new_uid # 不下发绑定②、不读卡 assert self.mock_modbus.set_card_mapping.called is False assert self.mock_modbus.read_all_antenna_cards.called is False assert app_module.panel_keepalive_miss[pid] == 1 def test_conflict_then_old_offline_triggers_takeover(self): """冲突中:新 UID 持续应答、原机连续2次无匹配81 -> 第2次离线后立即接管新 UID。""" old_uid = '44' * 12 new_uid = '55' * 12 pid = 'PANEL_dtu_001_12' app_module.dtu_config['address_range'] = {'start': 12, 'end': 12} app_module.address_config.stored_devices[old_uid] = 12 app_module.panel_config[pid] = {'address': 12, 'position': 12, 'panel_uid': old_uid, 'status': 'online'} app_module.dtu_config['port_mappings'] = {pid: {'1': '666666666666'}} self._query_map({12: new_uid}) self.mock_modbus.read_all_antenna_cards.return_value = read_result(make_cards({}), addr=12) app_module._sweep_panel_addresses() # 第1次:冲突,原机 miss=1 assert app_module.panel_config[pid]['panel_uid'] == old_uid app_module._sweep_panel_addresses() # 第2次:原机离线 -> 接管新 UID assert app_module.address_config.stored_devices.get(new_uid) == 12 assert old_uid not in app_module.address_config.stored_devices assert app_module.panel_config[pid]['panel_uid'] == new_uid assert app_module.panel_config[pid]['status'] == 'online' assert pid not in app_module.panel_conflict assert self.mock_modbus.set_card_mapping.called # 接管先 0x10 def test_pending_config_address_probed_even_when_offline(self): """配置地址后的新地址优先全 0 探测(即使有其他绑定线架离线)。""" old_uid = 'e6' * 12 new_uid = 'f7' * 12 pid = 'PANEL_dtu_001_2' app_module.dtu_config['address_range'] = {'start': 2, 'end': 8} app_module.address_config.stored_devices[old_uid] = 2 app_module.panel_config[pid] = {'address': 2, 'position': 2, 'panel_uid': old_uid, 'status': 'offline'} app_module.panel_keepalive_miss[pid] = 2 app_module._panel_config_addr_state['pending_address'] = 8 app_module._panel_config_addr_state['pending_until'] = time.time() + 60 self._query_map({8: new_uid}) self.mock_modbus.read_all_antenna_cards.return_value = read_result(make_cards({}), addr=8) app_module._sweep_panel_addresses() assert app_module.address_config.stored_devices.get(new_uid) == 8 assert app_module._panel_config_addr_state['pending_address'] is None def test_panel_unbind_api(self): """解绑 API: 移除绑定与面板配置。""" client = app.test_client() uid = '99' * 12 pid = 'PANEL_dtu_001_7' app_module.address_config.stored_devices[uid] = 7 app_module.panel_config[pid] = {'address': 7, 'position': 7, 'panel_uid': uid, 'status': 'online'} resp = client.post('/api/panel/unbind', json={'address': 7}) data = resp.get_json() assert resp.status_code == 200 and data['success'] assert uid not in app_module.address_config.stored_devices assert pid not in app_module.panel_config assert self.mock_save_dev.called def test_query_address_api(self): """V5 查询 API: 返回线架 UID 与原始帧。""" client = app.test_client() self.mock_modbus.query_address.return_value = { 'success': True, 'device_address': 5, 'uid': 'aa' * 12, 'raw_data': 'TEST'} with patch.object(app_module, '_serial_connected', return_value=True): resp = client.post('/api/modbus/query_address', json={'address': 5}) data = resp.get_json() assert resp.status_code == 200 assert data['success'] is True assert data['uid'] == 'aa' * 12 assert self.mock_modbus.query_address.call_args[0][0] == 5 def test_confirm_address_api_bind(self): """V5 确认 API: bind=true 时同时写入本地绑定表。""" client = app.test_client() uid = 'ab' * 12 self.mock_modbus.confirm_address.return_value = {'success': True, 'uid': uid, 'raw_data': 'TEST'} with patch.object(app_module, '_serial_connected', return_value=True): resp = client.post('/api/modbus/confirm_address', json={'address': 6, 'uid': uid, 'bind': True}) data = resp.get_json() assert resp.status_code == 200 and data['success'] is True assert app_module.address_config.stored_devices.get(uid) == 6 assert self.mock_save_dev.called def test_config_address_api_requires_serial(self): """串口未连接时配置地址接口返回 400。""" client = app.test_client() with patch.object(app_module, '_serial_connected', return_value=False): resp = client.post('/api/panel/config_address', json={}) assert resp.status_code == 400 assert resp.get_json()['success'] is False def test_config_address_status_api(self): client = app.test_client() resp = client.get('/api/panel/config_address_status') data = resp.get_json() assert resp.status_code == 200 and data['success'] is True assert 'config' in data def test_update_dtu_config_address_range(self): """DTU 配置 API: 地址段写入并校验。""" client = app.test_client() resp = client.post('/api/dtu/config', json={'address_range': {'start': 5, 'end': 60}}) assert resp.status_code == 200 assert app_module.dtu_config['address_range'] == {'start': 5, 'end': 60} assert self.mock_save_dtu.called resp = client.post('/api/dtu/config', json={'address_range': {'start': 70, 'end': 10}}) assert resp.status_code == 400 assert app_module.dtu_config['address_range'] == {'start': 5, 'end': 60} def test_address_range_fallback(self): app_module.dtu_config['address_range'] = {'start': 60, 'end': 10} assert app_module._address_range() == (1, 50) app_module.dtu_config['address_range'] = {'start': 3, 'end': 9} assert app_module._address_range() == (3, 9) app_module.dtu_config['address_range'] = None assert app_module._address_range() == (1, 50) def test_single_port_write_persists_only_target_port(self): """单端口写卡:硬件帧带全 24 口,但配置只落目标这一条(修复映射污染)。""" client = app.test_client() pid = 'PANEL_dtu_001_8' app_module.panel_config[pid] = {'address': 8, 'position': 8, 'panel_uid': 'cc' * 12, 'status': 'online'} app_module.dtu_config['port_mappings'] = {} # 硬件基底:4/22/23 口插着卡(这些只应出现在下发帧,不应落盘) self.mock_modbus.read_all_antenna_cards.return_value = read_result( make_cards({4: '04' * 6, 22: '16' * 6, 23: '17' * 6}), addr=8) # set_card_mapping 回 24 路 cards_written(模拟真实实现) written = {p: None for p in range(1, 25)} written[1] = 'aabbccddeeff' written[4] = '040404040404' written[22] = '161616161616' written[23] = '171717171717' self.mock_modbus.set_card_mapping.return_value = { 'success': True, 'device_address': 8, 'cards_written': written, 'raw_data': 'T'} with patch.object(app_module.serial_client, 'get_status', return_value={'connected': True}): resp = client.post('/api/modbus/set_card_mapping', json={'device_address': 8, 'port_id': 1, 'card_uid': 'AABBCCDDEEFF'}) assert resp.status_code == 200 and resp.get_json()['success'] saved = app_module.dtu_config['port_mappings'][pid] # 只落目标 1 口;硬件基底里的 4/22/23 不得被灌进配置,也不得出现 null assert saved == {'1': 'AABBCCDDEEFF'} # 下发帧仍带全部端口(目标口是新卡号,其它保留硬件读回值) args, _ = self.mock_modbus.set_card_mapping.call_args assert args[1][1] == 'AABBCCDDEEFF' assert args[1][4] == '040404040404' assert self.mock_save_dtu.called def test_single_port_clear_deletes_mapping_key(self): """单端口清除:删除该端口配置键(不写 null),硬件帧目标口发 None。""" client = app.test_client() pid = 'PANEL_dtu_001_8' app_module.panel_config[pid] = {'address': 8, 'position': 8, 'panel_uid': 'cc' * 12, 'status': 'online'} app_module.dtu_config['port_mappings'] = {pid: {'1': 'AABBCCDDEEFF', '2': '222222222222'}} self.mock_modbus.read_all_antenna_cards.return_value = read_result(make_cards({}), addr=8) self.mock_modbus.set_card_mapping.return_value = { 'success': True, 'device_address': 8, 'cards_written': {p: None for p in range(1, 25)}, 'raw_data': 'T'} with patch.object(app_module.serial_client, 'get_status', return_value={'connected': True}): resp = client.post('/api/modbus/set_card_mapping', json={'device_address': 8, 'port_id': 1, 'card_uid': None}) assert resp.status_code == 200 and resp.get_json()['success'] saved = app_module.dtu_config['port_mappings'][pid] assert '1' not in saved and saved.get('2') == '222222222222' args, _ = self.mock_modbus.set_card_mapping.call_args assert args[1][1] is None # 硬件目标口清成 0xFF def test_prune_null_port_mappings(self): """启动清理:删除 null/空端口,保留有效卡号;面板清空后整组移除。""" app_module.dtu_config['port_mappings'] = { 'PANEL_dtu_001_1': {'1': 'AABBCCDDEEFF', '5': None, '10': ''}, 'PANEL_dtu_001_4': {str(i): None for i in range(1, 24)} | {'24': 'DDAD57F95002'}, 'PANEL_dtu_001_9': {'1': None, '2': None}, } removed = app_module._prune_null_port_mappings() pm = app_module.dtu_config['port_mappings'] assert removed == 27 # 2(面板1)+ 23(面板4 的 1..23)+ 2(面板9) assert pm['PANEL_dtu_001_1'] == {'1': 'AABBCCDDEEFF'} assert pm['PANEL_dtu_001_4'] == {'24': 'DDAD57F95002'} assert 'PANEL_dtu_001_9' not in pm def test_clear_panel_mappings_api(self): """清空面板映射 API:删配置+在线时硬件 24 口清成 None,不影响绑定①。""" client = app.test_client() uid = '77' * 12 pid = 'PANEL_dtu_001_7' app_module.address_config.stored_devices[uid] = 7 app_module.panel_config[pid] = {'address': 7, 'position': 7, 'panel_uid': uid, 'status': 'online'} app_module.dtu_config['port_mappings'] = {pid: {'1': '111111111111', '3': '222222222222'}} self.mock_modbus.set_card_mapping.return_value = {'success': True} with patch.object(app_module.serial_client, 'get_status', return_value={'connected': True}): resp = client.post('/api/panel/clear_mappings', json={'address': 7}) data = resp.get_json() assert resp.status_code == 200 and data['success'] assert data['removed'] == 2 assert pid not in app_module.dtu_config['port_mappings'] # 绑定①保留 assert app_module.address_config.stored_devices.get(uid) == 7 # 硬件整帧清空 args, _ = self.mock_modbus.set_card_mapping.call_args assert args[0] == 7 and all(v is None for v in args[1].values()) def test_mapping_upsert_and_delete_api(self): """映射管理:新增落单口并在线下发;删除移除键且硬件目标口 None。""" client = app.test_client() uid = '88' * 12 pid = 'PANEL_dtu_001_6' app_module.address_config.stored_devices[uid] = 6 app_module.panel_config[pid] = {'address': 6, 'position': 6, 'panel_uid': uid, 'status': 'online'} app_module.dtu_config['port_mappings'] = {} self.mock_modbus.read_all_antenna_cards.return_value = read_result(make_cards({}), addr=6) self.mock_modbus.set_card_mapping.return_value = {'success': True} serial_ok = patch.object(app_module.serial_client, 'get_status', return_value={'connected': True}) serial_ok.start() try: # 新增端口 3 resp = client.post('/api/panel/mapping', json={'address': 6, 'port': 3, 'card_uid': 'aabbccddeeff'}) d = resp.get_json() assert resp.status_code == 200 and d['success'] and d['action'] == 'set' assert app_module.dtu_config['port_mappings'][pid] == {'3': 'AABBCCDDEEFF'} # 下发帧目标口为新卡号(规范化大写) args, _ = self.mock_modbus.set_card_mapping.call_args assert args[1][3] == 'AABBCCDDEEFF' # 非法卡号被拒 bad = client.post('/api/panel/mapping', json={'address': 6, 'port': 4, 'card_uid': 'zz'}) assert bad.status_code == 400 # 删除端口 3 resp = client.post('/api/panel/mapping', json={'address': 6, 'port': 3, 'card_uid': None}) d = resp.get_json() assert resp.status_code == 200 and d['action'] == 'delete' assert '3' not in app_module.dtu_config['port_mappings'].get(pid, {}) args, _ = self.mock_modbus.set_card_mapping.call_args assert args[1][3] is None finally: serial_ok.stop() def test_mappings_list_includes_unbound_residual(self): """映射列表:包含已注册面板和有残留映射的未注册面板。""" client = app.test_client() uid = '5a' * 12 pid1 = 'PANEL_dtu_001_2' app_module.address_config.stored_devices[uid] = 2 app_module.panel_config[pid1] = {'address': 2, 'position': 2, 'panel_uid': uid, 'status': 'online'} app_module.dtu_config['port_mappings'] = { pid1: {'1': '111111111111'}, 'PANEL_dtu_001_9': {'5': '555555555555', '7': None}, } resp = client.get('/api/panel/mappings') d = resp.get_json() assert resp.status_code == 200 and d['success'] by_id = {g['panel_id']: g for g in d['panels']} assert by_id[pid1]['registered'] is True assert by_id[pid1]['mappings'] == [{'port': 1, 'uid': '111111111111'}] g9 = by_id['PANEL_dtu_001_9'] assert g9['registered'] is False and g9['address'] == 9 # null 条目在列表里归一为 None(仍可见,便于清理) assert {m['port']: m['uid'] for m in g9['mappings']} == {5: '555555555555', 7: None} if __name__ == '__main__': pytest.main([__file__, '-v'])