test: 增加全链路多设备同步与药瓶生命周期自动化测试套件

This commit is contained in:
shen
2026-10-27 22:58:46 -07:00
parent 89ab13ecf5
commit ba32e29682
4 changed files with 712 additions and 2 deletions
+19 -2
View File
@@ -128,6 +128,19 @@ def init_db():
conn.execute("UPDATE dose_records SET flixotide_bottle_id = 'flix_b1_initial' WHERE flixotide_puffs > 0 AND flixotide_bottle_id IS NULL")
conn.execute("UPDATE dose_records SET ventolin_bottle_id = 'vent_b1_initial' WHERE ventolin_puffs > 0 AND ventolin_bottle_id IS NULL")
conn.execute("UPDATE dose_records SET updated_at = ? WHERE updated_at IS NULL", (now_iso,))
# 6. 若 canisters 为空,初始化基础配置
canister_count = conn.execute('SELECT COUNT(*) as c FROM canisters').fetchone()['c']
if canister_count == 0:
now_iso = datetime.datetime.now(datetime.timezone.utc).isoformat()
conn.execute('''
INSERT INTO canisters (id, name, total_doses, remaining_doses, opened_at, is_enabled, puffs_per_session, inhalation_seconds, is_steroid, sort_order, note, updated_at)
VALUES ('ventolin_primary', '万托林 (硫酸沙丁胺醇)', 200, 200, '2020-01-01T00:00:00Z', 1, 2, 15, 0, 1, '支气管舒张剂', ?)
''', (now_iso,))
conn.execute('''
INSERT INTO canisters (id, name, total_doses, remaining_doses, opened_at, is_enabled, puffs_per_session, inhalation_seconds, is_steroid, sort_order, note, updated_at)
VALUES ('flixotide_primary', '辅舒酮 (丙酸氟替卡松)', 60, 60, '2020-01-01T00:00:00Z', 1, 2, 15, 1, 2, '糖皮质激素', ?)
''', (now_iso,))
conn.close()
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
@@ -379,9 +392,13 @@ class SyncHandler(SimpleHTTPRequestHandler):
rem = max(0, td - consumed)
conn.execute('UPDATE bottles SET remaining_doses = ? WHERE id = ?', (rem, bid))
# 若是当前在用活跃瓶,同步更新 canisters 方案余量
# 若是当前在用活跃瓶,同步确保并更新 canisters 方案余量
if b['is_active']:
conn.execute('UPDATE canisters SET remaining_doses = ?, opened_at = ? WHERE id = ?', (rem, b['opened_at'], cid))
conn.execute('''
INSERT INTO canisters (id, name, total_doses, remaining_doses, opened_at, is_enabled, puffs_per_session, inhalation_seconds, is_steroid, sort_order, note, updated_at)
VALUES (?, ?, ?, ?, ?, 1, 2, 15, ?, 1, '', ?)
ON CONFLICT(id) DO UPDATE SET remaining_doses = excluded.remaining_doses, opened_at = excluded.opened_at
''', (cid, b['name'], td, rem, b['opened_at'], is_steroid, now_str))
# 6. 汇总全量数据响应客户端
all_records = []
+274
View File
@@ -0,0 +1,274 @@
#!/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
# 动态引入 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 = '2026-10-28T06:00:00Z'
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)
if __name__ == '__main__':
unittest.main()
+210
View File
@@ -0,0 +1,210 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:uuid/uuid.dart';
import 'package:aero_track/models/bottle.dart';
import 'package:aero_track/models/canister.dart';
import 'package:aero_track/models/dose_record.dart';
import 'package:aero_track/services/storage_service.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
setUp(() {
SharedPreferences.setMockInitialValues({});
});
group('StorageService & Bottle Lifecycle Tests', () {
test('1. 初始化时自动创建第 1 瓶 (Bottle #1) 且初始余量满喷', () async {
final storage = await StorageService.init();
final bottles = storage.getBottles();
expect(bottles.length, 2);
final flixBottle = storage.getActiveFlixotideBottle();
expect(flixBottle, isNotNull);
expect(flixBottle!.sequenceNumber, 1);
expect(flixBottle.totalDoses, 60);
expect(flixBottle.isActive, true);
final ventBottle = storage.getActiveVentolinBottle();
expect(ventBottle, isNotNull);
expect(ventBottle!.sequenceNumber, 1);
expect(ventBottle.totalDoses, 200);
expect(ventBottle.isActive, true);
final canisters = storage.getCanisters();
final flixCan = canisters.firstWhere((c) => c.isSteroid);
final ventCan = canisters.firstWhere((c) => !c.isSteroid);
expect(flixCan.remainingDoses, 60);
expect(ventCan.remainingDoses, 200);
});
test('2. 正常雾化记录自动扣减对应药瓶喷数并保持一致', () async {
final storage = await StorageService.init();
final flixBottle = storage.getActiveFlixotideBottle()!;
final ventBottle = storage.getActiveVentolinBottle()!;
final record = DoseRecord(
id: const Uuid().v4(),
startTime: DateTime.now().toUtc(),
endTime: DateTime.now().toUtc(),
flixotidePuffs: 2,
ventolinPuffs: 2,
flixotideBottleId: flixBottle.id,
ventolinBottleId: ventBottle.id,
);
await storage.addRecord(record);
final canisters = storage.getCanisters();
final flixCan = canisters.firstWhere((c) => c.isSteroid);
final ventCan = canisters.firstWhere((c) => !c.isSteroid);
expect(flixCan.remainingDoses, 58); // 60 - 2
expect(ventCan.remainingDoses, 198); // 200 - 2
});
test('3. 开新瓶 (openNewBottle) 归档旧瓶,激活第 2 瓶并重置为满喷', () async {
final storage = await StorageService.init();
final bottle1 = storage.getActiveFlixotideBottle()!;
// 第 1 瓶用掉 4 喷
await storage.addRecord(DoseRecord(
id: const Uuid().v4(),
startTime: DateTime.now().toUtc(),
endTime: DateTime.now().toUtc(),
flixotidePuffs: 4,
flixotideBottleId: bottle1.id,
));
expect(storage.getPrimaryFlixotide()!.remainingDoses, 56);
// 换新药瓶 (开新瓶)
final bottle2 = await storage.openNewBottle(bottle1.canisterId, deviceName: '妈妈手机');
expect(bottle2.sequenceNumber, 2);
expect(bottle2.isActive, true);
expect(bottle2.totalDoses, 60);
// 验证第 1 瓶已被归档
final allBottles = storage.getBottles().where((b) => b.canisterId == bottle1.canisterId).toList();
expect(allBottles.length, 2);
final archivedBottle1 = allBottles.firstWhere((b) => b.sequenceNumber == 1);
expect(archivedBottle1.isActive, false);
expect(archivedBottle1.finishedAt, isNotNull);
// 验证当前活跃药瓶切换为第 2 瓶,且余量对齐为满瓶 60 喷
final currentActive = storage.getActiveFlixotideBottle()!;
expect(currentActive.id, bottle2.id);
expect(storage.getPrimaryFlixotide()!.remainingDoses, 60);
});
test('4. 开新瓶后新产生的雾化仅扣减新瓶,旧瓶归档数据不被污染', () async {
final storage = await StorageService.init();
final bottle1 = storage.getActiveFlixotideBottle()!;
// 第 1 瓶用掉 60 喷 (用尽)
await storage.addRecord(DoseRecord(
id: const Uuid().v4(),
startTime: DateTime.now().toUtc().subtract(const Duration(days: 1)),
endTime: DateTime.now().toUtc().subtract(const Duration(days: 1)),
flixotidePuffs: 60,
flixotideBottleId: bottle1.id,
));
// 开第 2 瓶
final bottle2 = await storage.openNewBottle(bottle1.canisterId, deviceName: '测试设备');
expect(storage.getPrimaryFlixotide()!.remainingDoses, 60);
// 第 2 瓶吸入 2 喷
await storage.addRecord(DoseRecord(
id: const Uuid().v4(),
startTime: DateTime.now().toUtc(),
endTime: DateTime.now().toUtc(),
flixotidePuffs: 2,
flixotideBottleId: bottle2.id,
));
// 第 2 瓶余量应为 58 喷
expect(storage.getPrimaryFlixotide()!.remainingDoses, 58);
});
test('5. 软删除墓碑测试:误操作删除记录后喷数自动恢复', () async {
final storage = await StorageService.init();
final flixBottle = storage.getActiveFlixotideBottle()!;
final recordId = const Uuid().v4();
await storage.addRecord(DoseRecord(
id: recordId,
startTime: DateTime.now().toUtc(),
endTime: DateTime.now().toUtc(),
flixotidePuffs: 2,
flixotideBottleId: flixBottle.id,
));
expect(storage.getPrimaryFlixotide()!.remainingDoses, 58);
// 删除该记录
await storage.deleteRecord(recordId);
// 验证用户可见列表已移除该记录
expect(storage.getRecords().length, 0);
// 验证全量记录中标记了 isDeleted = true
final allRaw = storage.getAllRecords(includeDeleted: true);
expect(allRaw.length, 1);
expect(allRaw.first.isDeleted, true);
// 验证药瓶余量已恢复至 60 喷
expect(storage.getPrimaryFlixotide()!.remainingDoses, 60);
});
test('6. 历史数据平滑升级:未绑定 bottleId 的旧数据自动归属到第 1 瓶', () async {
// 预先写入未绑定 bottleId 的旧版数据
final legacyRecord = DoseRecord(
id: 'legacy_rec_1',
startTime: DateTime.parse('2026-10-27T02:00:00Z'),
endTime: DateTime.parse('2026-10-27T02:01:00Z'),
flixotidePuffs: 2,
ventolinPuffs: 1,
);
final prefs = await SharedPreferences.getInstance();
await prefs.setStringList('aerotrack_records', [legacyRecord.toJson()]);
// 初始化 StorageService
final storage = await StorageService.init();
// 验证平滑迁移:自动创建第 1 瓶,且历史记录关联到了第 1 瓶
final records = storage.getRecords();
expect(records.length, 1);
expect(records.first.flixotideBottleId, 'flix_b1_initial');
expect(records.first.ventolinBottleId, 'vent_b1_initial');
// 验证余量正确扣减了历史数据
expect(storage.getPrimaryFlixotide()!.remainingDoses, 58); // 60 - 2
expect(storage.getPrimaryVentolin()!.remainingDoses, 199); // 200 - 1
});
test('7. 试喷 (Prime) 扣除正确关联药瓶并扣减 1 喷', () async {
final storage = await StorageService.init();
final flixBottle = storage.getActiveFlixotideBottle()!;
final primeRecord = DoseRecord(
id: const Uuid().v4(),
startTime: DateTime.now().toUtc(),
endTime: DateTime.now().toUtc(),
flixotidePuffs: 1,
ventolinPuffs: 0,
flixotideBottleId: flixBottle.id,
isPrime: true,
note: '辅舒酮试喷',
);
await storage.addRecord(primeRecord);
expect(storage.getPrimaryFlixotide()!.remainingDoses, 59);
expect(storage.getRecords().first.isPrime, true);
});
});
}
+209
View File
@@ -0,0 +1,209 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:uuid/uuid.dart';
import 'package:aero_track/models/bottle.dart';
import 'package:aero_track/models/dose_record.dart';
import 'package:aero_track/models/canister.dart';
import 'package:aero_track/services/storage_service.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('Multi-Device Collaborative Sync Simulation Tests', () {
test('1. 设备 A 开新瓶:生成新 Bottle 实体与 60 喷满瓶初始状态', () async {
SharedPreferences.setMockInitialValues({});
final storageA = await StorageService.init();
final flixA1 = storageA.getActiveFlixotideBottle()!;
expect(flixA1.sequenceNumber, 1);
expect(storageA.getPrimaryFlixotide()!.remainingDoses, 60);
// 设备 A 开新瓶 (启用第 2 瓶)
final flixA2 = await storageA.openNewBottle(flixA1.canisterId, deviceName: '妈妈手机');
expect(flixA2.sequenceNumber, 2);
expect(flixA2.isActive, true);
expect(storageA.getPrimaryFlixotide()!.remainingDoses, 60);
// 验证第 1 瓶已归档
final allBottles = storageA.getBottles().where((b) => b.canisterId == flixA1.canisterId).toList();
expect(allBottles.length, 2);
expect(allBottles.firstWhere((b) => b.sequenceNumber == 1).isActive, false);
});
test('2. 设备 B (旧缓存/未换瓶) 同步后自动切换至第 2 瓶并展示满瓶 60 喷', () async {
// 模拟设备 B 处于旧状态 (只知道第 1 瓶且剩余 40 喷)
final oldBottle1 = Bottle(
id: 'flix_b1_initial',
canisterId: 'flixotide_primary',
name: '辅舒酮 (丙酸氟替卡松)',
sequenceNumber: 1,
totalDoses: 60,
openedAt: DateTime.parse('2020-01-01T00:00:00Z'),
isActive: true,
updatedAt: DateTime.parse('2020-01-01T00:00:00Z'),
);
SharedPreferences.setMockInitialValues({
'aerotrack_bottles': [oldBottle1.toJson()],
'aerotrack_canisters': [
Canister(
id: 'flixotide_primary',
name: '辅舒酮 (丙酸氟替卡松)',
totalDoses: 60,
remainingDoses: 40,
openedAt: DateTime.parse('2020-01-01T00:00:00Z'),
).toJson()
],
});
final storageB = await StorageService.init();
expect(storageB.getActiveFlixotideBottle()!.sequenceNumber, 1);
// 模拟从服务端拉到设备 A 创建的第 2 瓶
final remoteBottle1Archived = Bottle(
id: 'flix_b1_initial',
canisterId: 'flixotide_primary',
name: '辅舒酮',
sequenceNumber: 1,
totalDoses: 60,
openedAt: DateTime.parse('2020-01-01T00:00:00Z'),
finishedAt: DateTime.parse('2026-10-28T05:00:00Z'),
isActive: false,
updatedAt: DateTime.parse('2026-10-28T05:00:00Z'),
);
final remoteBottle2Active = Bottle(
id: 'flix_b2_new',
canisterId: 'flixotide_primary',
name: '辅舒酮',
sequenceNumber: 2,
totalDoses: 60,
openedAt: DateTime.parse('2026-10-28T05:00:00Z'),
isActive: true,
updatedAt: DateTime.parse('2026-10-28T05:00:00Z'),
);
// 设备 B 合并 Bottles
final localBottles = storageB.getBottles();
final bottleMap = {for (var b in localBottles) b.id: b};
for (var rb in [remoteBottle1Archived, remoteBottle2Active]) {
if (!bottleMap.containsKey(rb.id)) {
localBottles.add(rb);
} else {
final idx = localBottles.indexWhere((b) => b.id == rb.id);
localBottles[idx] = rb;
}
}
await storageB.saveBottles(localBottles);
await storageB.recalculateCanisterDoses();
// 验证设备 B 自动更新活跃瓶为第 2 瓶,且余量瞬间变为满瓶 60 喷
final activeB = storageB.getActiveFlixotideBottle()!;
expect(activeB.sequenceNumber, 2);
expect(activeB.id, 'flix_b2_new');
expect(storageB.getPrimaryFlixotide()!.remainingDoses, 60);
});
test('3. 设备 B 在第 2 瓶上雾化用药,扣减精准归属于第 2 瓶', () async {
final bottle2 = Bottle(
id: 'flix_b2_new',
canisterId: 'flixotide_primary',
name: '辅舒酮',
sequenceNumber: 2,
totalDoses: 60,
openedAt: DateTime.parse('2026-10-28T05:00:00Z'),
isActive: true,
);
SharedPreferences.setMockInitialValues({
'aerotrack_bottles': [bottle2.toJson()],
'aerotrack_canisters': [
Canister(
id: 'flixotide_primary',
name: '辅舒酮',
totalDoses: 60,
remainingDoses: 60,
openedAt: DateTime.parse('2026-10-28T05:00:00Z'),
).toJson()
],
});
final storage = await StorageService.init();
// 在第 2 瓶上吸入 2 喷
await storage.addRecord(DoseRecord(
id: 'dose_1',
startTime: DateTime.parse('2026-10-28T05:10:00Z'),
endTime: DateTime.parse('2026-10-28T05:11:00Z'),
flixotidePuffs: 2,
flixotideBottleId: bottle2.id,
));
expect(storage.getPrimaryFlixotide()!.remainingDoses, 58);
});
test('4. 软删除墓碑在多端同步传播,删除后各端自动准确恢复喷数', () async {
final bottle2 = Bottle(
id: 'flix_b2_new',
canisterId: 'flixotide_primary',
name: '辅舒酮',
sequenceNumber: 2,
totalDoses: 60,
openedAt: DateTime.parse('2026-10-28T05:00:00Z'),
isActive: true,
);
// 设备 A 录入并随后软删除了记录
final deletedDoseRecord = DoseRecord(
id: 'dose_mistake',
startTime: DateTime.parse('2026-10-28T05:10:00Z'),
endTime: DateTime.parse('2026-10-28T05:11:00Z'),
flixotidePuffs: 2,
flixotideBottleId: bottle2.id,
isDeleted: true,
updatedAt: DateTime.parse('2026-10-28T05:15:00Z'),
);
// 模拟设备 B 正在同步拉取该记录
SharedPreferences.setMockInitialValues({
'aerotrack_bottles': [bottle2.toJson()],
'aerotrack_records': [deletedDoseRecord.toJson()],
});
final storageB = await StorageService.init();
// 验证虽然有历史流水,但因被标记为 isDeleted,不扣减当瓶喷数,余量保持 60 喷
expect(storageB.getPrimaryFlixotide()!.remainingDoses, 60);
expect(storageB.getRecords().length, 0); // 用户界面不呈现已删除记录
expect(storageB.getAllRecords(includeDeleted: true).length, 1); // 同步底层完好保留墓碑
});
test('5. 跨时区与时钟偏差鲁棒性测试', () async {
SharedPreferences.setMockInitialValues({});
final storage = await StorageService.init();
final activeBottle = storage.getActiveFlixotideBottle()!;
// 模拟东八区 (CST +08:00) 与西七区 (PST -07:00) 产生的记录
final cstTime = DateTime.parse('2026-10-28T08:00:00+08:00').toUtc();
final pstTime = DateTime.parse('2026-10-27T17:00:00-07:00').toUtc();
await storage.addRecord(DoseRecord(
id: const Uuid().v4(),
startTime: cstTime,
endTime: cstTime,
flixotidePuffs: 2,
flixotideBottleId: activeBottle.id,
));
await storage.addRecord(DoseRecord(
id: const Uuid().v4(),
startTime: pstTime,
endTime: pstTime,
flixotidePuffs: 2,
flixotideBottleId: activeBottle.id,
));
// 60 - 2 - 2 = 56 喷,绝对确定,绝不被本地时区字符串带偏
expect(storage.getPrimaryFlixotide()!.remainingDoses, 56);
});
});
}