#!/usr/bin/env python3 """ AeroTrack LAN Sync Server 自动化测试套件 全面覆盖物理药瓶生命周期、多设备协同、开新瓶、软删除墓碑恢复、跨时区与防覆盖保护。 """ import unittest import os import sys import json import time import socket import tempfile import urllib.request import threading import datetime # 动态引入 server 模块 sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import server def get_free_port(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('127.0.0.1', 0)) port = s.getsockname()[1] s.close() return port class ServerIntegrationTestCase(unittest.TestCase): @classmethod def setUpClass(cls): # 使用独立的临时数据库进行隔离测试 cls.temp_dir = tempfile.TemporaryDirectory() cls.test_db = os.path.join(cls.temp_dir.name, 'test_aerotrack.db') server.DB_FILE = cls.test_db server.init_db() cls.port = get_free_port() server.server_address = ('127.0.0.1', cls.port) cls.httpd = server.ThreadedHTTPServer(('127.0.0.1', cls.port), server.SyncHandler) cls.thread = threading.Thread(target=cls.httpd.serve_forever, daemon=True) cls.thread.start() time.sleep(0.5) @classmethod def tearDownClass(cls): cls.httpd.shutdown() cls.httpd.server_close() cls.temp_dir.cleanup() def _post_json(self, path, data): url = f"http://127.0.0.1:{self.port}{path}" req = urllib.request.Request( url, data=json.dumps(data).encode('utf-8'), headers={'Content-Type': 'application/json; charset=utf-8'} ) with urllib.request.urlopen(req, timeout=3) as resp: self.assertEqual(resp.status, 200) return json.loads(resp.read().decode('utf-8')) def _get(self, path): url = f"http://127.0.0.1:{self.port}{path}" with urllib.request.urlopen(url, timeout=3) as resp: return resp.status, resp.read() def test_01_init_db_schema_and_seed(self): """测试 1: 验证数据库表结构完整性与初始药瓶种子自动生成""" conn = server.get_db() bottles = conn.execute("SELECT * FROM bottles ORDER BY sequence_number ASC").fetchall() self.assertEqual(len(bottles), 2) flix_b1 = [b for b in bottles if b['canister_id'] == 'flixotide_primary'][0] self.assertEqual(flix_b1['sequence_number'], 1) self.assertEqual(flix_b1['total_doses'], 60) self.assertEqual(flix_b1['remaining_doses'], 60) self.assertEqual(flix_b1['is_active'], 1) cols = [r['name'] for r in conn.execute("PRAGMA table_info(dose_records)").fetchall()] self.assertIn('flixotide_bottle_id', cols) self.assertIn('ventolin_bottle_id', cols) self.assertIn('is_deleted', cols) self.assertIn('updated_at', cols) conn.close() def test_02_ping_api(self): """测试 2: 验证 /api/v1/ping 接口正常连通""" status, body = self._get('/api/v1/ping') self.assertEqual(status, 200) data = json.loads(body.decode('utf-8')) self.assertEqual(data.get('status'), 'ok') def test_03_sync_status_api(self): """测试 3: 验证 /api/v1/sync/status 接口返回完整的药瓶与方案状态""" status, body = self._get('/api/v1/sync/status') self.assertEqual(status, 200) data = json.loads(body.decode('utf-8')) self.assertEqual(data.get('status'), 'online') self.assertIn('bottles', data) self.assertIn('canisters', data) self.assertIn('devices', data) def test_04_device_a_inhalation_deduction(self): """测试 4: 设备 A 吸入 2 喷,服务端精准核算余量 (60 -> 58)""" res = self._post_json('/api/v1/sync', { 'device_name': '妈妈手机', 'device_id': 'dev_phone_a', 'bottles': [], 'records': [ { 'id': 'rec_dose_01', 'startTime': '2026-10-28T05:00:00Z', 'endTime': '2026-10-28T05:01:00Z', 'flixotidePuffs': 2, 'ventolinPuffs': 0, 'flixotideBottleId': 'flix_b1_initial', 'isDeleted': False, 'updatedAt': '2026-10-28T05:01:00Z' } ], 'canisters': [] }) b1 = [b for b in res['bottles'] if b['id'] == 'flix_b1_initial'][0] self.assertEqual(b1['remainingDoses'], 58) can = [c for c in res['canisters'] if c['id'] == 'flixotide_primary'][0] self.assertEqual(can['remainingDoses'], 58) def test_05_device_b_syncs_and_sees_deduction(self): """测试 5: 设备 B 首次同步,拉取到真实余量 58 喷,不被本地空状态冲刷""" res = self._post_json('/api/v1/sync', { 'device_name': '爸爸手机', 'device_id': 'dev_phone_b', 'bottles': [], 'records': [], 'canisters': [] }) b1 = [b for b in res['bottles'] if b['id'] == 'flix_b1_initial'][0] self.assertEqual(b1['remainingDoses'], 58) self.assertEqual(len(res['records']), 1) def test_06_device_a_opens_new_bottle_2(self): """测试 6: 设备 A 点击【开新瓶】,激活第 2 瓶,第 1 瓶归档,余量刷新为 60 喷""" now_utc = (datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(minutes=1)).isoformat() res = self._post_json('/api/v1/sync', { 'device_name': '妈妈手机', 'device_id': 'dev_phone_a', 'bottles': [ { 'id': 'flix_b1_initial', 'canisterId': 'flixotide_primary', 'name': '辅舒酮', 'sequenceNumber': 1, 'totalDoses': 60, 'openedAt': '2020-01-01T00:00:00Z', 'finishedAt': now_utc, 'isActive': False, 'openedByDevice': '系统初始化', 'updatedAt': now_utc }, { 'id': 'flix_b2_uuid_test', 'canisterId': 'flixotide_primary', 'name': '辅舒酮', 'sequenceNumber': 2, 'totalDoses': 60, 'openedAt': now_utc, 'isActive': True, 'openedByDevice': '妈妈手机', 'updatedAt': now_utc } ], 'records': [], 'canisters': [] }) b2 = [b for b in res['bottles'] if b['id'] == 'flix_b2_uuid_test'][0] self.assertEqual(b2['sequenceNumber'], 2) self.assertEqual(b2['isActive'], True) self.assertEqual(b2['remainingDoses'], 60) # 方案主表自动切换为当前活跃瓶的 60 喷 can = [c for c in res['canisters'] if c['id'] == 'flixotide_primary'][0] self.assertEqual(can['remainingDoses'], 60) def test_07_device_b_syncs_and_automatically_switches_to_bottle_2(self): """测试 7: 设备 B 同步后自动切换至第 2 瓶,首页对齐为满瓶 60 喷""" res = self._post_json('/api/v1/sync', { 'device_name': '爸爸手机', 'device_id': 'dev_phone_b', 'bottles': [], 'records': [], 'canisters': [] }) active_flix = [b for b in res['bottles'] if b['canisterId'] == 'flixotide_primary' and b['isActive']][0] self.assertEqual(active_flix['id'], 'flix_b2_uuid_test') self.assertEqual(active_flix['sequenceNumber'], 2) self.assertEqual(active_flix['remainingDoses'], 60) def test_08_device_b_inhalation_on_bottle_2(self): """测试 8: 设备 B 在第 2 瓶上吸入 2 喷,准确扣减第 2 瓶 (60 -> 58)""" res = self._post_json('/api/v1/sync', { 'device_name': '爸爸手机', 'device_id': 'dev_phone_b', 'bottles': [], 'records': [ { 'id': 'rec_dose_02', 'startTime': '2026-10-28T06:10:00Z', 'endTime': '2026-10-28T06:11:00Z', 'flixotidePuffs': 2, 'ventolinPuffs': 0, 'flixotideBottleId': 'flix_b2_uuid_test', 'isDeleted': False, 'updatedAt': '2026-10-28T06:11:00Z' } ], 'canisters': [] }) b2 = [b for b in res['bottles'] if b['id'] == 'flix_b2_uuid_test'][0] self.assertEqual(b2['remainingDoses'], 58) can = [c for c in res['canisters'] if c['id'] == 'flixotide_primary'][0] self.assertEqual(can['remainingDoses'], 58) def test_09_soft_delete_tombstone_restores_dose(self): """测试 9: 设备 B 软删除误操作流水,全网标记 is_deleted=1,喷数自动恢复至 60""" res = self._post_json('/api/v1/sync', { 'device_name': '爸爸手机', 'device_id': 'dev_phone_b', 'bottles': [], 'records': [ { 'id': 'rec_dose_02', 'isDeleted': True, 'updatedAt': '2026-10-28T06:15:00Z' } ], 'canisters': [] }) b2 = [b for b in res['bottles'] if b['id'] == 'flix_b2_uuid_test'][0] self.assertEqual(b2['remainingDoses'], 60) # 准确恢复为 60 喷 can = [c for c in res['canisters'] if c['id'] == 'flixotide_primary'][0] self.assertEqual(can['remainingDoses'], 60) def test_10_outdated_device_cannot_overwrite_server_truth(self): """测试 10: 离线超期设备拿着旧的 40 喷快照上线,服务端拒绝被其覆盖""" res = self._post_json('/api/v1/sync', { 'device_name': '爷爷旧手机', 'device_id': 'dev_phone_c', 'bottles': [], 'records': [], 'canisters': [ { 'id': 'flixotide_primary', 'totalDoses': 60, 'remainingDoses': 40 } ] }) can = [c for c in res['canisters'] if c['id'] == 'flixotide_primary'][0] self.assertEqual(can['remainingDoses'], 60) # 维持权威真值,不被 40 冲刷 def test_11_dashboard_and_web_serving(self): """测试 11: 监控看板 HTML 渲染正常,包含物理药瓶档案表""" status, body = self._get('/dashboard') self.assertEqual(status, 200) html = body.decode('utf-8') self.assertIn('AeroTrack 局域网多设备同步服务器', html) self.assertIn('物理药瓶开封与换瓶档案', html) self.assertIn('第 2 瓶', html) def test_12_medicine_lookup_api(self): """测试 12: 药品条码/追溯码在线快速检索 API""" status, body = self._get('/api/v1/medicine/lookup?code=6925567800018') self.assertEqual(status, 200) res = json.loads(body.decode('utf-8')) self.assertEqual(res['status'], 'ok') self.assertIn('美林', res['data']['name']) self.assertEqual(res['data']['spec'], '100ml:2g') def test_13_family_medicine_sync_and_tombstone(self): """测试 13: 家庭药箱多设备双向同步与开封/删除""" # 设备 A 上报录入美林和滴眼液 res_a = self._post_json('/api/v1/sync', { 'device_name': '妈妈手机', 'device_id': 'dev_phone_mom', 'medicines': [ { 'id': 'med_test_meilin', 'name': '美林 (布洛芬混悬液)', 'category': 'oralLiquid', 'spec': '100ml', 'storageLocation': '常温药箱', 'targetUser': '宝宝', 'expiryDate': '2027-10-31T00:00:00Z', 'shelfLifeDaysAfterOpening': 60, 'isOpened': False, 'updatedAt': '2026-10-28T07:00:00Z' } ] }) self.assertIn('medicines', res_a) meds = res_a['medicines'] meilin = [m for m in meds if m['id'] == 'med_test_meilin'][0] self.assertEqual(meilin['name'], '美林 (布洛芬混悬液)') self.assertFalse(meilin['isOpened']) # 设备 B 同步并将美林标记开封打卡 res_b = self._post_json('/api/v1/sync', { 'device_name': '爸爸手机', 'device_id': 'dev_phone_dad', 'medicines': [ { 'id': 'med_test_meilin', 'name': '美林 (布洛芬混悬液)', 'category': 'oralLiquid', 'expiryDate': '2027-10-31T00:00:00Z', 'shelfLifeDaysAfterOpening': 60, 'isOpened': True, 'openedAt': '2026-10-28T07:30:00Z', 'openedByDevice': '爸爸手机', 'updatedAt': '2026-10-28T07:30:00Z' } ] }) meilin_b = [m for m in res_b['medicines'] if m['id'] == 'med_test_meilin'][0] self.assertTrue(meilin_b['isOpened']) self.assertEqual(meilin_b['openedByDevice'], '爸爸手机') # 监控看板中应包含家庭药箱信息 status, body = self._get('/dashboard') self.assertEqual(status, 200) html = body.decode('utf-8') self.assertIn('家庭智能药箱健康与保质期监控', html) self.assertIn('美林', html) if __name__ == '__main__': unittest.main()