Merge upstream/dev (22 commits) [upstream-sync]
Conflicts resolved by hand, our fork changes carried over: - MainActivity.kt: keep the unread widget hooks next to upstream's scroll capture (attach and detach both). - app_settings_screen.dart: upstream wrapped the list in MeshSettingsTileTheme; image-message and translation sections stay gated on kOnDeviceMl (ML-free build). - channel_chat_screen.dart: upstream split build() into methods; took theirs and re-applied the terminal-theme list padding. - chat_composer.dart: both imports (terminal_theme, radio_guard). - mesh_nav_tile.dart: upstream's meshTileTitleStyle, with the smaller terminal-theme title kept. flutter analyze clean, flutter test 1522 passed (CI image, local). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
185d2aca53
210 files changed
+52066
-5541
No files matched your search
@@ -225,6 +225,28 @@ void main() {
|
||||
expect(_storedTexts(hikingId), isNot(contains(_queuedHikingText)));
|
||||
});
|
||||
|
||||
test(
|
||||
'bulk delete matches by id, not the object held by the selection',
|
||||
() async {
|
||||
await _connect(_TestRadio());
|
||||
await _waitFor(() => _texts(1).contains(_queuedHikingText));
|
||||
final stored = _connector
|
||||
.getChannelMessages(_channelAt(1))
|
||||
.firstWhere((m) => m.text == _queuedHikingText);
|
||||
// A repeat heard while the confirmation was open replaces the stored
|
||||
// object; the selection still holds the old one with the same id.
|
||||
final stale = stored.copyWith();
|
||||
expect(identical(stale, stored), isFalse);
|
||||
expect(stale.messageId, stored.messageId);
|
||||
|
||||
final removed = await _connector.deleteChannelMessages([stale]);
|
||||
await _connector.flushPendingWrites();
|
||||
expect(removed, 1);
|
||||
expect(_texts(1), isNot(contains(_queuedHikingText)));
|
||||
expect(_storedTexts(hikingId), isNot(contains(_queuedHikingText)));
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'a PSK edit in place keeps the channel\'s place in the custom order',
|
||||
() async {
|
||||
|
||||
@@ -0,0 +1,372 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/connector/meshcore_connector.dart';
|
||||
import 'package:meshcore_open/connector/meshcore_protocol.dart';
|
||||
import 'package:meshcore_open/models/channel.dart';
|
||||
import 'package:meshcore_open/models/channel_message.dart';
|
||||
import 'package:meshcore_open/models/contact.dart';
|
||||
import 'package:meshcore_open/storage/channel_message_store.dart';
|
||||
import 'package:meshcore_open/storage/channel_store.dart';
|
||||
import 'package:meshcore_open/storage/contact_store.dart';
|
||||
import 'package:meshcore_open/storage/history_store.dart';
|
||||
import 'package:meshcore_open/storage/last_radio_store.dart';
|
||||
import 'package:meshcore_open/storage/message_store.dart';
|
||||
import 'package:meshcore_open/storage/prefs_manager.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
const _radioA =
|
||||
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
|
||||
const _radioB =
|
||||
'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb';
|
||||
final _contactKey = Uint8List.fromList(List.generate(32, (i) => i + 1));
|
||||
final _contactHex = pubKeyToHex(_contactKey);
|
||||
final _channel = Channel(
|
||||
index: 0,
|
||||
name: 'Test',
|
||||
psk: Uint8List.fromList(List.filled(16, 1)),
|
||||
);
|
||||
|
||||
String _dmKey(String radio) => 'messages_${radio.substring(0, 10)}$_contactHex';
|
||||
String _channelKey(String radio) =>
|
||||
'channel_messages_${radio.substring(0, 10)}_${_channel.storageId}';
|
||||
|
||||
Map<String, Object?> _dm(int i, {String prefix = 'dm'}) => {
|
||||
'senderKey': base64Encode(_contactKey),
|
||||
'text': '$prefix-$i',
|
||||
'timestamp': 1000 * (i + 1),
|
||||
'isOutgoing': false,
|
||||
'status': 2,
|
||||
'messageId': '$prefix-$i',
|
||||
'plainText': true,
|
||||
};
|
||||
Map<String, Object?> _ch(int i, {String prefix = 'ch'}) => {
|
||||
'senderName': 'Bob',
|
||||
'text': '$prefix-$i',
|
||||
'timestamp': 1000 * (i + 1),
|
||||
'isOutgoing': false,
|
||||
'status': 1,
|
||||
'channelIndex': 0,
|
||||
'messageId': '$prefix-$i',
|
||||
'plainText': true,
|
||||
};
|
||||
|
||||
class _TrackingHistory extends HistoryStore {
|
||||
final data = <String, String>{};
|
||||
final reads = <({String key, int offset, int? limit})>[];
|
||||
final fullReads = <String>[];
|
||||
String? delayedKey;
|
||||
Completer<void>? gate;
|
||||
Completer<void>? started;
|
||||
String? failedKey;
|
||||
|
||||
@override
|
||||
Future<String?> getString(String key) async {
|
||||
fullReads.add(key);
|
||||
return data[key];
|
||||
}
|
||||
|
||||
@override
|
||||
Future<bool> setString(String key, String value) async {
|
||||
data[key] = value;
|
||||
return true;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<bool> remove(String key) async {
|
||||
data.remove(key);
|
||||
return true;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Set<String>> getKeys() async => data.keys.toSet();
|
||||
|
||||
List<String> _entries(String key) =>
|
||||
((jsonDecode(data[key] ?? '[]')) as List).map(jsonEncode).toList();
|
||||
|
||||
@override
|
||||
Future<int> entryCount(String key) async => _entries(key).length;
|
||||
|
||||
@override
|
||||
Future<List<String>> readEntries(
|
||||
String key, {
|
||||
int offset = 0,
|
||||
int? limit,
|
||||
}) async {
|
||||
if (key == failedKey) throw StateError('History storage unavailable');
|
||||
reads.add((key: key, offset: offset, limit: limit));
|
||||
final selected = _entries(key).skip(offset);
|
||||
final snapshot = (limit == null ? selected : selected.take(limit)).toList();
|
||||
if (key == delayedKey && gate != null) {
|
||||
final wait = gate!;
|
||||
gate = null;
|
||||
started?.complete();
|
||||
await wait.future;
|
||||
}
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<int> replaceTail(
|
||||
String key,
|
||||
int preservedCount,
|
||||
List<String> entries, {
|
||||
int maxEntries = 1000,
|
||||
}) async {
|
||||
final prefix = _entries(key).take(preservedCount).toList();
|
||||
final combined = [...prefix, ...entries];
|
||||
final overflow = (combined.length - maxEntries).clamp(0, combined.length);
|
||||
data[key] = '[${combined.skip(overflow).join(',')}]';
|
||||
return (prefix.length - overflow).clamp(0, prefix.length);
|
||||
}
|
||||
|
||||
Completer<void> delayNextRead(String key) {
|
||||
delayedKey = key;
|
||||
gate = Completer<void>();
|
||||
started = Completer<void>();
|
||||
return gate!;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _seedRadio(String radio) async {
|
||||
final contact = Contact(
|
||||
publicKey: _contactKey,
|
||||
name: 'Alice',
|
||||
type: advTypeChat,
|
||||
pathLength: 0,
|
||||
path: Uint8List(0),
|
||||
lastSeen: DateTime.fromMillisecondsSinceEpoch(1000),
|
||||
);
|
||||
await (ContactStore()..setPublicKeyHex = radio).saveContacts([contact]);
|
||||
final channels = ChannelStore()..setPublicKeyHex = radio;
|
||||
await channels.saveChannels([_channel]);
|
||||
await channels.saveSlotChannelIds({0: _channel.storageId!});
|
||||
await PrefsManager.instance.setBool(
|
||||
'channel_storage_v2_${radio.substring(0, 10)}',
|
||||
true,
|
||||
);
|
||||
await LastRadioStore().save(
|
||||
LastRadio(
|
||||
publicKeyHex: radio,
|
||||
name: 'Saved',
|
||||
transport: LastRadio.transportBle,
|
||||
bleRemoteId: 'AA:BB:CC:DD:EE:FF',
|
||||
savedAt: DateTime.fromMillisecondsSinceEpoch(1000),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
late _TrackingHistory history;
|
||||
late MeshCoreConnector connector;
|
||||
|
||||
setUp(() async {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
PrefsManager.reset();
|
||||
await PrefsManager.initialize();
|
||||
await _seedRadio(_radioA);
|
||||
history = _TrackingHistory();
|
||||
history.data[_dmKey(_radioA)] = jsonEncode([
|
||||
for (var i = 0; i < 620; i++) _dm(i),
|
||||
]);
|
||||
history.data[_channelKey(_radioA)] = jsonEncode([
|
||||
for (var i = 0; i < 620; i++) _ch(i),
|
||||
]);
|
||||
HistoryStore.use(history);
|
||||
MessageStore().forgetArchive();
|
||||
ChannelMessageStore().forgetArchive();
|
||||
connector = MeshCoreConnector();
|
||||
addTearDown(connector.dispose);
|
||||
});
|
||||
|
||||
test(
|
||||
'initial loads and older pages read only the requested stored rows',
|
||||
() async {
|
||||
await connector.restoreLastRadio();
|
||||
final contact = connector.contacts.single;
|
||||
final channel = connector.channels.single;
|
||||
expect(connector.getMessages(contact).map((m) => m.text), [
|
||||
for (var i = 420; i < 620; i++) 'dm-$i',
|
||||
]);
|
||||
expect(connector.getChannelMessages(channel).map((m) => m.text), [
|
||||
for (var i = 420; i < 620; i++) 'ch-$i',
|
||||
]);
|
||||
expect(
|
||||
history.reads,
|
||||
containsAll([
|
||||
(key: _dmKey(_radioA), offset: 420, limit: 200),
|
||||
(key: _channelKey(_radioA), offset: 420, limit: 200),
|
||||
]),
|
||||
);
|
||||
expect(
|
||||
history.fullReads.where(
|
||||
(key) => key == _dmKey(_radioA) || key == _channelKey(_radioA),
|
||||
),
|
||||
isEmpty,
|
||||
);
|
||||
history.reads.clear();
|
||||
final dms = await connector.loadOlderMessages(_contactHex);
|
||||
final channels = await connector.loadOlderChannelMessages(0);
|
||||
expect(dms.map((m) => m.text), [for (var i = 370; i < 420; i++) 'dm-$i']);
|
||||
expect(channels.map((m) => m.text), [
|
||||
for (var i = 370; i < 420; i++) 'ch-$i',
|
||||
]);
|
||||
expect(history.reads, [
|
||||
(key: _dmKey(_radioA), offset: 370, limit: 50),
|
||||
(key: _channelKey(_radioA), offset: 370, limit: 50),
|
||||
]);
|
||||
final next = await connector.loadOlderMessages(_contactHex);
|
||||
expect(next.map((m) => m.text), [
|
||||
for (var i = 320; i < 370; i++) 'dm-$i',
|
||||
]);
|
||||
expect(
|
||||
connector.getMessages(contact).map((m) => m.messageId).toSet(),
|
||||
hasLength(300),
|
||||
);
|
||||
final search = await connector.allMessagesForSearch(_contactHex);
|
||||
expect(search.map((m) => m.text), [
|
||||
for (var i = 0; i < 620; i++) 'dm-$i',
|
||||
]);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'older pages start before the window when the archive is unreconciled',
|
||||
() async {
|
||||
await connector.restoreLastRadio();
|
||||
MessageStore().forgetArchive();
|
||||
ChannelMessageStore().forgetArchive();
|
||||
final dms = await connector.loadOlderMessages(_contactHex);
|
||||
final channels = await connector.loadOlderChannelMessages(0);
|
||||
expect(dms.map((m) => m.text), [for (var i = 370; i < 420; i++) 'dm-$i']);
|
||||
expect(channels.map((m) => m.text), [
|
||||
for (var i = 370; i < 420; i++) 'ch-$i',
|
||||
]);
|
||||
expect(
|
||||
connector.getMessages(connector.contacts.single).map((m) => m.text),
|
||||
[for (var i = 370; i < 620; i++) 'dm-$i'],
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'malformed rows consume physical offsets and do not hide older pages',
|
||||
() async {
|
||||
history.data[_dmKey(_radioA)] = jsonEncode([
|
||||
for (var i = 0; i < 620; i++)
|
||||
if (i >= 400 && i < 600) {'text': 1} else _dm(i),
|
||||
]);
|
||||
await connector.restoreLastRadio();
|
||||
expect(connector.getMessages(connector.contacts.single), hasLength(200));
|
||||
final older = await connector.loadOlderMessages(_contactHex);
|
||||
expect(older.map((m) => m.text), [
|
||||
for (var i = 170; i < 220; i++) 'dm-$i',
|
||||
]);
|
||||
final stored = await connector.allMessagesForSearch(_contactHex);
|
||||
expect(stored.map((m) => m.text), [
|
||||
for (var i = 0; i < 620; i++)
|
||||
if (i < 400 || i >= 600) 'dm-$i',
|
||||
]);
|
||||
expect(history.reads.last, (
|
||||
key: _dmKey(_radioA),
|
||||
offset: 0,
|
||||
limit: 170,
|
||||
), reason: 'Search reads the remaining prefix before the loaded window');
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'a storage read failure keeps the loaded window and archive cursor',
|
||||
() async {
|
||||
await connector.restoreLastRadio();
|
||||
final before = List.of(connector.getMessages(connector.contacts.single));
|
||||
final store = MessageStore()..setPublicKeyHex = _radioA;
|
||||
expect(store.archivedCount(_contactHex), 420);
|
||||
history.failedKey = _dmKey(_radioA);
|
||||
|
||||
await expectLater(
|
||||
connector.loadOlderMessages(_contactHex),
|
||||
throwsStateError,
|
||||
);
|
||||
expect(connector.getMessages(connector.contacts.single), before);
|
||||
expect(store.archivedCount(_contactHex), 420);
|
||||
history.failedKey = null;
|
||||
expect(await connector.loadOlderMessages(_contactHex), hasLength(50));
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'overlapping requests share a page rather than prepending it twice',
|
||||
() async {
|
||||
await connector.restoreLastRadio();
|
||||
history.reads.clear();
|
||||
final gate = history.delayNextRead(_dmKey(_radioA));
|
||||
final first = connector.loadOlderMessages(_contactHex);
|
||||
await history.started!.future;
|
||||
final second = connector.loadOlderMessages(_contactHex);
|
||||
gate.complete();
|
||||
await Future.wait([first, second]);
|
||||
expect(
|
||||
history.reads.where((r) => r.key == _dmKey(_radioA)),
|
||||
hasLength(1),
|
||||
);
|
||||
expect(connector.getMessages(connector.contacts.single), hasLength(250));
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'a delayed old-radio page cannot enter a newly restored radio',
|
||||
() async {
|
||||
await connector.restoreLastRadio();
|
||||
final gate = history.delayNextRead(_dmKey(_radioA));
|
||||
final oldPage = connector.loadOlderMessages(_contactHex);
|
||||
await history.started!.future;
|
||||
await _seedRadio(_radioB);
|
||||
history.data[_dmKey(_radioB)] = jsonEncode([
|
||||
for (var i = 0; i < 10; i++) _dm(i, prefix: 'new'),
|
||||
]);
|
||||
history.data[_channelKey(_radioB)] = '[]';
|
||||
await connector.restoreLastRadio();
|
||||
gate.complete();
|
||||
expect(await oldPage, isEmpty);
|
||||
expect(connector.storageKeyHex, _radioB);
|
||||
expect(
|
||||
connector.getMessages(connector.contacts.single).map((m) => m.text),
|
||||
[for (var i = 0; i < 10; i++) 'new-$i'],
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'channel edits during an asynchronous reload survive the stale read',
|
||||
() async {
|
||||
await connector.restoreLastRadio();
|
||||
final channel = connector.channels.single;
|
||||
final gate = history.delayNextRead(_channelKey(_radioA));
|
||||
final reload = connector.loadAllChannelMessages();
|
||||
await history.started!.future;
|
||||
final current = connector.getChannelMessages(channel);
|
||||
final removed = current.first;
|
||||
current.add(
|
||||
ChannelMessage(
|
||||
senderName: 'Live',
|
||||
text: 'arrived during read',
|
||||
timestamp: DateTime.fromMillisecondsSinceEpoch(1000000),
|
||||
isOutgoing: false,
|
||||
status: ChannelMessageStatus.sent,
|
||||
channelIndex: 0,
|
||||
messageId: 'live',
|
||||
),
|
||||
);
|
||||
await connector.deleteChannelMessage(removed);
|
||||
gate.complete();
|
||||
await reload;
|
||||
final messages = connector.getChannelMessages(channel);
|
||||
expect(messages.any((m) => m.messageId == 'live'), isTrue);
|
||||
expect(messages.any((m) => m.messageId == removed.messageId), isFalse);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -38,6 +38,26 @@ void main() {
|
||||
});
|
||||
});
|
||||
|
||||
group('private-key backup frames', () {
|
||||
test('uses the firmware command codes and 64-byte identity payload', () {
|
||||
final keyData = Uint8List.fromList(List.generate(64, (index) => index));
|
||||
expect(buildExportPrivateKeyFrame(), [cmdExportPrivateKey]);
|
||||
final frame = buildImportPrivateKeyFrame(keyData);
|
||||
expect(frame.length, 65);
|
||||
expect(frame.first, cmdImportPrivateKey);
|
||||
expect(frame.sublist(1), keyData);
|
||||
expect(respCodePrivateKey, 14);
|
||||
expect(respCodeDisabled, 15);
|
||||
});
|
||||
|
||||
test('rejects identity data with the wrong length', () {
|
||||
expect(
|
||||
() => buildImportPrivateKeyFrame(Uint8List(63)),
|
||||
throwsArgumentError,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
group('BufferWriter.writeCString', () {
|
||||
test('NUL-terminates and truncates on a character boundary', () {
|
||||
final writer = BufferWriter()..writeCString('#${'ё' * 20}', 32);
|
||||
|
||||
@@ -232,7 +232,7 @@ void main() {
|
||||
await _connect();
|
||||
// Nobody called "Ghost" has posted, so the reply keeps its mention.
|
||||
const text = '@[Ghost] cheap radios for sale, message me today';
|
||||
final cleanBefore = _filter.recentCleanCount;
|
||||
const filterText = 'cheap radios for sale, message me today';
|
||||
_connector.handleFrameForTest(
|
||||
ReviewFrames.channelMessage(
|
||||
channelIndex: 2,
|
||||
@@ -241,16 +241,19 @@ void main() {
|
||||
timestampSecs: _nowSecs(),
|
||||
),
|
||||
);
|
||||
await _waitFor(() => _find(2, text) != null);
|
||||
await _waitFor(
|
||||
() => _find(2, text) != null && _filter.hasRecentCleanExample(filterText),
|
||||
);
|
||||
final message = _find(2, text)!;
|
||||
expect(message.text, startsWith('@[Ghost]'));
|
||||
expect(_filter.recentCleanCount, cleanBefore + 1);
|
||||
|
||||
final spamBefore = _filter.spamExampleCount;
|
||||
await _connector.markChannelMessageSpam(_channelAt(2), message);
|
||||
expect(_filter.spamExampleCount, spamBefore + 1);
|
||||
// The clean example recorded on arrival is gone, not contradicted.
|
||||
expect(_filter.recentCleanCount, cleanBefore);
|
||||
// The clean example recorded on arrival is gone, not contradicted. Check
|
||||
// this example directly: other queued messages can teach the filter while
|
||||
// this async test is awaiting the retrain.
|
||||
expect(_filter.hasRecentCleanExample(filterText), isFalse);
|
||||
});
|
||||
|
||||
test('spam actions only touch the message in the chosen channel', () async {
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/connector/meshcore_connector.dart';
|
||||
import 'package:meshcore_open/connector/meshcore_protocol.dart';
|
||||
import 'package:meshcore_open/models/channel.dart';
|
||||
import 'package:meshcore_open/models/channel_message.dart';
|
||||
import 'package:meshcore_open/models/contact.dart';
|
||||
import 'package:meshcore_open/models/message.dart';
|
||||
import 'package:meshcore_open/review_mode/review_radio.dart';
|
||||
import 'package:meshcore_open/storage/channel_message_store.dart';
|
||||
import 'package:meshcore_open/storage/channel_store.dart';
|
||||
import 'package:meshcore_open/storage/contact_store.dart';
|
||||
import 'package:meshcore_open/storage/last_radio_store.dart';
|
||||
import 'package:meshcore_open/storage/message_store.dart';
|
||||
import 'package:meshcore_open/storage/prefs_manager.dart';
|
||||
import 'package:meshcore_open/storage/unread_store.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
final _radioKey = Uint8List.fromList(List<int>.generate(32, (i) => 0xA0 + i));
|
||||
final _radioHex = pubKeyToHex(_radioKey);
|
||||
final _aliceKey = Uint8List.fromList(List<int>.generate(32, (i) => 0x10 + i));
|
||||
final _psk = Uint8List.fromList(List<int>.generate(16, (i) => 0x40 + i));
|
||||
|
||||
Future<void> _waitFor(bool Function() condition, {int seconds = 8}) async {
|
||||
final end = DateTime.now().add(Duration(seconds: seconds));
|
||||
while (!condition()) {
|
||||
if (DateTime.now().isAfter(end)) fail('Timed out waiting for condition');
|
||||
await Future<void>.delayed(const Duration(milliseconds: 25));
|
||||
}
|
||||
}
|
||||
|
||||
/// Saves a radio's data the way a real session would.
|
||||
Future<void> _seedRadio() async {
|
||||
final alice = Contact(
|
||||
publicKey: _aliceKey,
|
||||
name: 'Alice',
|
||||
type: advTypeChat,
|
||||
pathLength: 1,
|
||||
path: Uint8List.fromList([0x22]),
|
||||
lastSeen: DateTime.fromMillisecondsSinceEpoch(1700000000000),
|
||||
);
|
||||
final self = Contact(
|
||||
publicKey: _radioKey,
|
||||
name: 'Me',
|
||||
type: advTypeChat,
|
||||
pathLength: 0,
|
||||
path: Uint8List(0),
|
||||
lastSeen: DateTime.fromMillisecondsSinceEpoch(1700000000000),
|
||||
);
|
||||
await (ContactStore()..setPublicKeyHex = _radioHex).saveContacts([
|
||||
alice,
|
||||
self,
|
||||
]);
|
||||
|
||||
final channel = Channel(index: 0, name: 'Base Camp', psk: _psk);
|
||||
final channelId = channel.storageId!;
|
||||
final channelStore = ChannelStore()..setPublicKeyHex = _radioHex;
|
||||
await channelStore.saveChannels([channel]);
|
||||
await channelStore.saveSlotChannelIds({0: channelId});
|
||||
await (ChannelMessageStore()..setPublicKeyHex = _radioHex)
|
||||
.saveChannelMessages(channelId, [
|
||||
ChannelMessage(
|
||||
senderName: 'Bob',
|
||||
text: 'camp is up',
|
||||
timestamp: DateTime.fromMillisecondsSinceEpoch(1700000001000),
|
||||
isOutgoing: false,
|
||||
status: ChannelMessageStatus.sent,
|
||||
channelIndex: 0,
|
||||
),
|
||||
]);
|
||||
|
||||
await (MessageStore()..setPublicKeyHex = _radioHex)
|
||||
.saveMessages(alice.publicKeyHex, [
|
||||
Message(
|
||||
senderKey: _aliceKey,
|
||||
text: 'hi there',
|
||||
timestamp: DateTime.fromMillisecondsSinceEpoch(1700000002000),
|
||||
isOutgoing: false,
|
||||
status: MessageStatus.delivered,
|
||||
),
|
||||
Message(
|
||||
senderKey: _aliceKey,
|
||||
text: 'did not go out',
|
||||
timestamp: DateTime.fromMillisecondsSinceEpoch(1700000003000),
|
||||
isOutgoing: true,
|
||||
status: MessageStatus.failed,
|
||||
),
|
||||
]);
|
||||
|
||||
final unread = UnreadStore()..setPublicKeyHex = _radioHex;
|
||||
unread.saveContactUnreadCount({alice.publicKeyHex: 2});
|
||||
await unread.flush();
|
||||
|
||||
await LastRadioStore().save(
|
||||
LastRadio(
|
||||
publicKeyHex: _radioHex,
|
||||
name: 'Base',
|
||||
transport: LastRadio.transportBle,
|
||||
bleRemoteId: 'AA:BB:CC:DD:EE:FF',
|
||||
savedAt: DateTime.fromMillisecondsSinceEpoch(1700000000000),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// initialize() listens to the notification service's single-subscription
|
||||
// reply stream, so these connectors run without it.
|
||||
MeshCoreConnector _newConnector() {
|
||||
final connector = MeshCoreConnector();
|
||||
addTearDown(connector.dispose);
|
||||
return connector;
|
||||
}
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
setUp(() async {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
PrefsManager.reset();
|
||||
await PrefsManager.initialize();
|
||||
ChannelMessageStore().forgetArchive();
|
||||
MessageStore().forgetArchive();
|
||||
await _seedRadio();
|
||||
ChannelMessageStore().forgetArchive();
|
||||
MessageStore().forgetArchive();
|
||||
});
|
||||
|
||||
test('restoreLastRadio shows the saved radio while disconnected', () async {
|
||||
final connector = _newConnector();
|
||||
expect(connector.hasRadioData, isFalse);
|
||||
|
||||
await connector.restoreLastRadio();
|
||||
|
||||
expect(connector.isConnected, isFalse);
|
||||
expect(connector.hasRadioData, isTrue);
|
||||
expect(connector.storageKeyHex, _radioHex);
|
||||
expect(connector.lastRadioName, 'Base');
|
||||
expect(connector.lastRadio?.canReconnectBle, isTrue);
|
||||
|
||||
// The radio's own entry is filtered out of the contact list.
|
||||
expect(connector.contacts.map((c) => c.name), ['Alice']);
|
||||
final alice = connector.contacts.single;
|
||||
expect(
|
||||
connector.getMessages(alice).map((m) => m.text),
|
||||
containsAll(['hi there', 'did not go out']),
|
||||
);
|
||||
expect(connector.getUnreadCountForContact(alice), 2);
|
||||
|
||||
expect(connector.channels.map((c) => c.name), ['Base Camp']);
|
||||
expect(
|
||||
connector
|
||||
.getChannelMessages(connector.channels.single)
|
||||
.map((m) => m.text),
|
||||
['camp is up'],
|
||||
);
|
||||
});
|
||||
|
||||
test('resend while offline keeps the message', () async {
|
||||
final connector = _newConnector();
|
||||
await connector.restoreLastRadio();
|
||||
final alice = connector.contacts.single;
|
||||
final failed = connector
|
||||
.getMessages(alice)
|
||||
.firstWhere((m) => m.text == 'did not go out');
|
||||
|
||||
await connector.resendMessage(alice, failed);
|
||||
|
||||
expect(
|
||||
connector.getMessages(alice).where((m) => m.text == 'did not go out'),
|
||||
hasLength(1),
|
||||
);
|
||||
final stored = await (MessageStore()..setPublicKeyHex = _radioHex)
|
||||
.loadMessages(alice.publicKeyHex);
|
||||
expect(stored.map((m) => m.text), contains('did not go out'));
|
||||
});
|
||||
|
||||
test('sendFrame throws RadioNotConnectedException offline', () async {
|
||||
final connector = _newConnector();
|
||||
await expectLater(
|
||||
connector.sendFrame(Uint8List.fromList([1])),
|
||||
throwsA(isA<RadioNotConnectedException>()),
|
||||
);
|
||||
});
|
||||
|
||||
test('a review session neither replaces the remembered radio nor keeps its '
|
||||
'channels, and the saved radio is back afterwards', () async {
|
||||
final connector = _newConnector();
|
||||
connector.reviewRadioFactoryForTest = () => ReviewRadio(
|
||||
scheduledMessageInterval: const Duration(hours: 1),
|
||||
ackDelay: const Duration(milliseconds: 100),
|
||||
replyDelay: const Duration(milliseconds: 200),
|
||||
);
|
||||
await connector.restoreLastRadio();
|
||||
expect(connector.channels.map((c) => c.name), ['Base Camp']);
|
||||
|
||||
await connector.connectReview();
|
||||
expect(connector.isReviewMode, isTrue);
|
||||
await _waitFor(() => connector.channels.length >= 3);
|
||||
|
||||
// A different radio answered: the saved radio's channels are gone.
|
||||
expect(connector.channels.map((c) => c.name), isNot(contains('Base Camp')));
|
||||
expect(connector.contacts.map((c) => c.name), isNot(contains('Alice')));
|
||||
expect(connector.storageKeyHex, isNot(_radioHex));
|
||||
expect(LastRadioStore().load()?.publicKeyHex, _radioHex);
|
||||
|
||||
await connector.disconnect();
|
||||
await _waitFor(
|
||||
() =>
|
||||
connector.channels.any((c) => c.name == 'Base Camp') &&
|
||||
connector.contacts.any((c) => c.name == 'Alice'),
|
||||
);
|
||||
expect(connector.isConnected, isFalse);
|
||||
expect(connector.storageKeyHex, _radioHex);
|
||||
expect(connector.lastRadio?.publicKeyHex, _radioHex);
|
||||
expect(LastRadioStore().load()?.publicKeyHex, _radioHex);
|
||||
final alice = connector.contacts.firstWhere((c) => c.name == 'Alice');
|
||||
expect(
|
||||
connector.getMessages(alice).map((m) => m.text),
|
||||
contains('hi there'),
|
||||
);
|
||||
expect(connector.getUnreadCountForContact(alice), 2);
|
||||
// Review data never lands under the real radio's keys.
|
||||
final channels = await (ChannelStore()..setPublicKeyHex = _radioHex)
|
||||
.loadChannels();
|
||||
expect(channels.map((c) => c.name), ['Base Camp']);
|
||||
});
|
||||
|
||||
test('without a remembered radio nothing is loaded', () async {
|
||||
await LastRadioStore().clear();
|
||||
final connector = _newConnector();
|
||||
await connector.restoreLastRadio();
|
||||
expect(connector.hasRadioData, isFalse);
|
||||
expect(connector.contacts, isEmpty);
|
||||
expect(connector.channels, isEmpty);
|
||||
expect(connector.lastRadio, isNull);
|
||||
});
|
||||
|
||||
test('stored last_radio is JSON with the full key', () {
|
||||
final raw = PrefsManager.instance.getString(LastRadioStore.prefsKey)!;
|
||||
expect((jsonDecode(raw) as Map)['publicKeyHex'], _radioHex);
|
||||
});
|
||||
}
|
||||
@@ -51,6 +51,21 @@ void main() {
|
||||
expect(queue.length, 0);
|
||||
});
|
||||
|
||||
test('firmware-disabled private-key transfer fails its waiter', () async {
|
||||
final queue = newQueue();
|
||||
final pending = queue.track(
|
||||
buildExportPrivateKeyFrame(),
|
||||
waitForReply: true,
|
||||
);
|
||||
|
||||
expect(queue.completeReply(frame([respCodeDisabled])), isTrue);
|
||||
await expectLater(
|
||||
pending!.completer!.future,
|
||||
throwsA(isA<UnsupportedError>()),
|
||||
);
|
||||
expect(queue.length, 0);
|
||||
});
|
||||
|
||||
test('untracked commands are not enrolled', () {
|
||||
final queue = newQueue();
|
||||
expect(queue.track(buildSyncNextMessageFrame()), isNull);
|
||||
|
||||
@@ -78,6 +78,8 @@ void main() {
|
||||
expect(connector.contacts, isNotEmpty);
|
||||
expect(listed(), isFalse);
|
||||
|
||||
// Contact saves are batched; land them before reading the store.
|
||||
await connector.flushPendingWrites();
|
||||
final store = ContactStore()..setPublicKeyHex = connector.selfPublicKeyHex;
|
||||
final saved = await store.loadContacts();
|
||||
expect(saved.any((c) => c.publicKeyHex == contact.publicKeyHex), isFalse);
|
||||
|
||||
@@ -208,14 +208,13 @@ void main() {
|
||||
_connector.state == MeshCoreConnectionState.disconnected &&
|
||||
_connector.isAutoReconnectScheduled,
|
||||
);
|
||||
await _waitFor(
|
||||
() => !_connector.isAutoReconnectScheduled,
|
||||
pollInterval: const Duration(milliseconds: 1),
|
||||
);
|
||||
// The timer firing proves an attempt started; wait for its failure to
|
||||
// finish and the next backoff to become active.
|
||||
final firstScheduledAttempt = _connector.reconnectAttemptsForTesting;
|
||||
// Wait for the failed attempt to schedule its next backoff. The timer's
|
||||
// inactive window can be shorter than a test poll interval, so observe
|
||||
// the monotonic retry count instead of trying to catch that window.
|
||||
await _waitFor(
|
||||
() =>
|
||||
_connector.reconnectAttemptsForTesting > firstScheduledAttempt &&
|
||||
_connector.state == MeshCoreConnectionState.disconnected &&
|
||||
_connector.isAutoReconnectScheduled,
|
||||
);
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/helpers/chat_jump.dart';
|
||||
|
||||
/// A reversed chat-style list with uneven row heights, so the list's extent
|
||||
/// estimate is wrong and the helper has to walk to the target.
|
||||
Widget _list(ScrollController controller, int count) {
|
||||
return MaterialApp(
|
||||
home: Scaffold(
|
||||
body: ListView.builder(
|
||||
reverse: true,
|
||||
controller: controller,
|
||||
itemCount: count,
|
||||
itemBuilder: (context, index) => SizedBox(
|
||||
key: ValueKey('row$index'),
|
||||
height: 40.0 + (index % 7) * 30,
|
||||
child: Text('row $index'),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void main() {
|
||||
for (final target in [0, 7, 250, 499]) {
|
||||
testWidgets('brings row $target of 500 on screen', (tester) async {
|
||||
final controller = ScrollController();
|
||||
addTearDown(controller.dispose);
|
||||
await tester.pumpWidget(_list(controller, 500));
|
||||
|
||||
late bool found;
|
||||
final done = scrollListToIndex(
|
||||
controller: controller,
|
||||
targetIndex: target,
|
||||
itemCount: 500,
|
||||
isMounted: () => true,
|
||||
).then((value) => found = value);
|
||||
// Drive frames until the helper finishes.
|
||||
for (var i = 0; i < 200; i++) {
|
||||
await tester.pump(const Duration(milliseconds: 50));
|
||||
}
|
||||
await done;
|
||||
|
||||
expect(found, isTrue);
|
||||
final row = find.byKey(ValueKey('row$target'));
|
||||
expect(row, findsOneWidget);
|
||||
final rect = tester.getRect(row);
|
||||
final screen = tester.getRect(find.byType(ListView));
|
||||
expect(screen.overlaps(rect), isTrue);
|
||||
});
|
||||
}
|
||||
|
||||
// Codex's case: older rows much taller than recent ones, so the first
|
||||
// estimate lands hundreds of rows short.
|
||||
testWidgets('reaches a row far past rows of a very different height', (
|
||||
tester,
|
||||
) async {
|
||||
final controller = ScrollController();
|
||||
addTearDown(controller.dispose);
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: Scaffold(
|
||||
body: ListView.builder(
|
||||
reverse: true,
|
||||
controller: controller,
|
||||
itemCount: 2000,
|
||||
itemBuilder: (_, i) => SizedBox(
|
||||
key: ValueKey('row$i'),
|
||||
height: i < 1000 ? 60 : 300,
|
||||
child: Text('row $i'),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
bool? found;
|
||||
final done = scrollListToIndex(
|
||||
controller: controller,
|
||||
targetIndex: 1500,
|
||||
itemCount: 2000,
|
||||
isMounted: () => true,
|
||||
).then((v) => found = v);
|
||||
for (var i = 0; i < 300; i++) {
|
||||
await tester.pump(const Duration(milliseconds: 50));
|
||||
}
|
||||
await done;
|
||||
expect(found, isTrue);
|
||||
expect(find.byKey(const ValueKey('row1500')), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('rejects an index outside the list', (tester) async {
|
||||
final controller = ScrollController();
|
||||
addTearDown(controller.dispose);
|
||||
await tester.pumpWidget(_list(controller, 10));
|
||||
expect(
|
||||
await scrollListToIndex(
|
||||
controller: controller,
|
||||
targetIndex: 10,
|
||||
itemCount: 10,
|
||||
isMounted: () => true,
|
||||
),
|
||||
isFalse,
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/helpers/contact_share_message.dart';
|
||||
|
||||
const _hex = '50ba28f599799142622d188469a63f3890d495cdcedd24239052abd364c0283d';
|
||||
|
||||
void main() {
|
||||
test('parses the official example', () {
|
||||
final s = parseContactShare('<$_hex:1:CC>')!;
|
||||
expect(s.publicKeyHex, _hex);
|
||||
expect(s.type, 1);
|
||||
expect(s.name, 'CC');
|
||||
expect(s.publicKey.length, 32);
|
||||
expect(s.shortKey, '50ba28...c0283d');
|
||||
final scanned = s.toScannedContact();
|
||||
expect(scanned.publicKey, s.publicKey);
|
||||
expect(scanned.type, 1);
|
||||
expect(scanned.name, 'CC');
|
||||
});
|
||||
|
||||
test('round trip', () {
|
||||
final key = Uint8List.fromList(List.generate(32, (i) => i * 7 % 256));
|
||||
final text = encodeContactShare(publicKey: key, type: 2, name: ' Hill ');
|
||||
final s = parseContactShare(text)!;
|
||||
expect(s.publicKey, key);
|
||||
expect(s.type, 2);
|
||||
expect(s.name, 'Hill');
|
||||
});
|
||||
|
||||
test('encode strips angle brackets and newlines', () {
|
||||
final text = encodeContactShare(
|
||||
publicKey: Uint8List(32),
|
||||
type: 1,
|
||||
name: '<a>\nb\r',
|
||||
);
|
||||
expect(parseContactShare(text)!.name, 'ab');
|
||||
});
|
||||
|
||||
test('uppercase hex is accepted and lowercased', () {
|
||||
final s = parseContactShare('<${_hex.toUpperCase()}:3:Room>')!;
|
||||
expect(s.publicKeyHex, _hex);
|
||||
});
|
||||
|
||||
test('name may contain colons', () {
|
||||
expect(parseContactShare('<$_hex:1:a:b:c>')!.name, 'a:b:c');
|
||||
});
|
||||
|
||||
test('surrounding whitespace is ignored', () {
|
||||
expect(parseContactShare(' \n<$_hex:4:S>\n ')!.type, 4);
|
||||
});
|
||||
|
||||
test('rejects bad length, hex, type', () {
|
||||
expect(parseContactShare('<${_hex.substring(2)}:1:x>'), isNull);
|
||||
expect(parseContactShare('<${_hex}00:1:x>'), isNull);
|
||||
expect(parseContactShare('<${"zz${_hex.substring(2)}"}:1:x>'), isNull);
|
||||
expect(parseContactShare('<$_hex:0:x>'), isNull);
|
||||
expect(parseContactShare('<$_hex:5:x>'), isNull);
|
||||
expect(parseContactShare('<$_hex:12:x>'), isNull);
|
||||
expect(parseContactShare('<$_hex:a:x>'), isNull);
|
||||
});
|
||||
|
||||
test('token among other words is not a share', () {
|
||||
expect(parseContactShare('look <$_hex:1:CC> here'), isNull);
|
||||
expect(parseContactShare('<$_hex:1:CC> hi'), isNull);
|
||||
expect(parseContactShare('hello'), isNull);
|
||||
});
|
||||
|
||||
test('findContactShare locates a token inside copied text', () {
|
||||
final s = findContactShare('Alice: <$_hex:2:Hilltop Rpt>')!;
|
||||
expect(s.publicKeyHex, _hex);
|
||||
expect(s.type, 2);
|
||||
expect(s.name, 'Hilltop Rpt');
|
||||
expect(findContactShare('look <$_hex:1:CC> here')!.name, 'CC');
|
||||
expect(findContactShare('meshcore://abcdef'), isNull);
|
||||
expect(findContactShare('<$_hex:9:x>'), isNull);
|
||||
});
|
||||
}
|
||||
@@ -69,8 +69,12 @@ void main() {
|
||||
|
||||
group('HolidayTriggerWatcher', () {
|
||||
late AppSettingsService settings;
|
||||
late DateTime now;
|
||||
|
||||
setUp(() async {
|
||||
now = DateTime(2026, 12, 25, 12);
|
||||
holidayAnimationClock = () => now;
|
||||
resetHolidayAnimationGate();
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
await PrefsManager.initialize();
|
||||
settings = AppSettingsService();
|
||||
@@ -147,6 +151,7 @@ void main() {
|
||||
) async {
|
||||
final ctx = await host(tester);
|
||||
for (final animation in HolidayAnimation.values) {
|
||||
now = now.add(holidayAnimationMinInterval);
|
||||
playHolidayAnimation(ctx, animation, origin: const Offset(80, 500));
|
||||
await tester.pump();
|
||||
expect(find.byType(HolidayAnimationView), findsOneWidget);
|
||||
@@ -157,6 +162,42 @@ void main() {
|
||||
}
|
||||
});
|
||||
|
||||
testWidgets('one at a time, then 5 quiet seconds after it ends', (
|
||||
tester,
|
||||
) async {
|
||||
final ctx = await host(tester);
|
||||
void play(HolidayAnimation a) =>
|
||||
playHolidayAnimation(ctx, a, origin: Offset.zero);
|
||||
|
||||
play(HolidayAnimation.christmas);
|
||||
await tester.pump();
|
||||
expect(find.byType(HolidayAnimationView), findsOneWidget);
|
||||
|
||||
// Still playing: a second greeting is dropped, not stacked or queued.
|
||||
now = now.add(const Duration(seconds: 30));
|
||||
play(HolidayAnimation.newYear);
|
||||
await tester.pump();
|
||||
expect(find.byType(HolidayAnimationView), findsOneWidget);
|
||||
await tester.pumpAndSettle(); // christmas ends at `now`
|
||||
expect(find.byType(HolidayAnimationView), findsNothing);
|
||||
// Nothing was queued behind it.
|
||||
await tester.pump(const Duration(seconds: 10));
|
||||
expect(find.byType(HolidayAnimationView), findsNothing);
|
||||
|
||||
// Under 5 seconds after it ended: dropped.
|
||||
now = now.add(const Duration(seconds: 4));
|
||||
play(HolidayAnimation.newYear);
|
||||
await tester.pump();
|
||||
expect(find.byType(HolidayAnimationView), findsNothing);
|
||||
|
||||
// 5 seconds after it ended: plays.
|
||||
now = now.add(const Duration(seconds: 1));
|
||||
play(HolidayAnimation.newYear);
|
||||
await tester.pump();
|
||||
expect(find.byType(HolidayAnimationView), findsOneWidget);
|
||||
await tester.pumpAndSettle();
|
||||
});
|
||||
|
||||
testWidgets('respects the setting and reduced motion', (tester) async {
|
||||
await settings.setHolidayAnimationsEnabled(false);
|
||||
var ctx = await host(tester);
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/helpers/message_search.dart';
|
||||
|
||||
ChatSearchEntry _e(
|
||||
String id,
|
||||
String text, {
|
||||
String sender = 'Alice',
|
||||
String? translated,
|
||||
bool matchSender = false,
|
||||
int minute = 0,
|
||||
}) => ChatSearchEntry(
|
||||
id: id,
|
||||
sender: sender,
|
||||
text: text,
|
||||
translatedText: translated,
|
||||
time: DateTime(2025, 1, 1, 12, minute),
|
||||
matchSender: matchSender,
|
||||
);
|
||||
|
||||
void main() {
|
||||
test('matches case-insensitively', () {
|
||||
final r = searchEntries([_e('1', 'Hello World')], 'wORLD');
|
||||
expect(r.map((e) => e.id), ['1']);
|
||||
});
|
||||
|
||||
test('matches translated text', () {
|
||||
final r = searchEntries([
|
||||
_e('1', 'hola', translated: 'hello there'),
|
||||
], 'THERE');
|
||||
expect(r, hasLength(1));
|
||||
});
|
||||
|
||||
test('sender matches only when matchSender is set', () {
|
||||
final entries = [
|
||||
_e('1', 'x', sender: 'Bobby', matchSender: true),
|
||||
_e('2', 'y', sender: 'Bobby'),
|
||||
];
|
||||
expect(searchEntries(entries, 'bob').map((e) => e.id), ['1']);
|
||||
});
|
||||
|
||||
test('results are newest first', () {
|
||||
final entries = [
|
||||
_e('1', 'ping', minute: 1),
|
||||
_e('2', 'nope', minute: 2),
|
||||
_e('3', 'ping', minute: 3),
|
||||
];
|
||||
expect(searchEntries(entries, 'ping').map((e) => e.id), ['3', '1']);
|
||||
});
|
||||
|
||||
test('empty or whitespace query yields no results', () {
|
||||
final entries = [_e('1', 'anything')];
|
||||
expect(searchEntries(entries, ''), isEmpty);
|
||||
expect(searchEntries(entries, ' '), isEmpty);
|
||||
});
|
||||
|
||||
test('query is trimmed', () {
|
||||
expect(searchEntries([_e('1', 'abc def')], ' def '), hasLength(1));
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/helpers/path_trace_input.dart';
|
||||
|
||||
void main() {
|
||||
PathTraceParseResult p(String s, [int w = 1]) =>
|
||||
PathTraceInputParser.parse(s, w);
|
||||
|
||||
test('comma separated, case-insensitive', () {
|
||||
final r = p('a1,B2,c3').input!;
|
||||
expect(r.hopWidth, 1);
|
||||
expect(r.bytes, [0xa1, 0xb2, 0xc3]);
|
||||
expect(r.hops.length, 3);
|
||||
});
|
||||
|
||||
test('mixed separators and 0x prefixes', () {
|
||||
final r = p('0xA1 > b2 → 0Xc3/d4\n-e5').input!;
|
||||
expect(r.bytes, [0xa1, 0xb2, 0xc3, 0xd4, 0xe5]);
|
||||
});
|
||||
|
||||
test('two and three byte hops define width', () {
|
||||
expect(p('a1b2,c3d4', 1).input!.hopWidth, 2);
|
||||
final r = p('a1b2c3 d4e5f6', 1).input!;
|
||||
expect(r.hopWidth, 3);
|
||||
expect(r.hops.last, [0xd4, 0xe5, 0xf6]);
|
||||
});
|
||||
|
||||
test('continuous string splits by default width', () {
|
||||
expect(p('a1b2c3d4', 1).input!.hops.length, 4);
|
||||
expect(p('a1b2c3d4', 2).input!.hops.length, 2);
|
||||
expect(p('a1b2c3', 3).input!.hopWidth, 3);
|
||||
expect(p('a1b2c3', 2).error, PathTraceInputError.oddLength);
|
||||
});
|
||||
|
||||
test('errors', () {
|
||||
expect(p(' ').error, PathTraceInputError.empty);
|
||||
expect(p('a1,zz').error, PathTraceInputError.invalidHex);
|
||||
expect(p('a1,b').error, PathTraceInputError.oddLength);
|
||||
expect(p('abc').error, PathTraceInputError.oddLength);
|
||||
expect(p('a1,b2c3').error, PathTraceInputError.mixedWidths);
|
||||
expect(p('a1b2c3d4,e5f6a7b8').error, PathTraceInputError.unsupportedWidth);
|
||||
});
|
||||
|
||||
test('too many hops', () {
|
||||
final ok = List.filled(64, 'aa').join(',');
|
||||
expect(p(ok).isValid, isTrue);
|
||||
expect(p('$ok,bb').error, PathTraceInputError.tooManyHops);
|
||||
final wide = List.filled(22, 'aabbcc').join(',');
|
||||
expect(p(wide).error, PathTraceInputError.tooManyHops);
|
||||
});
|
||||
|
||||
group('traceFitsInRequest', () {
|
||||
PathTraceInput hops(int count, int width) => PathTraceInputParser.parse(
|
||||
List.generate(count, (i) => 'ab' * width).join(','),
|
||||
width,
|
||||
).input!;
|
||||
|
||||
test('round trip of 21 three-byte hops exceeds the frame limit', () {
|
||||
// 41 hops x 4-byte trace prefixes + 10-byte header = 174 > 172.
|
||||
expect(traceFitsInRequest(hops(21, 3), roundTrip: true), isFalse);
|
||||
expect(traceFitsInRequest(hops(21, 3), roundTrip: false), isTrue);
|
||||
});
|
||||
|
||||
test('round trip of 20 three-byte hops fits', () {
|
||||
// 39 x 4 + 10 = 166.
|
||||
expect(traceFitsInRequest(hops(20, 3), roundTrip: true), isTrue);
|
||||
});
|
||||
|
||||
test('hop count is capped at 64 even when bytes fit', () {
|
||||
// 33 one-byte hops round trip = 65 hops.
|
||||
expect(traceFitsInRequest(hops(33, 1), roundTrip: true), isFalse);
|
||||
expect(traceFitsInRequest(hops(32, 1), roundTrip: true), isTrue);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -454,6 +454,42 @@ void main() {
|
||||
expect(sendOnly.isComplete, isFalse);
|
||||
});
|
||||
|
||||
test('only considers a complete bundle installed', () {
|
||||
final spec = imageCodecPresetModels.single;
|
||||
ImageCodecModelRecord record({
|
||||
required int bundleVersion,
|
||||
required List<String> assetFileNames,
|
||||
required Map<String, ImageCodecAssetRole> assetRoles,
|
||||
}) => ImageCodecModelRecord(
|
||||
id: spec.id,
|
||||
name: spec.fileName,
|
||||
sourceUrl: spec.graph.sourceUrl,
|
||||
localPath: '/models/${spec.fileName}',
|
||||
downloadedAt: DateTime.fromMillisecondsSinceEpoch(0),
|
||||
fileSizeBytes: 10,
|
||||
assetFileNames: assetFileNames,
|
||||
assetRoles: assetRoles,
|
||||
bundleVersion: bundleVersion,
|
||||
);
|
||||
|
||||
final completeRecord = record(
|
||||
bundleVersion: kImageCodecBundleVersion,
|
||||
assetFileNames: [for (final asset in spec.assets) asset.fileName],
|
||||
assetRoles: {
|
||||
for (final asset in spec.assets) asset.fileName: asset.role,
|
||||
},
|
||||
);
|
||||
final partialRecord = record(
|
||||
bundleVersion: 0,
|
||||
assetFileNames: [spec.fileName],
|
||||
assetRoles: {spec.fileName: ImageCodecAssetRole.decoderGraph},
|
||||
);
|
||||
|
||||
expect(spec.hasCompleteInstalledRecord([completeRecord]), isTrue);
|
||||
expect(spec.hasCompleteInstalledRecord([partialRecord]), isFalse);
|
||||
expect(spec.hasCompleteInstalledRecord([]), isFalse);
|
||||
});
|
||||
|
||||
test('uses the HuggingFace resolve/main URL shape', () {
|
||||
for (final asset in imageCodecPresetModels.single.assets) {
|
||||
expect(asset.sourceUrl, startsWith('https://huggingface.co/'));
|
||||
|
||||
@@ -0,0 +1,263 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_localizations/flutter_localizations.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:provider/single_child_widget.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import 'package:meshcore_open/connector/meshcore_connector.dart';
|
||||
import 'package:meshcore_open/connector/meshcore_protocol.dart';
|
||||
import 'package:meshcore_open/l10n/app_localizations.dart';
|
||||
import 'package:meshcore_open/review_mode/review_radio.dart';
|
||||
import 'package:meshcore_open/screens/channel_chat_screen.dart';
|
||||
import 'package:meshcore_open/screens/chat_screen.dart';
|
||||
import 'package:meshcore_open/services/app_debug_log_service.dart';
|
||||
import 'package:meshcore_open/services/app_settings_service.dart';
|
||||
import 'package:meshcore_open/services/ble_debug_log_service.dart';
|
||||
import 'package:meshcore_open/services/chat_text_scale_service.dart';
|
||||
import 'package:meshcore_open/services/image_codec_service.dart';
|
||||
import 'package:meshcore_open/services/map_tile_cache_service.dart';
|
||||
import 'package:meshcore_open/services/message_retry_service.dart';
|
||||
import 'package:meshcore_open/services/path_history_service.dart';
|
||||
import 'package:meshcore_open/services/received_image_store.dart';
|
||||
import 'package:meshcore_open/services/storage_service.dart';
|
||||
import 'package:meshcore_open/services/timeout_prediction_service.dart';
|
||||
import 'package:meshcore_open/services/translation_service.dart';
|
||||
import 'package:meshcore_open/services/ui_view_state_service.dart';
|
||||
import 'package:meshcore_open/storage/prefs_manager.dart';
|
||||
import 'package:meshcore_open/theme/mesh_theme.dart';
|
||||
|
||||
/// Chat screen behaviour that depends on navigation: which conversation is
|
||||
/// active while chats are covered, and jumping to a search result.
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
final tempDir = Directory.systemTemp.createTempSync('active_conv_test');
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(
|
||||
const MethodChannel('plugins.flutter.io/path_provider'),
|
||||
(call) async => tempDir.path,
|
||||
);
|
||||
|
||||
setUpAll(() async {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
PrefsManager.reset();
|
||||
await PrefsManager.initialize();
|
||||
});
|
||||
|
||||
// A chat covered by another page (e.g. one opened from a notification) must
|
||||
// stop being the active conversation, and become active again once the page
|
||||
// on top is popped, so unread counting matches what is on screen.
|
||||
testWidgets('covered chats unregister and re-register when uncovered', (
|
||||
tester,
|
||||
) async {
|
||||
final (connector, navigatorKey) = await _pumpChannelChat(tester);
|
||||
final channelA = connector.channels[0];
|
||||
final channelB = connector.channels[1];
|
||||
final contact = connector.contacts.firstWhere((c) => c.type == advTypeChat);
|
||||
|
||||
expect(connector.activeChannelIndex, channelA.index);
|
||||
|
||||
// Channel B opened on top (as a notification tap does).
|
||||
navigatorKey.currentState!.push(
|
||||
MaterialPageRoute(builder: (_) => ChannelChatScreen(channel: channelB)),
|
||||
);
|
||||
await _settle(tester);
|
||||
expect(connector.activeChannelIndex, channelB.index);
|
||||
|
||||
navigatorKey.currentState!.pop();
|
||||
await _settle(tester);
|
||||
expect(connector.activeChannelIndex, channelA.index);
|
||||
|
||||
// A DM on top hides the channel entirely.
|
||||
navigatorKey.currentState!.push(
|
||||
MaterialPageRoute(builder: (_) => ChatScreen(contact: contact)),
|
||||
);
|
||||
await _settle(tester);
|
||||
expect(connector.activeChannelIndex, isNull);
|
||||
expect(connector.activeContactKey, contact.publicKeyHex);
|
||||
|
||||
navigatorKey.currentState!.pop();
|
||||
await _settle(tester);
|
||||
expect(connector.activeContactKey, isNull);
|
||||
expect(connector.activeChannelIndex, channelA.index);
|
||||
|
||||
// A page pushed without a transition never reports `forward`.
|
||||
navigatorKey.currentState!.push(
|
||||
_InstantPageRoute(builder: (_) => const Scaffold()),
|
||||
);
|
||||
await _settle(tester);
|
||||
expect(connector.activeChannelIndex, isNull);
|
||||
|
||||
navigatorKey.currentState!.pop();
|
||||
await _settle(tester);
|
||||
expect(connector.activeChannelIndex, channelA.index);
|
||||
|
||||
await _tearDown(tester);
|
||||
expect(connector.activeChannelIndex, isNull);
|
||||
});
|
||||
|
||||
testWidgets('tapping a search result closes search and shows the message', (
|
||||
tester,
|
||||
) async {
|
||||
tester.view.physicalSize = const Size(400, 700);
|
||||
tester.view.devicePixelRatio = 1.0;
|
||||
addTearDown(tester.view.reset);
|
||||
|
||||
final (connector, _) = await _pumpChannelChat(tester);
|
||||
final messages = connector.getChannelMessages(connector.channels[0]);
|
||||
expect(messages, isNotEmpty);
|
||||
// The oldest message: furthest from where the chat opens (the bottom).
|
||||
final target = messages.first;
|
||||
final word = target.text
|
||||
.split(RegExp(r'\s+'))
|
||||
.firstWhere((w) => w.length >= 4, orElse: () => target.text);
|
||||
|
||||
await tester.tap(find.byTooltip('Search messages'));
|
||||
await _settle(tester);
|
||||
await tester.enterText(
|
||||
find.descendant(
|
||||
of: find.byType(AppBar),
|
||||
matching: find.byType(TextField),
|
||||
),
|
||||
word,
|
||||
);
|
||||
await _settle(tester);
|
||||
|
||||
// Results show sender + time headers; tap the row holding the target.
|
||||
final result = find.descendant(
|
||||
of: find.byType(ListView),
|
||||
matching: find.textContaining(target.text, findRichText: true),
|
||||
);
|
||||
expect(result, findsWidgets);
|
||||
await tester.tap(result.first);
|
||||
for (var i = 0; i < 40; i++) {
|
||||
await tester.pump(const Duration(milliseconds: 100));
|
||||
}
|
||||
|
||||
// Search is closed and the message bubble is on screen.
|
||||
expect(find.byTooltip('Close search'), findsNothing);
|
||||
final bubble = find.textContaining(target.text, findRichText: true);
|
||||
expect(bubble, findsWidgets);
|
||||
final screen = Offset.zero & const Size(400, 700);
|
||||
expect(
|
||||
bubble.evaluate().any((e) {
|
||||
final box = e.renderObject as RenderBox?;
|
||||
if (box == null || !box.hasSize) return false;
|
||||
return screen.overlaps(box.localToGlobal(Offset.zero) & box.size);
|
||||
}),
|
||||
isTrue,
|
||||
);
|
||||
|
||||
await _tearDown(tester);
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _settle(WidgetTester tester) async {
|
||||
for (var i = 0; i < 10; i++) {
|
||||
await tester.pump(const Duration(milliseconds: 100));
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _tearDown(WidgetTester tester) async {
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
await tester.pump(const Duration(minutes: 1));
|
||||
}
|
||||
|
||||
/// One review-radio connection shared by the tests: reconnecting it in the
|
||||
/// same run does not resend the channel list.
|
||||
(MeshCoreConnector, List<SingleChildWidget>)? _shared;
|
||||
|
||||
/// Connects the review radio (once) and shows the first channel's chat.
|
||||
Future<(MeshCoreConnector, GlobalKey<NavigatorState>)> _pumpChannelChat(
|
||||
WidgetTester tester,
|
||||
) async {
|
||||
final (connector, providers) = _shared ??= await _connect(tester);
|
||||
final navigatorKey = GlobalKey<NavigatorState>();
|
||||
await tester.pumpWidget(
|
||||
MultiProvider(
|
||||
providers: providers,
|
||||
child: MaterialApp(
|
||||
navigatorKey: navigatorKey,
|
||||
theme: MeshTheme.light(),
|
||||
locale: const Locale('en'),
|
||||
localizationsDelegates: const [
|
||||
AppLocalizations.delegate,
|
||||
GlobalMaterialLocalizations.delegate,
|
||||
GlobalWidgetsLocalizations.delegate,
|
||||
GlobalCupertinoLocalizations.delegate,
|
||||
],
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
home: ChannelChatScreen(channel: connector.channels[0]),
|
||||
),
|
||||
),
|
||||
);
|
||||
await _settle(tester);
|
||||
return (connector, navigatorKey);
|
||||
}
|
||||
|
||||
Future<(MeshCoreConnector, List<SingleChildWidget>)> _connect(
|
||||
WidgetTester tester,
|
||||
) async {
|
||||
final storage = StorageService();
|
||||
final connector = MeshCoreConnector();
|
||||
final retry = MessageRetryService();
|
||||
final settings = AppSettingsService();
|
||||
final translation = TranslationService(settings);
|
||||
await tester.runAsync(() async {
|
||||
await settings.loadSettings();
|
||||
connector.initialize(
|
||||
retryService: retry,
|
||||
pathHistoryService: PathHistoryService(storage),
|
||||
appSettingsService: settings,
|
||||
translationService: translation,
|
||||
);
|
||||
connector.reviewRadioFactoryForTest = () => ReviewRadio(
|
||||
scheduledMessageInterval: const Duration(hours: 1),
|
||||
ackDelay: const Duration(hours: 1),
|
||||
replyDelay: const Duration(hours: 1),
|
||||
);
|
||||
await connector.connectReview();
|
||||
final end = DateTime.now().add(const Duration(seconds: 8));
|
||||
while ((connector.contacts.isEmpty || connector.channels.length < 2) &&
|
||||
DateTime.now().isBefore(end)) {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 25));
|
||||
}
|
||||
});
|
||||
expect(connector.channels.length, greaterThanOrEqualTo(2));
|
||||
|
||||
return (
|
||||
connector,
|
||||
<SingleChildWidget>[
|
||||
ChangeNotifierProvider.value(value: connector),
|
||||
ChangeNotifierProvider.value(value: retry),
|
||||
ChangeNotifierProvider.value(value: PathHistoryService(storage)),
|
||||
ChangeNotifierProvider.value(value: settings),
|
||||
ChangeNotifierProvider.value(value: BleDebugLogService()),
|
||||
ChangeNotifierProvider.value(value: AppDebugLogService()),
|
||||
ChangeNotifierProvider.value(value: ChatTextScaleService()),
|
||||
ChangeNotifierProvider.value(value: translation),
|
||||
ChangeNotifierProvider.value(value: UiViewStateService()),
|
||||
Provider.value(value: storage),
|
||||
ChangeNotifierProvider.value(
|
||||
value: MapTileCacheService(appSettingsService: settings),
|
||||
),
|
||||
ChangeNotifierProvider.value(value: TimeoutPredictionService(storage)),
|
||||
ChangeNotifierProvider.value(value: ImageCodecService(settings)),
|
||||
ChangeNotifierProvider.value(value: ReceivedImageStore()),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
class _InstantPageRoute extends MaterialPageRoute<void> {
|
||||
_InstantPageRoute({required super.builder});
|
||||
|
||||
@override
|
||||
Duration get transitionDuration => Duration.zero;
|
||||
|
||||
@override
|
||||
Duration get reverseTransitionDuration => Duration.zero;
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_map/flutter_map.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
|
||||
import 'package:latlong2/latlong.dart';
|
||||
import 'package:meshcore_open/connector/meshcore_connector.dart';
|
||||
import 'package:meshcore_open/l10n/app_localizations.dart';
|
||||
import 'package:meshcore_open/screens/map_screen.dart';
|
||||
import 'package:meshcore_open/services/app_settings_service.dart';
|
||||
import 'package:meshcore_open/services/map_tile_cache_service.dart';
|
||||
import 'package:meshcore_open/services/path_history_service.dart';
|
||||
import 'package:meshcore_open/services/storage_service.dart';
|
||||
import 'package:meshcore_open/services/ui_view_state_service.dart';
|
||||
import 'package:meshcore_open/storage/prefs_manager.dart';
|
||||
import 'package:meshcore_open/theme/mesh_theme.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
const _cameraKey = 'flutter.map_last_camera';
|
||||
const _preferencesChannel = MethodChannel(
|
||||
'plugins.flutter.io/shared_preferences',
|
||||
);
|
||||
|
||||
class _UnusedCacheManager implements BaseCacheManager {
|
||||
@override
|
||||
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
|
||||
}
|
||||
|
||||
class _MapWithoutTiles extends MapTileCacheService {
|
||||
_MapWithoutTiles(AppSettingsService settings)
|
||||
: super(appSettingsService: settings, cacheManager: _UnusedCacheManager());
|
||||
|
||||
@override
|
||||
Widget buildTileLayer(BuildContext context, {double opacity = 1}) =>
|
||||
const SizedBox.shrink();
|
||||
}
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
late Map<String, Object> persisted;
|
||||
late List<List<String>> cameraWrites;
|
||||
|
||||
setUp(() async {
|
||||
persisted = {};
|
||||
cameraWrites = [];
|
||||
SharedPreferences.resetStatic();
|
||||
PrefsManager.reset();
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(_preferencesChannel, (call) async {
|
||||
if (call.method == 'getAll') return persisted;
|
||||
final args = call.arguments as Map<dynamic, dynamic>;
|
||||
final key = args['key'] as String;
|
||||
if (call.method == 'remove') {
|
||||
persisted.remove(key);
|
||||
} else {
|
||||
persisted[key] = args['value'] as Object;
|
||||
if (key == _cameraKey) {
|
||||
cameraWrites.add(List<String>.from(args['value'] as List));
|
||||
}
|
||||
}
|
||||
return true;
|
||||
});
|
||||
await PrefsManager.initialize();
|
||||
});
|
||||
|
||||
Future<MapController> openMap(WidgetTester tester) async {
|
||||
final settings = AppSettingsService();
|
||||
final connector = MeshCoreConnector();
|
||||
final paths = PathHistoryService(StorageService());
|
||||
final tiles = _MapWithoutTiles(settings);
|
||||
addTearDown(() {
|
||||
connector.dispose();
|
||||
paths.dispose();
|
||||
tiles.dispose();
|
||||
settings.dispose();
|
||||
});
|
||||
await tester.pumpWidget(
|
||||
MultiProvider(
|
||||
providers: [
|
||||
ChangeNotifierProvider.value(value: connector),
|
||||
ChangeNotifierProvider.value(value: settings),
|
||||
ChangeNotifierProvider.value(value: paths),
|
||||
ChangeNotifierProvider.value(value: UiViewStateService()),
|
||||
ChangeNotifierProvider<MapTileCacheService>.value(value: tiles),
|
||||
],
|
||||
child: MaterialApp(
|
||||
theme: MeshTheme.light(),
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
home: const MapScreen(),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pump();
|
||||
return tester.widget<FlutterMap>(find.byType(FlutterMap)).mapController!;
|
||||
}
|
||||
|
||||
testWidgets('camera movements persist once after interaction settles', (
|
||||
tester,
|
||||
) async {
|
||||
final controller = await openMap(tester);
|
||||
controller.move(const LatLng(35, -112), 9);
|
||||
await tester.pump(const Duration(milliseconds: 300));
|
||||
controller.move(const LatLng(36, -113), 10);
|
||||
await tester.pump(const Duration(milliseconds: 300));
|
||||
expect(cameraWrites, isEmpty);
|
||||
await tester.pump(const Duration(milliseconds: 201));
|
||||
expect(cameraWrites, [
|
||||
['36.0', '-113.0', '10.0'],
|
||||
]);
|
||||
|
||||
// Duplicate end events and disposal must not rewrite an unchanged camera.
|
||||
final map = tester.widget<FlutterMap>(find.byType(FlutterMap));
|
||||
map.options.onMapEvent!(
|
||||
MapEventMoveEnd(
|
||||
source: MapEventSource.mapController,
|
||||
camera: controller.camera,
|
||||
),
|
||||
);
|
||||
await tester.pump(const Duration(milliseconds: 600));
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
await tester.pump();
|
||||
expect(cameraWrites, hasLength(1));
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'leaving the map flushes the latest camera and cancels its timer',
|
||||
(tester) async {
|
||||
final controller = await openMap(tester);
|
||||
controller.move(const LatLng(37, -114), 11);
|
||||
await tester.pump(const Duration(milliseconds: 100));
|
||||
expect(cameraWrites, isEmpty);
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
await tester.pump();
|
||||
expect(cameraWrites, [
|
||||
['37.0', '-114.0', '11.0'],
|
||||
]);
|
||||
await tester.pump(const Duration(seconds: 1));
|
||||
expect(cameraWrites, hasLength(1));
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets('backgrounding the app flushes without waiting for debounce', (
|
||||
tester,
|
||||
) async {
|
||||
final controller = await openMap(tester);
|
||||
controller.move(const LatLng(38, -115), 12);
|
||||
await tester.pump(const Duration(milliseconds: 100));
|
||||
tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive);
|
||||
await tester.pump();
|
||||
expect(cameraWrites, [
|
||||
['38.0', '-115.0', '12.0'],
|
||||
]);
|
||||
tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
await tester.pump();
|
||||
expect(cameraWrites, hasLength(1));
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
|
||||
import 'package:flutter_map/flutter_map.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:latlong2/latlong.dart';
|
||||
import 'package:meshcore_open/connector/meshcore_connector.dart';
|
||||
import 'package:meshcore_open/connector/meshcore_protocol.dart';
|
||||
import 'package:meshcore_open/l10n/app_localizations.dart';
|
||||
import 'package:meshcore_open/models/contact.dart';
|
||||
import 'package:meshcore_open/screens/map_screen.dart';
|
||||
import 'package:meshcore_open/services/app_settings_service.dart';
|
||||
import 'package:meshcore_open/services/map_tile_cache_service.dart';
|
||||
import 'package:meshcore_open/services/path_history_service.dart';
|
||||
import 'package:meshcore_open/services/storage_service.dart';
|
||||
import 'package:meshcore_open/services/ui_view_state_service.dart';
|
||||
import 'package:meshcore_open/storage/prefs_manager.dart';
|
||||
import 'package:meshcore_open/theme/mesh_theme.dart';
|
||||
import 'package:meshcore_open/widgets/quick_switch_bar.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
class _Connector extends MeshCoreConnector {
|
||||
List<Contact> nodes = [];
|
||||
int contactUnread = 0;
|
||||
int channelUnread = 0;
|
||||
|
||||
@override
|
||||
List<Contact> get allContacts => List.unmodifiable(nodes);
|
||||
|
||||
@override
|
||||
List<Contact> get contacts => List.unmodifiable(nodes);
|
||||
|
||||
@override
|
||||
int getTotalContactsUnreadCount() => contactUnread;
|
||||
|
||||
@override
|
||||
int getTotalChannelsUnreadCount() => channelUnread;
|
||||
}
|
||||
|
||||
class _UnusedCacheManager implements BaseCacheManager {
|
||||
@override
|
||||
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
|
||||
}
|
||||
|
||||
class _CountingTiles extends MapTileCacheService {
|
||||
_CountingTiles(AppSettingsService settings)
|
||||
: super(appSettingsService: settings, cacheManager: _UnusedCacheManager());
|
||||
|
||||
int builds = 0;
|
||||
|
||||
@override
|
||||
Widget buildTileLayer(BuildContext context, {double opacity = 1}) {
|
||||
builds++;
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
}
|
||||
|
||||
Contact _node({double latitude = 35, DateTime? lastSeen}) => Contact(
|
||||
publicKey: Uint8List.fromList(List.filled(32, 1)),
|
||||
name: 'Repeater',
|
||||
type: advTypeRepeater,
|
||||
pathLength: 0,
|
||||
path: Uint8List(0),
|
||||
latitude: latitude,
|
||||
longitude: -112,
|
||||
lastSeen: lastSeen ?? DateTime.now(),
|
||||
);
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
late _Connector connector;
|
||||
late AppSettingsService settings;
|
||||
late _CountingTiles tiles;
|
||||
late PathHistoryService paths;
|
||||
late UiViewStateService viewState;
|
||||
|
||||
setUp(() async {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
PrefsManager.reset();
|
||||
await PrefsManager.initialize();
|
||||
connector = _Connector();
|
||||
settings = AppSettingsService();
|
||||
tiles = _CountingTiles(settings);
|
||||
paths = PathHistoryService(StorageService());
|
||||
viewState = UiViewStateService();
|
||||
});
|
||||
|
||||
tearDown(() {
|
||||
connector.dispose();
|
||||
settings.dispose();
|
||||
tiles.dispose();
|
||||
paths.dispose();
|
||||
viewState.dispose();
|
||||
});
|
||||
|
||||
Future<void> openMap(WidgetTester tester) async {
|
||||
await tester.pumpWidget(
|
||||
MultiProvider(
|
||||
providers: [
|
||||
ChangeNotifierProvider<MeshCoreConnector>.value(value: connector),
|
||||
ChangeNotifierProvider.value(value: settings),
|
||||
ChangeNotifierProvider.value(value: paths),
|
||||
ChangeNotifierProvider.value(value: viewState),
|
||||
ChangeNotifierProvider<MapTileCacheService>.value(value: tiles),
|
||||
],
|
||||
child: MaterialApp(
|
||||
theme: MeshTheme.light(),
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
home: const MapScreen(),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pump();
|
||||
await tester.pump(const Duration(milliseconds: 60));
|
||||
await tester.pump();
|
||||
}
|
||||
|
||||
Iterable<LatLng> markerPoints(WidgetTester tester) => tester
|
||||
.widgetList<MarkerLayer>(find.byType(MarkerLayer))
|
||||
.expand((layer) => layer.markers)
|
||||
.map((marker) => marker.point);
|
||||
|
||||
testWidgets('unread badges update without rebuilding the map', (
|
||||
tester,
|
||||
) async {
|
||||
connector.nodes = [_node()];
|
||||
await openMap(tester);
|
||||
final originalBuilds = tiles.builds;
|
||||
|
||||
connector.contactUnread = 3;
|
||||
connector.channelUnread = 5;
|
||||
connector.notifyListeners();
|
||||
await tester.pump(const Duration(milliseconds: 60));
|
||||
await tester.pump();
|
||||
|
||||
final navigation = tester.widget<QuickSwitchBar>(
|
||||
find.byType(QuickSwitchBar),
|
||||
);
|
||||
expect(navigation.contactsUnreadCount, 3);
|
||||
expect(navigation.channelsUnreadCount, 5);
|
||||
expect(tiles.builds, originalBuilds);
|
||||
|
||||
connector.notifyListeners();
|
||||
await tester.pump(const Duration(milliseconds: 60));
|
||||
await tester.pump();
|
||||
expect(tiles.builds, originalBuilds);
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
});
|
||||
|
||||
testWidgets('contact movement invalidates cached markers', (tester) async {
|
||||
connector.nodes = [_node()];
|
||||
await openMap(tester);
|
||||
expect(markerPoints(tester), contains(const LatLng(35, -112)));
|
||||
final originalBuilds = tiles.builds;
|
||||
|
||||
connector.nodes = [connector.nodes.single.copyWith(latitude: 36)];
|
||||
connector.notifyListeners();
|
||||
await tester.pump(const Duration(milliseconds: 60));
|
||||
await tester.pump();
|
||||
|
||||
expect(tiles.builds, greaterThan(originalBuilds));
|
||||
expect(markerPoints(tester), contains(const LatLng(36, -112)));
|
||||
expect(markerPoints(tester), isNot(contains(const LatLng(35, -112))));
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
});
|
||||
|
||||
testWidgets('time filters invalidate the visible marker cache', (
|
||||
tester,
|
||||
) async {
|
||||
connector.nodes = [
|
||||
_node(lastSeen: DateTime.now().subtract(const Duration(hours: 3))),
|
||||
];
|
||||
await openMap(tester);
|
||||
expect(markerPoints(tester), contains(const LatLng(35, -112)));
|
||||
|
||||
await settings.setMapTimeFilterHours(1);
|
||||
await tester.pump();
|
||||
expect(markerPoints(tester), isNot(contains(const LatLng(35, -112))));
|
||||
|
||||
await settings.setMapTimeFilterHours(0);
|
||||
await tester.pump();
|
||||
expect(markerPoints(tester), contains(const LatLng(35, -112)));
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,347 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_localizations/flutter_localizations.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import 'package:meshcore_open/connector/meshcore_connector.dart';
|
||||
import 'package:meshcore_open/connector/meshcore_protocol.dart';
|
||||
import 'package:meshcore_open/l10n/app_localizations.dart';
|
||||
import 'package:meshcore_open/models/channel.dart';
|
||||
import 'package:meshcore_open/models/channel_message.dart';
|
||||
import 'package:meshcore_open/models/contact.dart';
|
||||
import 'package:meshcore_open/models/message.dart';
|
||||
import 'package:meshcore_open/review_mode/review_radio.dart';
|
||||
import 'package:meshcore_open/screens/channel_chat_screen.dart';
|
||||
import 'package:meshcore_open/screens/channels_screen.dart';
|
||||
import 'package:meshcore_open/screens/chat_screen.dart';
|
||||
import 'package:meshcore_open/screens/contacts_screen.dart';
|
||||
import 'package:meshcore_open/services/app_debug_log_service.dart';
|
||||
import 'package:meshcore_open/services/app_settings_service.dart';
|
||||
import 'package:meshcore_open/services/ble_debug_log_service.dart';
|
||||
import 'package:meshcore_open/services/chat_text_scale_service.dart';
|
||||
import 'package:meshcore_open/services/image_codec_service.dart';
|
||||
import 'package:meshcore_open/services/map_tile_cache_service.dart';
|
||||
import 'package:meshcore_open/services/message_retry_service.dart';
|
||||
import 'package:meshcore_open/services/network_map/network_map_upload_service.dart';
|
||||
import 'package:meshcore_open/services/path_history_service.dart';
|
||||
import 'package:meshcore_open/services/received_image_store.dart';
|
||||
import 'package:meshcore_open/services/storage_service.dart';
|
||||
import 'package:meshcore_open/services/timeout_prediction_service.dart';
|
||||
import 'package:meshcore_open/services/translation_service.dart';
|
||||
import 'package:meshcore_open/services/ui_view_state_service.dart';
|
||||
import 'package:meshcore_open/storage/channel_message_store.dart';
|
||||
import 'package:meshcore_open/storage/channel_store.dart';
|
||||
import 'package:meshcore_open/storage/contact_store.dart';
|
||||
import 'package:meshcore_open/storage/last_radio_store.dart';
|
||||
import 'package:meshcore_open/storage/message_store.dart';
|
||||
import 'package:meshcore_open/storage/prefs_manager.dart';
|
||||
import 'package:meshcore_open/theme/mesh_theme.dart';
|
||||
import 'package:meshcore_open/widgets/chat_composer.dart';
|
||||
import 'package:meshcore_open/widgets/connect_sheet.dart';
|
||||
|
||||
final _radioKey = Uint8List.fromList(List<int>.generate(32, (i) => 0xA0 + i));
|
||||
final _radioHex = pubKeyToHex(_radioKey);
|
||||
final _aliceKey = Uint8List.fromList(List<int>.generate(32, (i) => 0x10 + i));
|
||||
final _psk = Uint8List.fromList(List<int>.generate(16, (i) => 0x40 + i));
|
||||
|
||||
final _l10n = lookupAppLocalizations(const Locale('en'));
|
||||
|
||||
Future<void> _seedRadio() async {
|
||||
final alice = Contact(
|
||||
publicKey: _aliceKey,
|
||||
name: 'Alice',
|
||||
type: advTypeChat,
|
||||
pathLength: 1,
|
||||
path: Uint8List.fromList([0x22]),
|
||||
lastSeen: DateTime.fromMillisecondsSinceEpoch(1700000000000),
|
||||
);
|
||||
await (ContactStore()..setPublicKeyHex = _radioHex).saveContacts([alice]);
|
||||
final channel = Channel(index: 0, name: 'Base Camp', psk: _psk);
|
||||
final channelStore = ChannelStore()..setPublicKeyHex = _radioHex;
|
||||
await channelStore.saveChannels([channel]);
|
||||
await channelStore.saveSlotChannelIds({0: channel.storageId!});
|
||||
await (ChannelMessageStore()..setPublicKeyHex = _radioHex)
|
||||
.saveChannelMessages(channel.storageId!, [
|
||||
ChannelMessage(
|
||||
senderName: 'Bob',
|
||||
text: 'camp is up',
|
||||
timestamp: DateTime.fromMillisecondsSinceEpoch(1700000001000),
|
||||
isOutgoing: false,
|
||||
status: ChannelMessageStatus.sent,
|
||||
channelIndex: 0,
|
||||
),
|
||||
]);
|
||||
await (MessageStore()..setPublicKeyHex = _radioHex)
|
||||
.saveMessages(alice.publicKeyHex, [
|
||||
Message(
|
||||
senderKey: _aliceKey,
|
||||
text: 'hi there',
|
||||
timestamp: DateTime.fromMillisecondsSinceEpoch(1700000002000),
|
||||
isOutgoing: false,
|
||||
status: MessageStatus.delivered,
|
||||
),
|
||||
]);
|
||||
await LastRadioStore().save(
|
||||
LastRadio(
|
||||
publicKeyHex: _radioHex,
|
||||
name: 'Base',
|
||||
transport: LastRadio.transportBle,
|
||||
bleRemoteId: 'AA:BB:CC:DD:EE:FF',
|
||||
savedAt: DateTime.fromMillisecondsSinceEpoch(1700000000000),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<Widget> _app(
|
||||
WidgetTester tester,
|
||||
MeshCoreConnector connector,
|
||||
Widget home,
|
||||
) async {
|
||||
final storage = StorageService();
|
||||
final settings = AppSettingsService();
|
||||
await tester.runAsync(settings.loadSettings);
|
||||
final translation = TranslationService(settings);
|
||||
return MultiProvider(
|
||||
providers: [
|
||||
ChangeNotifierProvider.value(value: connector),
|
||||
ChangeNotifierProvider.value(value: MessageRetryService()),
|
||||
ChangeNotifierProvider.value(value: PathHistoryService(storage)),
|
||||
ChangeNotifierProvider.value(value: settings),
|
||||
ChangeNotifierProvider.value(value: BleDebugLogService()),
|
||||
ChangeNotifierProvider.value(value: AppDebugLogService()),
|
||||
ChangeNotifierProvider.value(value: ChatTextScaleService()),
|
||||
ChangeNotifierProvider.value(value: translation),
|
||||
ChangeNotifierProvider.value(value: UiViewStateService()),
|
||||
Provider.value(value: storage),
|
||||
ChangeNotifierProvider.value(
|
||||
value: MapTileCacheService(appSettingsService: settings),
|
||||
),
|
||||
ChangeNotifierProvider.value(value: TimeoutPredictionService(storage)),
|
||||
ChangeNotifierProvider.value(value: ImageCodecService(settings)),
|
||||
ChangeNotifierProvider.value(value: ReceivedImageStore()),
|
||||
ChangeNotifierProvider.value(
|
||||
value: NetworkMapUploadService(
|
||||
connector: connector,
|
||||
settings: settings,
|
||||
),
|
||||
),
|
||||
],
|
||||
child: MaterialApp(
|
||||
theme: MeshTheme.light(),
|
||||
locale: const Locale('en'),
|
||||
localizationsDelegates: const [
|
||||
AppLocalizations.delegate,
|
||||
GlobalMaterialLocalizations.delegate,
|
||||
GlobalWidgetsLocalizations.delegate,
|
||||
GlobalCupertinoLocalizations.delegate,
|
||||
],
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
home: home,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _settle(WidgetTester tester) async {
|
||||
for (var i = 0; i < 10; i++) {
|
||||
await tester.pump(const Duration(milliseconds: 100));
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _waitFor(
|
||||
WidgetTester tester,
|
||||
bool Function() condition, {
|
||||
int seconds = 8,
|
||||
}) async {
|
||||
await tester.runAsync(() async {
|
||||
final end = DateTime.now().add(Duration(seconds: seconds));
|
||||
while (!condition()) {
|
||||
if (DateTime.now().isAfter(end)) fail('Timed out waiting for condition');
|
||||
await Future<void>.delayed(const Duration(milliseconds: 25));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Restores the seeded radio into a connector that never connects.
|
||||
Future<MeshCoreConnector> _offlineConnector(WidgetTester tester) async {
|
||||
final connector = MeshCoreConnector();
|
||||
addTearDown(connector.dispose);
|
||||
await tester.runAsync(connector.restoreLastRadio);
|
||||
expect(connector.isConnected, isFalse);
|
||||
expect(connector.channels, isNotEmpty);
|
||||
return connector;
|
||||
}
|
||||
|
||||
PopupMenuItem<Object?> _menuItem(String label) =>
|
||||
find
|
||||
.ancestor(
|
||||
of: find.text(label),
|
||||
matching: find.byWidgetPredicate((w) => w is PopupMenuItem),
|
||||
)
|
||||
.evaluate()
|
||||
.single
|
||||
.widget
|
||||
as PopupMenuItem<Object?>;
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
final tempDir = Directory.systemTemp.createTempSync('offline_mode_test');
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(
|
||||
const MethodChannel('plugins.flutter.io/path_provider'),
|
||||
(call) async => tempDir.path,
|
||||
);
|
||||
|
||||
setUp(() async {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
PrefsManager.reset();
|
||||
await PrefsManager.initialize();
|
||||
ChannelMessageStore().forgetArchive();
|
||||
MessageStore().forgetArchive();
|
||||
await _seedRadio();
|
||||
ChannelMessageStore().forgetArchive();
|
||||
MessageStore().forgetArchive();
|
||||
});
|
||||
|
||||
testWidgets('Channels screen stays put offline with saved data and a '
|
||||
'Connect control', (tester) async {
|
||||
final connector = await _offlineConnector(tester);
|
||||
await tester.pumpWidget(
|
||||
await _app(tester, connector, const ChannelsScreen()),
|
||||
);
|
||||
await _settle(tester);
|
||||
|
||||
expect(find.byType(ChannelsScreen), findsOneWidget);
|
||||
expect(find.text('Base Camp'), findsOneWidget);
|
||||
expect(find.byType(ConnectButton), findsOneWidget);
|
||||
expect(find.text(_l10n.appBar_offlineSubtitle('Base')), findsOneWidget);
|
||||
// Adding a channel needs the radio.
|
||||
expect(find.byType(FloatingActionButton), findsNothing);
|
||||
|
||||
await tester.tap(find.byIcon(Icons.more_vert));
|
||||
await _settle(tester);
|
||||
expect(find.text(_l10n.common_connect), findsWidgets);
|
||||
expect(find.text(_l10n.common_disconnect), findsNothing);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
});
|
||||
|
||||
testWidgets('Contacts screen stays put offline and disables radio actions', (
|
||||
tester,
|
||||
) async {
|
||||
final connector = await _offlineConnector(tester);
|
||||
await tester.pumpWidget(
|
||||
await _app(tester, connector, const ContactsScreen()),
|
||||
);
|
||||
await _settle(tester);
|
||||
|
||||
expect(find.byType(ContactsScreen), findsOneWidget);
|
||||
expect(find.text('Alice'), findsWidgets);
|
||||
expect(find.byType(ConnectButton), findsOneWidget);
|
||||
expect(find.byType(FloatingActionButton), findsNothing);
|
||||
|
||||
await tester.tap(find.byIcon(Icons.more_vert));
|
||||
await _settle(tester);
|
||||
expect(_menuItem(_l10n.contacts_floodAdvert).enabled, isFalse);
|
||||
expect(_menuItem(_l10n.contacts_zeroHopAdvert).enabled, isFalse);
|
||||
expect(_menuItem(_l10n.contacts_addContactFromClipboard).enabled, isFalse);
|
||||
expect(_menuItem(_l10n.common_connect).enabled, isTrue);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
});
|
||||
|
||||
testWidgets('Channel chat offline is read-only', (tester) async {
|
||||
final connector = await _offlineConnector(tester);
|
||||
await tester.pumpWidget(
|
||||
await _app(
|
||||
tester,
|
||||
connector,
|
||||
ChannelChatScreen(channel: connector.channels.single),
|
||||
),
|
||||
);
|
||||
await _settle(tester);
|
||||
|
||||
expect(find.textContaining('camp is up'), findsWidgets);
|
||||
expect(find.byType(OfflineComposerBar), findsOneWidget);
|
||||
expect(find.text(_l10n.chat_composerOffline), findsOneWidget);
|
||||
expect(find.byType(TextField), findsNothing);
|
||||
expect(find.byType(ConnectButton), findsOneWidget);
|
||||
|
||||
await tester.tap(find.byIcon(Icons.more_vert));
|
||||
await _settle(tester);
|
||||
expect(_menuItem(_l10n.channels_editChannel).enabled, isFalse);
|
||||
expect(_menuItem(_l10n.contact_clearChat).enabled, isFalse);
|
||||
expect(_menuItem(_l10n.channels_deleteChannel).enabled, isFalse);
|
||||
// Per-device preferences stay available.
|
||||
expect(_menuItem(_l10n.chatBackground_title).enabled, isTrue);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
});
|
||||
|
||||
testWidgets('DM chat offline is read-only', (tester) async {
|
||||
final connector = await _offlineConnector(tester);
|
||||
final alice = connector.contacts.single;
|
||||
await tester.pumpWidget(
|
||||
await _app(tester, connector, ChatScreen(contact: alice)),
|
||||
);
|
||||
await _settle(tester);
|
||||
|
||||
expect(find.textContaining('hi there'), findsWidgets);
|
||||
expect(find.byType(OfflineComposerBar), findsOneWidget);
|
||||
expect(find.byType(TextField), findsNothing);
|
||||
|
||||
await tester.tap(find.byIcon(Icons.more_vert));
|
||||
await _settle(tester);
|
||||
expect(_menuItem(_l10n.contact_clearChat).enabled, isFalse);
|
||||
expect(_menuItem(_l10n.contact_telemetry).enabled, isFalse);
|
||||
expect(_menuItem(_l10n.contact_info).enabled, isTrue);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
});
|
||||
|
||||
testWidgets('a draft typed while connected survives a disconnect and '
|
||||
'reconnect', (tester) async {
|
||||
final connector = MeshCoreConnector();
|
||||
addTearDown(connector.dispose);
|
||||
connector.reviewRadioFactoryForTest = () => ReviewRadio(
|
||||
scheduledMessageInterval: const Duration(hours: 1),
|
||||
ackDelay: const Duration(hours: 1),
|
||||
replyDelay: const Duration(hours: 1),
|
||||
);
|
||||
await tester.runAsync(connector.connectReview);
|
||||
await _waitFor(tester, () => connector.contacts.isNotEmpty);
|
||||
final contact = connector.contacts.firstWhere((c) => c.type == advTypeChat);
|
||||
|
||||
await tester.pumpWidget(
|
||||
await _app(tester, connector, ChatScreen(contact: contact)),
|
||||
);
|
||||
await _settle(tester);
|
||||
await tester.enterText(find.byType(TextField), 'half written');
|
||||
await _settle(tester);
|
||||
|
||||
await tester.runAsync(connector.disconnect);
|
||||
// Connector notifications are debounced on a real timer.
|
||||
await _waitFor(tester, () => !connector.isConnected);
|
||||
await tester.runAsync(
|
||||
() => Future<void>.delayed(const Duration(milliseconds: 200)),
|
||||
);
|
||||
await _settle(tester);
|
||||
expect(find.byType(ChatScreen), findsOneWidget);
|
||||
expect(find.byType(OfflineComposerBar), findsOneWidget);
|
||||
expect(find.byType(TextField), findsNothing);
|
||||
|
||||
await tester.runAsync(connector.connectReview);
|
||||
await _waitFor(tester, () => connector.isConnected);
|
||||
await tester.runAsync(
|
||||
() => Future<void>.delayed(const Duration(milliseconds: 200)),
|
||||
);
|
||||
await _settle(tester);
|
||||
expect(find.byType(OfflineComposerBar), findsNothing);
|
||||
final field = tester.widget<TextField>(find.byType(TextField));
|
||||
expect(field.controller?.text, 'half written');
|
||||
|
||||
await tester.runAsync(connector.disconnect);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
await tester.pump(const Duration(minutes: 1));
|
||||
});
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
@@ -56,6 +57,7 @@ import 'package:meshcore_open/services/translation_service.dart';
|
||||
import 'package:meshcore_open/services/ui_view_state_service.dart';
|
||||
import 'package:meshcore_open/storage/prefs_manager.dart';
|
||||
import 'package:meshcore_open/theme/mesh_theme.dart';
|
||||
import 'package:meshcore_open/widgets/routing_sheet.dart';
|
||||
|
||||
/// Renders every screen on a small phone (320x568, the narrowest common
|
||||
/// width) at several text scales, plus a desktop window, and fails on any
|
||||
@@ -146,11 +148,21 @@ _interactions = {
|
||||
'Contacts add sheet': (t, _) async {
|
||||
await t.tap(find.byType(FloatingActionButton));
|
||||
},
|
||||
// Four routing modes (Auto, Flood, Direct, Manual) share one row.
|
||||
'Routing sheet': (t, c) async {
|
||||
unawaited(
|
||||
ContactRoutingSheet.show(
|
||||
t.element(find.byType(ChatScreen)),
|
||||
contact: _contactOfType(c, advTypeChat),
|
||||
),
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
final Map<String, _ScreenBuilder> _screens = {
|
||||
'Contacts options sheet': (_) => const ContactsScreen(),
|
||||
'Contacts add sheet': (_) => const ContactsScreen(),
|
||||
'Routing sheet': (c) => ChatScreen(contact: _contactOfType(c, advTypeChat)),
|
||||
'Scanner': (_) => const ScannerScreen(),
|
||||
'Tcp': (_) => const TcpScreen(),
|
||||
'Usb': (_) => const UsbScreen(),
|
||||
@@ -229,9 +241,20 @@ void main() {
|
||||
|
||||
final variants = [
|
||||
for (final entry in _screens.entries) (entry, false),
|
||||
// Repeater screens add a banner while the companion radio is offline.
|
||||
// Repeater screens add a banner while the companion radio is offline;
|
||||
// the main and chat screens swap in the Connect button and the
|
||||
// read-only composer bar.
|
||||
for (final entry in _screens.entries)
|
||||
if (entry.key.startsWith('Repeater') || entry.key == 'Neighbors')
|
||||
if (entry.key.startsWith('Repeater') ||
|
||||
const {
|
||||
'Neighbors',
|
||||
'Channels',
|
||||
'Contacts',
|
||||
'Map',
|
||||
'Chat',
|
||||
'ChannelChat',
|
||||
'Settings',
|
||||
}.contains(entry.key))
|
||||
(entry, true),
|
||||
];
|
||||
for (final (entry, offline) in variants) {
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import '../../scripts/reset_http_profile.dart';
|
||||
|
||||
void main() {
|
||||
test('stops recording before clearing and verifies the result', () async {
|
||||
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
|
||||
final calls = <Map<String, dynamic>>[];
|
||||
final paths = <String>[];
|
||||
var recording = true;
|
||||
var requests = <Object>[
|
||||
{'id': 'captured-request'},
|
||||
];
|
||||
final subscription = server.listen((request) async {
|
||||
paths.add(request.uri.path);
|
||||
final socket = await WebSocketTransformer.upgrade(request);
|
||||
socket.listen((data) {
|
||||
final call = jsonDecode(data as String) as Map<String, dynamic>;
|
||||
calls.add(call);
|
||||
final parameters = call['params'] as Map;
|
||||
Map<String, dynamic> result;
|
||||
switch (call['method']) {
|
||||
case 'getVM':
|
||||
result = {
|
||||
'isolates': [
|
||||
{'name': 'worker', 'id': 'worker'},
|
||||
{'name': 'main', 'id': 'main-isolate'},
|
||||
],
|
||||
};
|
||||
case 'ext.dart.io.httpEnableTimelineLogging':
|
||||
if (parameters['enabled'] == 'false') recording = false;
|
||||
result = {'enabled': recording};
|
||||
case 'ext.dart.io.clearHttpProfile':
|
||||
expect(recording, isFalse);
|
||||
requests = [];
|
||||
result = {'type': 'Success'};
|
||||
case 'ext.dart.io.getHttpProfile':
|
||||
result = {'requests': requests};
|
||||
default:
|
||||
fail('Unexpected service method ${call['method']}');
|
||||
}
|
||||
socket.add(jsonEncode({'id': call['id'], 'result': result}));
|
||||
});
|
||||
});
|
||||
addTearDown(() async {
|
||||
await subscription.cancel();
|
||||
await server.close(force: true);
|
||||
});
|
||||
|
||||
expect(
|
||||
await resetHttpProfile(
|
||||
Uri.parse('http://127.0.0.1:${server.port}/service-token=/'),
|
||||
),
|
||||
0,
|
||||
);
|
||||
expect(paths, ['/service-token=/ws']);
|
||||
expect(calls.map((call) => call['method']), [
|
||||
'getVM',
|
||||
'ext.dart.io.httpEnableTimelineLogging',
|
||||
'ext.dart.io.clearHttpProfile',
|
||||
'ext.dart.io.httpEnableTimelineLogging',
|
||||
'ext.dart.io.getHttpProfile',
|
||||
]);
|
||||
for (final call in calls.skip(1)) {
|
||||
expect((call['params'] as Map)['isolateId'], 'main-isolate');
|
||||
}
|
||||
});
|
||||
|
||||
test('rejects unsupported URIs before connecting', () async {
|
||||
await expectLater(
|
||||
resetHttpProfile(Uri.parse('file:///tmp/service')),
|
||||
throwsFormatException,
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,408 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/connector/meshcore_connector.dart';
|
||||
import 'package:meshcore_open/models/app_settings.dart';
|
||||
import 'package:meshcore_open/models/image_codec_support.dart';
|
||||
import 'package:meshcore_open/models/translation_support.dart';
|
||||
import 'package:meshcore_open/services/app_settings_service.dart';
|
||||
import 'package:meshcore_open/services/image_codec_file_store.dart';
|
||||
import 'package:meshcore_open/services/image_codec_service.dart';
|
||||
import 'package:meshcore_open/services/image_codec_settings_store.dart';
|
||||
import 'package:meshcore_open/services/translation_file_store.dart';
|
||||
import 'package:meshcore_open/services/translation_service.dart';
|
||||
import 'package:meshcore_open/services/backup_service.dart';
|
||||
import 'package:meshcore_open/storage/prefs_manager.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
class _EmptyTranslationFileStore extends TranslationFileStore {
|
||||
@override
|
||||
Future<List<TranslationModelRecord>> scanDownloadedModels() async => const [];
|
||||
}
|
||||
|
||||
class _EmptyImageCodecFileStore extends ImageCodecFileStore {
|
||||
@override
|
||||
Future<List<ImageCodecModelRecord>> scanDownloadedModels() async => const [];
|
||||
}
|
||||
|
||||
class _AppSettingsCodecStore implements ImageCodecSettingsStore {
|
||||
_AppSettingsCodecStore(this.service);
|
||||
|
||||
final AppSettingsService service;
|
||||
|
||||
@override
|
||||
ImageCodecPreferences get preferences => service.settings.imageCodec;
|
||||
|
||||
@override
|
||||
Future<void> load() async {}
|
||||
|
||||
@override
|
||||
Future<void> save(ImageCodecPreferences preferences) =>
|
||||
service.setImageCodecPreferences(preferences);
|
||||
}
|
||||
|
||||
void main() {
|
||||
const payload = <String, Object?>{
|
||||
'format': 'meshcore-open-backup',
|
||||
'version': 1,
|
||||
'sourcePublicKey': '0011223344',
|
||||
'items': ['privateKey'],
|
||||
'sections': {
|
||||
'nodeSettings': {'privateKey': 'private-key-data'},
|
||||
},
|
||||
};
|
||||
|
||||
group('BackupService creation', () {
|
||||
test(
|
||||
'expands stored JSON for readability and retains banner preferences',
|
||||
() async {
|
||||
SharedPreferences.setMockInitialValues({
|
||||
'app_settings': jsonEncode({
|
||||
'theme_mode': 'dark',
|
||||
'map_use_online_map_for_paths': true,
|
||||
'upload_ipfs_api_key': 'ipfs-secret',
|
||||
'map_tile_api_key': 'stadia-secret',
|
||||
'custom_themes': [
|
||||
{'name': 'Example'},
|
||||
],
|
||||
'path_history_sample': {
|
||||
'path_bytes': [1, 16, 255],
|
||||
},
|
||||
}),
|
||||
'node_banner_txt': 'banner text',
|
||||
'node_banner_expires_ms': 123,
|
||||
});
|
||||
PrefsManager.reset();
|
||||
await PrefsManager.initialize();
|
||||
addTearDown(PrefsManager.reset);
|
||||
final connector = MeshCoreConnector();
|
||||
addTearDown(connector.dispose);
|
||||
|
||||
final json = await const BackupService().createBackup(
|
||||
items: {BackupItem.appSettings},
|
||||
connector: connector,
|
||||
settings: AppSettings(),
|
||||
password: '',
|
||||
);
|
||||
final payload = jsonDecode(json) as Map<String, dynamic>;
|
||||
expect(payload['items'], [BackupItem.appSettings.name]);
|
||||
final preferences =
|
||||
(payload['sections'] as Map<String, dynamic>)['appSettings']
|
||||
as Map<String, dynamic>;
|
||||
final values = preferences['preferences'] as Map<String, dynamic>;
|
||||
expect(values['app_settings'], isA<Map<String, dynamic>>());
|
||||
final appSettings = values['app_settings'] as Map<String, dynamic>;
|
||||
expect(appSettings, isNot(contains('upload_ipfs_api_key')));
|
||||
expect(appSettings, isNot(contains('map_tile_api_key')));
|
||||
expect(appSettings['map_use_online_map_for_paths'], isTrue);
|
||||
expect(values['node_banner_txt'], 'banner text');
|
||||
expect(values['node_banner_expires_ms'], 123);
|
||||
expect(json, contains('"theme_mode": "dark"'));
|
||||
expect(json, contains('"path_bytes": [1, 16, 255]'));
|
||||
expect(json, isNot(contains('ipfs-secret')));
|
||||
expect(json, isNot(contains('stadia-secret')));
|
||||
final inspected = await const BackupService().inspectImport(
|
||||
contents: json,
|
||||
password: '',
|
||||
);
|
||||
expect(inspected.availableItems, contains(BackupItem.appSettings));
|
||||
expect(inspected.availableItems, isNot(contains(BackupItem.ipfsKey)));
|
||||
expect(
|
||||
inspected.availableItems,
|
||||
isNot(contains(BackupItem.stadiaMapKey)),
|
||||
);
|
||||
final settingsService = AppSettingsService();
|
||||
addTearDown(settingsService.dispose);
|
||||
await const BackupService().restoreBackup(
|
||||
contents: json,
|
||||
password: '',
|
||||
items: {BackupItem.appSettings},
|
||||
connector: connector,
|
||||
appSettingsService: settingsService,
|
||||
);
|
||||
final restored =
|
||||
jsonDecode(PrefsManager.instance.getString('app_settings')!)
|
||||
as Map<String, dynamic>;
|
||||
expect(
|
||||
(restored['path_history_sample']
|
||||
as Map<String, dynamic>)['path_bytes'],
|
||||
[1, 16, 255],
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test('backs up a sensitive key without unrelated app settings', () async {
|
||||
SharedPreferences.setMockInitialValues({
|
||||
'app_settings': jsonEncode({
|
||||
'theme_mode': 'dark',
|
||||
'upload_ipfs_api_key': 'ipfs-secret',
|
||||
'map_tile_api_key': 'stadia-secret',
|
||||
}),
|
||||
});
|
||||
PrefsManager.reset();
|
||||
await PrefsManager.initialize();
|
||||
addTearDown(PrefsManager.reset);
|
||||
final connector = MeshCoreConnector();
|
||||
addTearDown(connector.dispose);
|
||||
|
||||
final json = await const BackupService().createBackup(
|
||||
items: {BackupItem.ipfsKey},
|
||||
connector: connector,
|
||||
settings: AppSettings(),
|
||||
password: '',
|
||||
);
|
||||
final payload = jsonDecode(json) as Map<String, dynamic>;
|
||||
expect(payload['items'], [BackupItem.ipfsKey.name]);
|
||||
final section =
|
||||
(payload['sections'] as Map<String, dynamic>)['appSettings']
|
||||
as Map<String, dynamic>;
|
||||
final preferences = section['preferences'] as Map<String, dynamic>;
|
||||
expect(preferences.keys, {'app_settings'});
|
||||
expect(preferences['app_settings'], {
|
||||
'upload_ipfs_api_key': 'ipfs-secret',
|
||||
});
|
||||
expect(json, isNot(contains('stadia-secret')));
|
||||
});
|
||||
|
||||
test(
|
||||
'restores a selected key without replacing other app preferences',
|
||||
() async {
|
||||
SharedPreferences.setMockInitialValues({
|
||||
'app_settings': jsonEncode({
|
||||
'theme_mode': 'light',
|
||||
'upload_ipfs_api_key': 'old-ipfs',
|
||||
'map_tile_api_key': 'existing-stadia',
|
||||
}),
|
||||
});
|
||||
PrefsManager.reset();
|
||||
await PrefsManager.initialize();
|
||||
addTearDown(PrefsManager.reset);
|
||||
final connector = MeshCoreConnector();
|
||||
final settingsService = AppSettingsService();
|
||||
addTearDown(connector.dispose);
|
||||
addTearDown(settingsService.dispose);
|
||||
|
||||
final backup = await BackupService.encodeBackup({
|
||||
'format': 'meshcore-open-backup',
|
||||
'version': 1,
|
||||
'sourcePublicKey': '',
|
||||
'items': [BackupItem.ipfsKey.name],
|
||||
'sections': {
|
||||
'appSettings': {
|
||||
'preferences': {
|
||||
'app_settings': {'upload_ipfs_api_key': 'new-ipfs'},
|
||||
},
|
||||
},
|
||||
},
|
||||
}, password: '');
|
||||
await const BackupService().restoreBackup(
|
||||
contents: backup,
|
||||
password: '',
|
||||
items: {BackupItem.ipfsKey},
|
||||
connector: connector,
|
||||
appSettingsService: settingsService,
|
||||
);
|
||||
|
||||
final restored =
|
||||
jsonDecode(PrefsManager.instance.getString('app_settings')!)
|
||||
as Map<String, dynamic>;
|
||||
expect(restored['theme_mode'], 'light');
|
||||
expect(restored['upload_ipfs_api_key'], 'new-ipfs');
|
||||
expect(restored['map_tile_api_key'], 'existing-stadia');
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
group('restored model registry reconciliation', () {
|
||||
test(
|
||||
'removes model records absent from disk but retains selections',
|
||||
() async {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
PrefsManager.reset();
|
||||
await PrefsManager.initialize();
|
||||
addTearDown(PrefsManager.reset);
|
||||
final settingsService = AppSettingsService();
|
||||
addTearDown(settingsService.dispose);
|
||||
final downloadedAt = DateTime(2026);
|
||||
await settingsService.updateSettings(
|
||||
AppSettings(
|
||||
mapUseOnlineMapForPaths: true,
|
||||
translationSelectedModelId: 'translation-model',
|
||||
translationDownloadedModels: [
|
||||
TranslationModelRecord(
|
||||
id: 'translation-model',
|
||||
name: 'translation.gguf',
|
||||
sourceUrl: 'https://example.com/translation.gguf',
|
||||
localPath: '/old-device/translation.gguf',
|
||||
downloadedAt: downloadedAt,
|
||||
fileSizeBytes: 100,
|
||||
),
|
||||
],
|
||||
imageCodecSelectedModelId: 'image-model',
|
||||
imageCodecDownloadedModels: [
|
||||
ImageCodecModelRecord(
|
||||
id: 'image-model',
|
||||
name: 'image.onnx',
|
||||
sourceUrl: 'https://example.com/image.onnx',
|
||||
localPath: '/old-device/image.onnx',
|
||||
downloadedAt: downloadedAt,
|
||||
fileSizeBytes: 100,
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
final translationService = TranslationService(
|
||||
settingsService,
|
||||
fileStore: _EmptyTranslationFileStore(),
|
||||
);
|
||||
final imageCodecService = ImageCodecService(
|
||||
settingsService,
|
||||
fileStore: _EmptyImageCodecFileStore(),
|
||||
settingsStore: _AppSettingsCodecStore(settingsService),
|
||||
);
|
||||
addTearDown(translationService.dispose);
|
||||
addTearDown(imageCodecService.dispose);
|
||||
|
||||
await translationService.refreshDownloadedModels(clearMissing: true);
|
||||
await imageCodecService.refreshDownloadedModels(clearMissing: true);
|
||||
|
||||
expect(settingsService.settings.translationDownloadedModels, isEmpty);
|
||||
expect(settingsService.settings.mapUseOnlineMapForPaths, isTrue);
|
||||
expect(
|
||||
settingsService.settings.translationSelectedModelId,
|
||||
'translation-model',
|
||||
);
|
||||
expect(settingsService.settings.imageCodecDownloadedModels, isEmpty);
|
||||
expect(
|
||||
settingsService.settings.imageCodecSelectedModelId,
|
||||
'image-model',
|
||||
);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
group('BackupService import inspection', () {
|
||||
test(
|
||||
'identifies only the fields present in an official app backup',
|
||||
() async {
|
||||
final publicKey = List.filled(32, 'a1').join();
|
||||
final contactKey = List.filled(32, 'b2').join();
|
||||
final privateKey = List.filled(64, 'c3').join();
|
||||
final json = jsonEncode({
|
||||
'name': 'Test node',
|
||||
'public_key': publicKey,
|
||||
'private_key': privateKey,
|
||||
'radio_settings': {
|
||||
'frequency': 869618,
|
||||
'bandwidth': 62500,
|
||||
'spreading_factor': 8,
|
||||
'coding_rate': 8,
|
||||
'tx_power': 22,
|
||||
},
|
||||
'position_settings': {'latitude': '47.5', 'longitude': '7.8'},
|
||||
'other_settings': {'advert_location_policy': 0},
|
||||
'auto_add_settings': {'auto_add_chat': true},
|
||||
'channels': [
|
||||
{'name': 'Public', 'secret': List.filled(16, '01').join()},
|
||||
],
|
||||
'contacts': [
|
||||
{
|
||||
'type': 1,
|
||||
'name': 'Contact',
|
||||
'custom_name': null,
|
||||
'public_key': contactKey,
|
||||
'flags': 0,
|
||||
'latitude': '0.0',
|
||||
'longitude': '0.0',
|
||||
'last_advert': 1,
|
||||
'last_modified': 1,
|
||||
'out_path_list': null,
|
||||
},
|
||||
],
|
||||
}).replaceFirst('"name":"Test node",', '"name":"Test node"');
|
||||
|
||||
final inspected = await const BackupService().inspectImport(
|
||||
contents: json,
|
||||
password: '',
|
||||
);
|
||||
expect(inspected.isOfficial, isTrue);
|
||||
expect(
|
||||
inspected.availableItems,
|
||||
containsAll({
|
||||
BackupItem.deviceName,
|
||||
BackupItem.privateKey,
|
||||
BackupItem.publicKey,
|
||||
BackupItem.radioSettings,
|
||||
BackupItem.location,
|
||||
BackupItem.contactSettings,
|
||||
BackupItem.privacySettings,
|
||||
BackupItem.channels,
|
||||
BackupItem.contacts,
|
||||
}),
|
||||
);
|
||||
for (final item in [
|
||||
BackupItem.regions,
|
||||
BackupItem.appSettings,
|
||||
BackupItem.perContactSettings,
|
||||
BackupItem.contactGroups,
|
||||
BackupItem.contactHistory,
|
||||
BackupItem.discoveredContacts,
|
||||
BackupItem.channelFilters,
|
||||
BackupItem.channelSettings,
|
||||
BackupItem.communities,
|
||||
BackupItem.channelHistory,
|
||||
]) {
|
||||
expect(inspected.availableItems, isNot(contains(item)));
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test('reports only selected sections in a MeshCore Open backup', () async {
|
||||
final json = await BackupService.encodeBackup({
|
||||
...payload,
|
||||
'items': [BackupItem.deviceName.name, BackupItem.channels.name],
|
||||
}, password: '');
|
||||
final inspected = await const BackupService().inspectImport(
|
||||
contents: json,
|
||||
password: '',
|
||||
);
|
||||
expect(inspected.isOfficial, isFalse);
|
||||
expect(inspected.availableItems, {
|
||||
BackupItem.deviceName,
|
||||
BackupItem.channels,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
group('BackupService file encoding', () {
|
||||
test('writes readable JSON when the password is empty', () async {
|
||||
final file = await BackupService.encodeBackup(payload, password: '');
|
||||
expect(jsonDecode(file), payload);
|
||||
expect(await BackupService.decodeBackup(file, password: ''), payload);
|
||||
});
|
||||
|
||||
test('encrypts and restores payload when a password is provided', () async {
|
||||
final file = await BackupService.encodeBackup(
|
||||
payload,
|
||||
password: 'correct horse battery staple',
|
||||
);
|
||||
expect(file, contains('meshcore-open-encrypted-backup'));
|
||||
expect(file, isNot(contains('private-key-data')));
|
||||
expect(
|
||||
await BackupService.decodeBackup(
|
||||
file,
|
||||
password: 'correct horse battery staple',
|
||||
),
|
||||
payload,
|
||||
);
|
||||
});
|
||||
|
||||
test('rejects a wrong password', () async {
|
||||
final file = await BackupService.encodeBackup(payload, password: 'right');
|
||||
await expectLater(
|
||||
BackupService.decodeBackup(file, password: 'wrong'),
|
||||
throwsFormatException,
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/services/map_tile_cache_repository_io.dart';
|
||||
import 'package:meshcore_open/services/map_tile_cache_repository_stub.dart'
|
||||
as web;
|
||||
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
|
||||
|
||||
void main() {
|
||||
late Directory directory;
|
||||
late SqliteMapTileCacheRepository repository;
|
||||
final factory = databaseFactoryFfiNoIsolate;
|
||||
|
||||
SqliteMapTileCacheRepository createRepository() =>
|
||||
SqliteMapTileCacheRepository(
|
||||
databaseName: 'map_tile_cache',
|
||||
directory: () async => directory,
|
||||
factory: factory,
|
||||
);
|
||||
|
||||
CacheObject tile(String key, {int daysOld = 0, int? id}) => CacheObject(
|
||||
'https://tile.openstreetmap.org/$key.png',
|
||||
key: key,
|
||||
id: id,
|
||||
relativePath: '$key.png',
|
||||
validTill: DateTime(2030),
|
||||
touched: DateTime.now().subtract(Duration(days: daysOld)),
|
||||
length: 123,
|
||||
eTag: 'etag-$key',
|
||||
);
|
||||
|
||||
setUpAll(sqfliteFfiInit);
|
||||
setUp(() async {
|
||||
directory = await Directory.systemTemp.createTemp('meshcore-map-metadata-');
|
||||
repository = createRepository();
|
||||
});
|
||||
tearDown(() async {
|
||||
await repository.close();
|
||||
await directory.delete(recursive: true);
|
||||
});
|
||||
|
||||
test('desktop selects SQLite and web keeps its platform default', () {
|
||||
expect(
|
||||
createMapTileCacheRepository('map_tile_cache'),
|
||||
Platform.isLinux || Platform.isWindows
|
||||
? isA<SqliteMapTileCacheRepository>()
|
||||
: isNot(isA<SqliteMapTileCacheRepository>()),
|
||||
);
|
||||
expect(
|
||||
web.createMapTileCacheRepository('map_tile_cache'),
|
||||
isA<NonStoringObjectProvider>(),
|
||||
);
|
||||
});
|
||||
|
||||
test('metadata survives reopen and supports updates and deletes', () async {
|
||||
await repository.open();
|
||||
final inserted = await repository.insert(tile('a'));
|
||||
expect(inserted.id, isNotNull);
|
||||
expect(inserted.touched, isNotNull);
|
||||
await repository.update(inserted.copyWith(length: 456));
|
||||
expect((await repository.get('a'))!.length, 456);
|
||||
await repository.close();
|
||||
|
||||
repository = createRepository();
|
||||
await repository.open();
|
||||
final restored = (await repository.get('a'))!;
|
||||
expect(restored.relativePath, 'a.png');
|
||||
expect(restored.eTag, 'etag-a');
|
||||
expect(restored.length, 456);
|
||||
expect(await repository.deleteAll([]), 0);
|
||||
expect(await repository.deleteAll([restored.id!, restored.id!]), 1);
|
||||
expect(await repository.get('a'), isNull);
|
||||
});
|
||||
|
||||
test('age and capacity queries select oldest metadata in SQLite', () async {
|
||||
await repository.open();
|
||||
for (var days = 2; days <= 5; days++) {
|
||||
await repository.insert(
|
||||
tile('tile-$days', daysOld: days),
|
||||
setTouchedToNow: false,
|
||||
);
|
||||
}
|
||||
expect(
|
||||
(await repository.getObjectsOverCapacity(2)).map((entry) => entry.key),
|
||||
['tile-4', 'tile-5'],
|
||||
);
|
||||
expect(
|
||||
(await repository.getOldObjects(
|
||||
const Duration(days: 3),
|
||||
)).map((entry) => entry.key),
|
||||
['tile-5', 'tile-4', 'tile-3'],
|
||||
);
|
||||
});
|
||||
|
||||
test('legacy JSON migrates without altering downloaded tile files', () async {
|
||||
final legacy = File('${directory.path}/map_tile_cache.json');
|
||||
final oldTile = tile('10/1/2', daysOld: 2, id: 88);
|
||||
final downloaded = File('${directory.path}/tile-bytes.png');
|
||||
await downloaded.writeAsBytes([1, 2, 3]);
|
||||
await legacy.writeAsString(
|
||||
jsonEncode([oldTile.toMap(setTouchedToNow: false)]),
|
||||
);
|
||||
|
||||
await repository.open();
|
||||
final imported = (await repository.get(oldTile.key))!;
|
||||
expect(imported.url, oldTile.url);
|
||||
expect(imported.relativePath, oldTile.relativePath);
|
||||
expect(
|
||||
imported.touched!.millisecondsSinceEpoch,
|
||||
oldTile.touched!.millisecondsSinceEpoch,
|
||||
);
|
||||
expect(imported.length, oldTile.length);
|
||||
expect(imported.eTag, oldTile.eTag);
|
||||
expect(await downloaded.readAsBytes(), [1, 2, 3]);
|
||||
expect(await legacy.exists(), isFalse);
|
||||
await repository.close();
|
||||
|
||||
// A crash after commit but before cleanup must not replay stale metadata.
|
||||
await legacy.writeAsString(
|
||||
jsonEncode([tile('stale', id: 99).toMap(setTouchedToNow: false)]),
|
||||
);
|
||||
repository = createRepository();
|
||||
await repository.open();
|
||||
expect(await repository.get('stale'), isNull);
|
||||
expect((await repository.getAllObjects()).length, 1);
|
||||
expect(await legacy.exists(), isFalse);
|
||||
});
|
||||
|
||||
test(
|
||||
'malformed migration imports readable records and sets the file aside',
|
||||
() async {
|
||||
final legacy = File('${directory.path}/map_tile_cache.json');
|
||||
final aside = File('${legacy.path}.unreadable');
|
||||
final content = jsonEncode([
|
||||
{'invalid': true},
|
||||
tile('readable', id: 1).toMap(setTouchedToNow: false),
|
||||
]);
|
||||
await legacy.writeAsString(content);
|
||||
await repository.open();
|
||||
expect((await repository.getAllObjects()).single.key, 'readable');
|
||||
expect(await legacy.exists(), isFalse);
|
||||
expect(await aside.readAsString(), content);
|
||||
await repository.close();
|
||||
|
||||
// The file that was set aside is not imported again.
|
||||
repository = createRepository();
|
||||
await repository.open();
|
||||
expect((await repository.getAllObjects()).length, 1);
|
||||
await repository.close();
|
||||
await repository.deleteDataFile();
|
||||
expect(await aside.exists(), isFalse);
|
||||
},
|
||||
);
|
||||
|
||||
test('a legacy file that is not JSON does not block opening', () async {
|
||||
final legacy = File('${directory.path}/map_tile_cache.json');
|
||||
await legacy.writeAsString('{broken');
|
||||
await repository.open();
|
||||
expect(await repository.getAllObjects(), isEmpty);
|
||||
expect(await legacy.exists(), isFalse);
|
||||
expect(await File('${legacy.path}.unreadable').readAsString(), '{broken');
|
||||
});
|
||||
|
||||
test(
|
||||
'failed SQL import rolls back rows and preserves original JSON',
|
||||
() async {
|
||||
await repository.open();
|
||||
await repository.close();
|
||||
final db = await factory.openDatabase(
|
||||
'${directory.path}/map_tile_cache.db',
|
||||
);
|
||||
await db.delete('cacheMigration');
|
||||
await db.execute('''
|
||||
CREATE TRIGGER fail_import BEFORE INSERT ON cacheObject
|
||||
WHEN NEW.key = 'bad' BEGIN SELECT RAISE(ABORT, 'test failure'); END
|
||||
''');
|
||||
await db.close();
|
||||
final legacy = File('${directory.path}/map_tile_cache.json');
|
||||
await legacy.writeAsString(
|
||||
jsonEncode([
|
||||
tile('good', id: 1).toMap(setTouchedToNow: false),
|
||||
tile('bad', id: 2).toMap(setTouchedToNow: false),
|
||||
]),
|
||||
);
|
||||
await expectLater(repository.open(), throwsA(isA<DatabaseException>()));
|
||||
expect(await legacy.exists(), isTrue);
|
||||
|
||||
final failed = await factory.openDatabase(
|
||||
'${directory.path}/map_tile_cache.db',
|
||||
);
|
||||
expect(await failed.query('cacheObject'), isEmpty);
|
||||
expect(await failed.query('cacheMigration'), isEmpty);
|
||||
await failed.execute('DROP TRIGGER fail_import');
|
||||
await failed.close();
|
||||
await repository.open();
|
||||
expect((await repository.getAllObjects()).length, 2);
|
||||
expect(await legacy.exists(), isFalse);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'newer database versions are rejected without deleting legacy data',
|
||||
() async {
|
||||
final db = await factory.openDatabase(
|
||||
'${directory.path}/map_tile_cache.db',
|
||||
options: OpenDatabaseOptions(
|
||||
version: SqliteMapTileCacheRepository.schemaVersion + 1,
|
||||
),
|
||||
);
|
||||
await db.close();
|
||||
final legacy = File('${directory.path}/map_tile_cache.json');
|
||||
await legacy.writeAsString('[]');
|
||||
await expectLater(repository.open(), throwsA(isA<DatabaseException>()));
|
||||
expect(await legacy.exists(), isTrue);
|
||||
},
|
||||
);
|
||||
|
||||
test('newer import markers are not overwritten or replayed', () async {
|
||||
await repository.open();
|
||||
await repository.insert(tile('current'));
|
||||
await repository.close();
|
||||
final db = await factory.openDatabase(
|
||||
'${directory.path}/map_tile_cache.db',
|
||||
);
|
||||
await db.update('cacheMigration', {
|
||||
'version': SqliteMapTileCacheRepository.legacyImportVersion + 1,
|
||||
});
|
||||
await db.close();
|
||||
final legacy = File('${directory.path}/map_tile_cache.json');
|
||||
await legacy.writeAsString(
|
||||
jsonEncode([tile('legacy', id: 1).toMap(setTouchedToNow: false)]),
|
||||
);
|
||||
await repository.open();
|
||||
expect((await repository.getAllObjects()).map((entry) => entry.key), [
|
||||
'current',
|
||||
]);
|
||||
expect(await legacy.exists(), isTrue);
|
||||
await repository.close();
|
||||
final reopened = await factory.openDatabase(
|
||||
'${directory.path}/map_tile_cache.db',
|
||||
);
|
||||
expect(
|
||||
(await reopened.query('cacheMigration')).single['version'],
|
||||
SqliteMapTileCacheRepository.legacyImportVersion + 1,
|
||||
);
|
||||
await reopened.close();
|
||||
});
|
||||
|
||||
test(
|
||||
'inventory connections do not close the cache-manager connection',
|
||||
() async {
|
||||
await repository.open();
|
||||
await repository.open();
|
||||
expect(await repository.close(), isFalse);
|
||||
final inserted = await repository.insert(tile('a'));
|
||||
expect((await repository.get('a'))!.id, inserted.id);
|
||||
expect(await repository.close(), isTrue);
|
||||
await repository.deleteDataFile();
|
||||
expect(await repository.exists(), isFalse);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -27,12 +27,66 @@ void main() {
|
||||
);
|
||||
});
|
||||
|
||||
test('short replies repeated by the same sender are not duplicates', () {
|
||||
test('sameSenderSends sets which send in a row is flagged', () {
|
||||
final tracker = DuplicateTracker();
|
||||
for (final text in ['ok', 'test', 'yes sir', 'ok']) {
|
||||
tracker.check(channelId: 'c', sender: 'Alice', text: text, at: t0);
|
||||
const text = 'Anyone on the hill repeater?';
|
||||
FilterReason? send(int minutes) => tracker.check(
|
||||
channelId: 'c',
|
||||
sender: 'Bob',
|
||||
text: text,
|
||||
at: t0.add(Duration(minutes: minutes)),
|
||||
sameSenderSends: 3,
|
||||
);
|
||||
expect(send(0), isNull);
|
||||
// Re-sent because nobody answered.
|
||||
expect(send(4), isNull);
|
||||
expect(send(9), FilterReason.duplicate);
|
||||
// A slow flood keeps the run going: each send is within the window of
|
||||
// the previous one.
|
||||
expect(send(17), FilterReason.duplicate);
|
||||
expect(send(25), FilterReason.duplicate);
|
||||
});
|
||||
|
||||
test('the same message seen again is never a repeat', () {
|
||||
final tracker = DuplicateTracker();
|
||||
const text = 'Gday from Brunkerville, how is everyone';
|
||||
// Another companion syncing messages the first one already delivered:
|
||||
// same sender, text and send second, arriving later.
|
||||
for (var i = 0; i < 5; i++) {
|
||||
expect(
|
||||
tracker.check(
|
||||
channelId: 'c',
|
||||
sender: 'VK2WSL TRACKER',
|
||||
text: text,
|
||||
at: t0,
|
||||
receivedAt: t0.add(Duration(minutes: i)),
|
||||
),
|
||||
isNull,
|
||||
);
|
||||
}
|
||||
for (final text in ['@[Bob] ok', 'test', 'yes sir']) {
|
||||
// Copies are not counted: a real re-send is only the second send.
|
||||
expect(
|
||||
tracker.check(
|
||||
channelId: 'c',
|
||||
sender: 'VK2WSL TRACKER',
|
||||
text: text,
|
||||
at: t0.add(const Duration(minutes: 2)),
|
||||
sameSenderSends: 3,
|
||||
),
|
||||
isNull,
|
||||
);
|
||||
});
|
||||
|
||||
test('short texts repeated by the same sender are duplicates', () {
|
||||
final tracker = DuplicateTracker();
|
||||
for (final text in ['hello', 'test', 'yes sir']) {
|
||||
expect(
|
||||
tracker.check(channelId: 'c', sender: 'Alice', text: text, at: t0),
|
||||
isNull,
|
||||
reason: text,
|
||||
);
|
||||
}
|
||||
for (final text in ['Hello!', 'test', 'yes sir']) {
|
||||
expect(
|
||||
tracker.check(
|
||||
channelId: 'c',
|
||||
@@ -40,12 +94,36 @@ void main() {
|
||||
text: text,
|
||||
at: t0.add(const Duration(minutes: 5)),
|
||||
),
|
||||
isNull,
|
||||
FilterReason.duplicate,
|
||||
reason: text,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('short texts use the same send count as long ones', () {
|
||||
final tracker = DuplicateTracker(sameSenderSends: 3);
|
||||
FilterReason? send(int minute) => tracker.check(
|
||||
channelId: 'c',
|
||||
sender: 'Alice',
|
||||
text: 'hello',
|
||||
at: t0.add(Duration(minutes: minute)),
|
||||
);
|
||||
expect(send(0), isNull);
|
||||
expect(send(1), isNull);
|
||||
expect(send(2), FilterReason.duplicate);
|
||||
});
|
||||
|
||||
test('a short text from many senders is not a repeat', () {
|
||||
final tracker = DuplicateTracker();
|
||||
for (final sender in ['Alice', 'Bob', 'Carol', 'Dave']) {
|
||||
expect(
|
||||
tracker.check(channelId: 'c', sender: sender, text: 'hello', at: t0),
|
||||
isNull,
|
||||
reason: sender,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('same sender repeat after the window is not a duplicate', () {
|
||||
final tracker = DuplicateTracker();
|
||||
tracker.check(channelId: 'c', sender: 'Bob', text: 'Hello', at: t0);
|
||||
|
||||
@@ -204,8 +204,10 @@ void main() {
|
||||
|
||||
test('duplicates setting off still records but does not filter', () async {
|
||||
await service.updateSettings(service.settings.copyWith(duplicates: false));
|
||||
expect(eval('a', 'meet at the park'), isNull);
|
||||
expect(eval('a', 'meet at the park'), isNull);
|
||||
for (var i = 0; i < 3; i++) {
|
||||
expect(eval('a', 'meet at the park'), isNull);
|
||||
now = now.add(const Duration(minutes: 1));
|
||||
}
|
||||
await service.updateSettings(service.settings.copyWith(duplicates: true));
|
||||
expect(eval('a', 'meet at the park')?.reason, FilterReason.duplicate);
|
||||
});
|
||||
@@ -216,13 +218,55 @@ void main() {
|
||||
eval('a', 'buy cheap radios here now')?.reason,
|
||||
FilterReason.textRule,
|
||||
);
|
||||
now = now.add(const Duration(minutes: 1));
|
||||
expect(
|
||||
eval('a', 'buy cheap radios here now')?.reason,
|
||||
FilterReason.textRule,
|
||||
);
|
||||
await service.removeRule('x');
|
||||
now = now.add(const Duration(minutes: 1));
|
||||
expect(
|
||||
eval('a', 'buy cheap radios here now')?.reason,
|
||||
FilterReason.duplicate,
|
||||
);
|
||||
});
|
||||
|
||||
test('repeatSends setting picks which send is flagged', () async {
|
||||
await service.updateSettings(service.settings.copyWith(repeatSends: 3));
|
||||
expect(eval('a', 'meet at the park'), isNull);
|
||||
now = now.add(const Duration(minutes: 1));
|
||||
expect(eval('a', 'meet at the park'), isNull);
|
||||
now = now.add(const Duration(minutes: 1));
|
||||
expect(eval('a', 'meet at the park')?.reason, FilterReason.duplicate);
|
||||
});
|
||||
|
||||
test('repeatSends is saved and clamped', () {
|
||||
const settings = MessageFilterSettings(repeatSends: 4);
|
||||
expect(MessageFilterSettings.fromJson(settings.toJson()).repeatSends, 4);
|
||||
expect(MessageFilterSettings.fromJson({}).repeatSends, 2);
|
||||
expect(MessageFilterSettings.fromJson({'repeatSends': 99}).repeatSends, 5);
|
||||
expect(MessageFilterSettings.fromJson({'repeatSends': 0}).repeatSends, 2);
|
||||
});
|
||||
|
||||
test('messages that mention someone are exempt from duplicates', () {
|
||||
for (var i = 0; i < 4; i++) {
|
||||
// Asking several people the same thing.
|
||||
expect(eval('a', '@[Person$i] are you home yet'), isNull);
|
||||
expect(
|
||||
service.evaluate(
|
||||
channelId: _channel,
|
||||
sender: 'b',
|
||||
text: 'did you get my message',
|
||||
isReply: true,
|
||||
),
|
||||
isNull,
|
||||
);
|
||||
now = now.add(const Duration(minutes: 1));
|
||||
}
|
||||
// Mentions were not recorded, so the plain text starts fresh.
|
||||
expect(eval('a', 'are you home yet'), isNull);
|
||||
});
|
||||
|
||||
test('not spam exempts duplicates in that channel', () async {
|
||||
eval('a', 'meet at the park');
|
||||
await service.markNotSpam(
|
||||
@@ -279,6 +323,26 @@ void main() {
|
||||
expect(service.notSpamExampleCount, 1);
|
||||
});
|
||||
|
||||
test('bulk spam and not-spam store every example and persist', () async {
|
||||
await service.markSpamMany([
|
||||
(sender: 'a', text: 'Buy now'),
|
||||
(sender: 'b', text: 'Free crypto'),
|
||||
(sender: 'c', text: ' '),
|
||||
]);
|
||||
expect(service.spamExampleCount, 2);
|
||||
|
||||
await service.markNotSpamMany([
|
||||
(channelId: _channel, sender: 'a', text: 'buy now'),
|
||||
(channelId: _channel, sender: 'd', text: 'Hello all'),
|
||||
]);
|
||||
expect(service.spamExampleCount, 1);
|
||||
expect(service.notSpamExampleCount, 2);
|
||||
|
||||
final reloaded = await create();
|
||||
expect(reloaded.spamExampleCount, 1);
|
||||
expect(reloaded.notSpamExampleCount, 2);
|
||||
});
|
||||
|
||||
test('state persists across instances and reset keeps rules', () async {
|
||||
await service.addRule(const FilterRule(id: 'r1', pattern: 'promo'));
|
||||
await service.updateSettings(
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/models/contact.dart';
|
||||
import 'package:meshcore_open/models/message.dart';
|
||||
import 'package:meshcore_open/models/path_selection.dart';
|
||||
import 'package:meshcore_open/services/message_retry_service.dart';
|
||||
|
||||
Contact _contact({int pathLength = -1, List<int> path = const []}) => Contact(
|
||||
publicKey: Uint8List.fromList(List<int>.generate(32, (i) => 0xAA + i)),
|
||||
name: 'Test',
|
||||
type: 1,
|
||||
pathLength: pathLength,
|
||||
path: Uint8List.fromList(path),
|
||||
lastSeen: DateTime.now(),
|
||||
);
|
||||
|
||||
/// Route failures only count once the contact proved reachable: a message
|
||||
/// that never gets through must not wreck the routes' history.
|
||||
void main() {
|
||||
late MessageRetryService service;
|
||||
late Map<String, Message> latest;
|
||||
late List<({int attempt, int timestamp})> sends;
|
||||
late List<({List<int> path, bool flood, bool success})> results;
|
||||
final selfKey = Uint8List(32);
|
||||
|
||||
setUp(() {
|
||||
service = MessageRetryService(
|
||||
sentWatchdogGrace: const Duration(milliseconds: 10),
|
||||
);
|
||||
service.setMaxRetries(2);
|
||||
latest = {};
|
||||
sends = [];
|
||||
results = [];
|
||||
service.initialize(
|
||||
RetryServiceConfig(
|
||||
sendMessage: (_, _, attempt, timestamp) async {
|
||||
sends.add((attempt: attempt, timestamp: timestamp));
|
||||
},
|
||||
addMessage: (_, m) => latest[m.messageId] = m,
|
||||
updateMessage: (m) => latest[m.messageId] = m,
|
||||
getSelfPublicKey: () => selfKey,
|
||||
calculateTimeout: (_, _, {String? contactKey, int? deviceTimeoutMs}) =>
|
||||
20,
|
||||
recordPathResult: (_, PathSelection selection, success, _) =>
|
||||
results.add((
|
||||
path: List<int>.of(selection.pathBytes),
|
||||
flood: selection.useFlood,
|
||||
success: success,
|
||||
)),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
tearDown(() => service.dispose());
|
||||
|
||||
// Lists inside records compare by identity, so compare readable strings.
|
||||
List<String> recorded() => [
|
||||
for (final r in results)
|
||||
'${r.flood ? 'flood' : r.path}:${r.success ? 'ok' : 'fail'}',
|
||||
];
|
||||
|
||||
int ackHashFor(int attempt) => MessageRetryService.computeExpectedAckHash(
|
||||
sends.firstWhere((s) => s.attempt == attempt).timestamp,
|
||||
attempt,
|
||||
'hello',
|
||||
selfKey,
|
||||
);
|
||||
|
||||
test('a message that never gets through blames no route', () async {
|
||||
await service.sendMessageWithRetry(
|
||||
contact: _contact(pathLength: 2, path: [0x11, 0x22]),
|
||||
text: 'hello',
|
||||
);
|
||||
await pumpEventQueue();
|
||||
|
||||
// Attempt 0 times out, the 1 s backoff runs, attempt 1 times out too.
|
||||
await Future<void>.delayed(const Duration(milliseconds: 1300));
|
||||
|
||||
expect(latest.values.single.status, MessageStatus.failed);
|
||||
expect(results.where((r) => !r.flood), isEmpty);
|
||||
});
|
||||
|
||||
test('once delivered, the routes that timed out are blamed', () async {
|
||||
await service.sendMessageWithRetry(
|
||||
contact: _contact(pathLength: 2, path: [0x11, 0x22]),
|
||||
text: 'hello',
|
||||
);
|
||||
await pumpEventQueue();
|
||||
|
||||
// Attempt 0 times out; the retry goes out on another route.
|
||||
await Future<void>.delayed(const Duration(milliseconds: 100));
|
||||
service.updatePendingContact(_contact(pathLength: 1, path: [0x33]));
|
||||
// Act as soon as attempt 1 goes out, before its own 30 ms watchdog.
|
||||
for (var i = 0; i < 300 && sends.length < 2; i++) {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 5));
|
||||
}
|
||||
expect(sends.map((s) => s.attempt), [0, 1]);
|
||||
|
||||
// The radio confirms the send (so the ACK maps to attempt 1), then ACKs.
|
||||
expect(service.updateMessageFromSent(ackHashFor(1), 60000), isTrue);
|
||||
service.handleAckReceived(ackHashFor(1), 400);
|
||||
|
||||
expect(latest.values.single.status, MessageStatus.delivered);
|
||||
expect(recorded(), ['[17, 34]:fail', '[51]:ok']);
|
||||
});
|
||||
|
||||
test(
|
||||
'a late ACK for a timed-out attempt credits it, not blames it',
|
||||
() async {
|
||||
await service.sendMessageWithRetry(
|
||||
contact: _contact(pathLength: 2, path: [0x11, 0x22]),
|
||||
text: 'hello',
|
||||
);
|
||||
await pumpEventQueue();
|
||||
|
||||
// Attempt 0 times out and its failure is held back...
|
||||
await Future<void>.delayed(const Duration(milliseconds: 100));
|
||||
expect(latest.values.single.retryCount, 1);
|
||||
|
||||
// ...then its ACK arrives after all.
|
||||
service.handleAckReceived(ackHashFor(0), 900);
|
||||
|
||||
expect(recorded(), ['[17, 34]:ok']);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'a late ACK after the final timeout still blames earlier routes',
|
||||
() async {
|
||||
await service.sendMessageWithRetry(
|
||||
contact: _contact(pathLength: 2, path: [0x11, 0x22]),
|
||||
text: 'hello',
|
||||
);
|
||||
await pumpEventQueue();
|
||||
|
||||
// Attempt 0 times out; attempt 1 goes out on another route and also
|
||||
// times out, so the message is marked failed.
|
||||
await Future<void>.delayed(const Duration(milliseconds: 100));
|
||||
service.updatePendingContact(_contact(pathLength: 1, path: [0x33]));
|
||||
for (var i = 0; i < 300 && sends.length < 2; i++) {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 5));
|
||||
}
|
||||
expect(service.updateMessageFromSent(ackHashFor(1), 20), isTrue);
|
||||
await Future<void>.delayed(const Duration(milliseconds: 100));
|
||||
expect(latest.values.single.status, MessageStatus.failed);
|
||||
expect(recorded(), isEmpty);
|
||||
|
||||
// Within the grace period, attempt 1's ACK arrives after all.
|
||||
service.handleAckReceived(ackHashFor(1), 1500);
|
||||
|
||||
expect(latest.values.single.status, MessageStatus.delivered);
|
||||
expect(recorded(), ['[17, 34]:fail', '[51]:ok']);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
import 'dart:async';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/models/contact.dart';
|
||||
import 'package:meshcore_open/models/path_history.dart';
|
||||
import 'package:meshcore_open/services/path_history_service.dart';
|
||||
import 'package:meshcore_open/services/storage_service.dart';
|
||||
|
||||
class _Load {
|
||||
_Load(this.scope, this.contact);
|
||||
final String scope;
|
||||
final String contact;
|
||||
final result = Completer<ContactPathHistory?>();
|
||||
}
|
||||
|
||||
class _Storage extends StorageService {
|
||||
String scope = 'a';
|
||||
bool delayLoads = true;
|
||||
Completer<void>? saveGate;
|
||||
bool failClears = false;
|
||||
final loads = <_Load>[];
|
||||
final saved = <String, ContactPathHistory>{};
|
||||
|
||||
@override
|
||||
set setPublicKeyHex(String value) => scope = value;
|
||||
|
||||
@override
|
||||
Future<ContactPathHistory?> loadPathHistory(String contactPubKeyHex) async {
|
||||
final load = _Load(scope, contactPubKeyHex);
|
||||
loads.add(load);
|
||||
if (delayLoads) return load.result.future;
|
||||
return saved['${load.scope}:$contactPubKeyHex'];
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> savePathHistory(
|
||||
String contactPubKeyHex,
|
||||
ContactPathHistory history,
|
||||
) async {
|
||||
final key = '$scope:$contactPubKeyHex';
|
||||
await saveGate?.future;
|
||||
saved[key] = history;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> clearPathHistory(String contactPubKeyHex) async {
|
||||
if (failClears) throw StateError('clear failed');
|
||||
saved.remove('$scope:$contactPubKeyHex');
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> clearAllPathHistories() async {
|
||||
if (failClears) throw StateError('clear failed');
|
||||
saved.removeWhere((key, value) => key.startsWith('$scope:'));
|
||||
}
|
||||
}
|
||||
|
||||
ContactPathHistory _history(String key, int hop) => ContactPathHistory(
|
||||
contactPubKeyHex: key,
|
||||
recentPaths: [
|
||||
PathRecord(
|
||||
hopCount: 1,
|
||||
tripTimeMs: 1,
|
||||
timestamp: DateTime(2026),
|
||||
wasFloodDiscovery: true,
|
||||
pathBytes: [hop],
|
||||
successCount: 1,
|
||||
failureCount: 0,
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
Contact _contact(int hop) => Contact(
|
||||
publicKey: Uint8List(32),
|
||||
name: 'Test',
|
||||
type: 1,
|
||||
pathLength: 1,
|
||||
path: Uint8List.fromList([hop]),
|
||||
lastSeen: DateTime(2026),
|
||||
);
|
||||
|
||||
Future<void> _settle() => Future<void>.delayed(Duration.zero);
|
||||
|
||||
void main() {
|
||||
late _Storage storage;
|
||||
late PathHistoryService service;
|
||||
setUp(() {
|
||||
storage = _Storage();
|
||||
service = PathHistoryService(storage);
|
||||
});
|
||||
tearDown(() => service.dispose());
|
||||
|
||||
test(
|
||||
'an old load cannot populate the next radio or remove its pending load',
|
||||
() async {
|
||||
service.getRecentPaths('contact');
|
||||
await _settle();
|
||||
service.setDevicePublicKey('b');
|
||||
service.getRecentPaths('contact');
|
||||
await _settle();
|
||||
expect(storage.loads.map((load) => load.scope), ['a', 'b']);
|
||||
storage.loads[0].result.complete(_history('contact', 1));
|
||||
await _settle();
|
||||
expect(service.isCached('contact'), isFalse);
|
||||
service.getRecentPaths('contact');
|
||||
await _settle();
|
||||
expect(storage.loads, hasLength(2));
|
||||
storage.loads[1].result.complete(_history('contact', 2));
|
||||
await _settle();
|
||||
expect(service.peekRecentPaths('contact').single.pathBytes, [2]);
|
||||
},
|
||||
);
|
||||
|
||||
test('an old pending path event cannot be added to the next radio', () async {
|
||||
final contact = _contact(1);
|
||||
service.handlePathUpdated(contact);
|
||||
await _settle();
|
||||
service.setDevicePublicKey('b');
|
||||
service.getRecentPaths(contact.publicKeyHex);
|
||||
await _settle();
|
||||
storage.loads[1].result.complete(_history(contact.publicKeyHex, 2));
|
||||
await _settle();
|
||||
storage.loads[0].result.complete(null);
|
||||
await _settle();
|
||||
expect(service.peekRecentPaths(contact.publicKeyHex).single.pathBytes, [2]);
|
||||
});
|
||||
|
||||
test('clearing a contact invalidates an outstanding read', () async {
|
||||
service.getRecentPaths('contact');
|
||||
await _settle();
|
||||
await service.clearPathHistory('contact');
|
||||
storage.loads.single.result.complete(_history('contact', 1));
|
||||
await _settle();
|
||||
expect(service.isCached('contact'), isFalse);
|
||||
});
|
||||
|
||||
for (final dispose in [false, true]) {
|
||||
test(
|
||||
'${dispose ? 'disposing' : 'clearing all'} prevents delayed load notifications',
|
||||
() async {
|
||||
var notifications = 0;
|
||||
service.addListener(() => notifications++);
|
||||
service.getRecentPaths('contact');
|
||||
await _settle();
|
||||
if (dispose) {
|
||||
service.dispose();
|
||||
} else {
|
||||
service.clearAllHistories();
|
||||
}
|
||||
final before = notifications;
|
||||
storage.loads.single.result.complete(_history('contact', 1));
|
||||
await _settle();
|
||||
expect(service.isCached('contact'), isFalse);
|
||||
expect(notifications, before);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
test('reads wait for an already-started history save', () async {
|
||||
storage.delayLoads = false;
|
||||
service.handlePathUpdated(_contact(1));
|
||||
await _settle();
|
||||
storage.saveGate = Completer<void>();
|
||||
final save = service.flushPendingWrites();
|
||||
await _settle();
|
||||
final read = service.readStoredPaths('other');
|
||||
await _settle();
|
||||
expect(storage.loads.where((load) => load.contact == 'other'), isEmpty);
|
||||
storage.saveGate!.complete();
|
||||
await save;
|
||||
expect(await read, isEmpty);
|
||||
expect(
|
||||
storage.loads.where((load) => load.contact == 'other'),
|
||||
hasLength(1),
|
||||
);
|
||||
});
|
||||
|
||||
test(
|
||||
'clearing all waits for in-flight saves before allowing a new read',
|
||||
() async {
|
||||
storage.delayLoads = false;
|
||||
final contact = _contact(1);
|
||||
service.handlePathUpdated(contact);
|
||||
await _settle();
|
||||
storage.saveGate = Completer<void>();
|
||||
final save = service.flushPendingWrites();
|
||||
await _settle();
|
||||
service.clearAllHistories();
|
||||
final read = service.readStoredPaths(contact.publicKeyHex);
|
||||
storage.saveGate!.complete();
|
||||
await save;
|
||||
expect(await read, isEmpty);
|
||||
expect(storage.saved, isEmpty);
|
||||
},
|
||||
);
|
||||
|
||||
test('a scope switch while waiting for saves skips the old read', () async {
|
||||
storage.delayLoads = false;
|
||||
service.handlePathUpdated(_contact(1));
|
||||
await _settle();
|
||||
storage.saveGate = Completer<void>();
|
||||
final save = service.flushPendingWrites();
|
||||
final read = service.readStoredPaths('other');
|
||||
service.setDevicePublicKey('b');
|
||||
storage.saveGate!.complete();
|
||||
await save;
|
||||
expect(await read, isEmpty);
|
||||
expect(storage.loads.where((load) => load.contact == 'other'), isEmpty);
|
||||
expect(storage.saved.keys.single, startsWith('a:'));
|
||||
});
|
||||
|
||||
test(
|
||||
'a failed clear does not break later loads, clears or flushes',
|
||||
() async {
|
||||
storage.delayLoads = false;
|
||||
storage.failClears = true;
|
||||
await expectLater(service.clearPathHistory('contact'), throwsStateError);
|
||||
service.clearAllHistories();
|
||||
await _settle();
|
||||
|
||||
storage.failClears = false;
|
||||
storage.saved['a:contact'] = _history('contact', 3);
|
||||
await service.flushPendingWrites();
|
||||
expect((await service.readStoredPaths('contact')).single.pathBytes, [3]);
|
||||
await service.clearPathHistory('contact');
|
||||
expect(storage.saved, isEmpty);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'dart:math' as math;
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
@@ -104,9 +105,33 @@ void main() {
|
||||
|
||||
setUp(() {
|
||||
storage = FakeStorageService();
|
||||
svc = PathHistoryService(storage);
|
||||
// Picks are random by design (Thompson sampling); seed for repeatability.
|
||||
svc = PathHistoryService(storage, random: math.Random(1));
|
||||
});
|
||||
|
||||
/// How often each route is picked over [n] selections, keyed by hex bytes.
|
||||
Map<String, int> tally(
|
||||
String pubKey, {
|
||||
int n = 400,
|
||||
int attemptIndex = 0,
|
||||
List<PathSelection> recent = const [],
|
||||
}) {
|
||||
final counts = <String, int>{};
|
||||
for (var i = 0; i < n; i++) {
|
||||
final pick = svc.selectPathForAttempt(
|
||||
pubKey,
|
||||
attemptIndex: attemptIndex,
|
||||
maxRetries: 5,
|
||||
recentSelections: recent,
|
||||
);
|
||||
final key = pick.useFlood
|
||||
? 'flood'
|
||||
: pick.pathBytes.map((b) => b.toRadixString(16)).join(',');
|
||||
counts[key] = (counts[key] ?? 0) + 1;
|
||||
}
|
||||
return counts;
|
||||
}
|
||||
|
||||
group('path selection', () {
|
||||
test('empty path history returns flood', () {
|
||||
const pubKey =
|
||||
@@ -149,135 +174,129 @@ void main() {
|
||||
}
|
||||
});
|
||||
|
||||
test(
|
||||
'retries avoid immediately repeating the same path when possible',
|
||||
() async {
|
||||
final pubKey = _hex('rot1');
|
||||
await _seed(svc, pubKey, pathBytes: [0xAA], hopCount: 1, weight: 1.0);
|
||||
test('retries usually move to a different path', () async {
|
||||
final pubKey = _hex('rot1');
|
||||
await _seed(svc, pubKey, pathBytes: [0xAA], hopCount: 1, weight: 1.0);
|
||||
svc.recordPathResult(
|
||||
pubKey,
|
||||
const PathSelection(pathBytes: [0xBB], hopCount: 1, useFlood: false),
|
||||
success: true,
|
||||
successIncrement: 0.0,
|
||||
);
|
||||
await _flush();
|
||||
|
||||
// After [0xBB] missed, the retry should mostly try [0xAA].
|
||||
final counts = tally(
|
||||
pubKey,
|
||||
attemptIndex: 1,
|
||||
recent: const [
|
||||
PathSelection(pathBytes: [0xBB], hopCount: 1, useFlood: false),
|
||||
],
|
||||
);
|
||||
expect(counts['flood'], isNull);
|
||||
expect(counts['aa']!, greaterThan(counts['bb'] ?? 0));
|
||||
});
|
||||
|
||||
test('a third retry favours the path not yet tried', () async {
|
||||
final pubKey = _hex('rot2');
|
||||
await _seed(svc, pubKey, pathBytes: [0xA1], hopCount: 1, weight: 3.0);
|
||||
for (final bytes in const [
|
||||
[0xB2],
|
||||
[0xC3],
|
||||
]) {
|
||||
svc.recordPathResult(
|
||||
pubKey,
|
||||
const PathSelection(pathBytes: [0xBB], hopCount: 1, useFlood: false),
|
||||
PathSelection(pathBytes: bytes, hopCount: 1, useFlood: false),
|
||||
success: true,
|
||||
successIncrement: 0.0,
|
||||
);
|
||||
await _flush();
|
||||
}
|
||||
await _flush();
|
||||
|
||||
final first = svc.selectPathForAttempt(
|
||||
pubKey,
|
||||
attemptIndex: 0,
|
||||
maxRetries: 5,
|
||||
);
|
||||
final second = svc.selectPathForAttempt(
|
||||
pubKey,
|
||||
attemptIndex: 1,
|
||||
maxRetries: 5,
|
||||
recentSelections: [first],
|
||||
);
|
||||
final counts = tally(
|
||||
pubKey,
|
||||
attemptIndex: 2,
|
||||
recent: const [
|
||||
PathSelection(pathBytes: [0xB2], hopCount: 1, useFlood: false),
|
||||
PathSelection(pathBytes: [0xC3], hopCount: 1, useFlood: false),
|
||||
],
|
||||
);
|
||||
// [0xA1] is untested (no results) yet still the most likely pick,
|
||||
// because both others just missed for this message.
|
||||
expect(counts['a1']!, greaterThan(counts['b2'] ?? 0));
|
||||
expect(counts['a1']!, greaterThan(counts['c3'] ?? 0));
|
||||
});
|
||||
|
||||
expect(first.useFlood, isFalse);
|
||||
expect(second.useFlood, isFalse);
|
||||
expect(second.pathBytes, isNot(equals(first.pathBytes)));
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'retries avoid the last two paths when a third option exists',
|
||||
() async {
|
||||
final pubKey = _hex('rot2');
|
||||
await _seed(svc, pubKey, pathBytes: [0xA1], hopCount: 1, weight: 3.0);
|
||||
test('first attempts favour the best path but still try others', () async {
|
||||
final pubKey = _hex('rot3');
|
||||
await _seed(svc, pubKey, pathBytes: [0xA1], hopCount: 1, weight: 4.0);
|
||||
for (var i = 0; i < 6; i++) {
|
||||
svc.recordPathResult(
|
||||
pubKey,
|
||||
const PathSelection(pathBytes: [0xB2], hopCount: 1, useFlood: false),
|
||||
success: true,
|
||||
successIncrement: 1.0,
|
||||
);
|
||||
svc.recordPathResult(
|
||||
pubKey,
|
||||
const PathSelection(pathBytes: [0xC3], hopCount: 1, useFlood: false),
|
||||
success: true,
|
||||
successIncrement: 0.0,
|
||||
);
|
||||
await _flush();
|
||||
|
||||
final first = svc.selectPathForAttempt(
|
||||
pubKey,
|
||||
attemptIndex: 0,
|
||||
maxRetries: 5,
|
||||
);
|
||||
final second = svc.selectPathForAttempt(
|
||||
pubKey,
|
||||
attemptIndex: 1,
|
||||
maxRetries: 5,
|
||||
recentSelections: [first],
|
||||
);
|
||||
final third = svc.selectPathForAttempt(
|
||||
pubKey,
|
||||
attemptIndex: 2,
|
||||
maxRetries: 5,
|
||||
recentSelections: [first, second],
|
||||
);
|
||||
|
||||
final chosenPaths = [
|
||||
first.pathBytes,
|
||||
second.pathBytes,
|
||||
third.pathBytes,
|
||||
];
|
||||
expect(
|
||||
chosenPaths
|
||||
.map((path) => path.map((b) => b.toRadixString(16)).join(','))
|
||||
.toSet()
|
||||
.length,
|
||||
equals(3),
|
||||
);
|
||||
expect(
|
||||
chosenPaths,
|
||||
everyElement(anyOf(equals([0xA1]), equals([0xB2]), equals([0xC3]))),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test('first-attempt selection rotates across ranked candidates', () async {
|
||||
final pubKey = _hex('rot3');
|
||||
await _seed(svc, pubKey, pathBytes: [0xA1], hopCount: 1, weight: 4.0);
|
||||
svc.recordPathResult(
|
||||
pubKey,
|
||||
const PathSelection(pathBytes: [0xB2], hopCount: 1, useFlood: false),
|
||||
success: true,
|
||||
successIncrement: 1.0,
|
||||
);
|
||||
}
|
||||
svc.recordPathResult(
|
||||
pubKey,
|
||||
const PathSelection(pathBytes: [0xC3], hopCount: 1, useFlood: false),
|
||||
success: true,
|
||||
successIncrement: 0.5,
|
||||
success: false,
|
||||
);
|
||||
await _flush();
|
||||
|
||||
final first = svc.selectPathForAttempt(
|
||||
pubKey,
|
||||
attemptIndex: 0,
|
||||
maxRetries: 5,
|
||||
);
|
||||
final second = svc.selectPathForAttempt(
|
||||
pubKey,
|
||||
attemptIndex: 0,
|
||||
maxRetries: 5,
|
||||
);
|
||||
final third = svc.selectPathForAttempt(
|
||||
pubKey,
|
||||
attemptIndex: 0,
|
||||
maxRetries: 5,
|
||||
);
|
||||
final counts = tally(pubKey);
|
||||
expect(counts['b2']!, greaterThan(counts['a1'] ?? 0));
|
||||
expect(counts['b2']!, greaterThan(counts['c3'] ?? 0));
|
||||
// Exploration: the untested path is still tried now and then.
|
||||
expect(counts['a1'] ?? 0, greaterThan(0));
|
||||
});
|
||||
|
||||
expect(first.pathBytes, isNot(equals(second.pathBytes)));
|
||||
expect(second.pathBytes, isNot(equals(third.pathBytes)));
|
||||
expect(
|
||||
[first.pathBytes, second.pathBytes, third.pathBytes]
|
||||
.map((path) => path.map((b) => b.toRadixString(16)).join(','))
|
||||
.toSet()
|
||||
.length,
|
||||
equals(3),
|
||||
// Issue #643: the direct path (zero hops, no bytes) must be a rotation
|
||||
// candidate alongside saved multi-hop routes.
|
||||
test('direct path is a candidate alongside other routes', () async {
|
||||
final pubKey = _hex('dir1');
|
||||
await _seed(svc, pubKey, pathBytes: const [], hopCount: 0, weight: 2.0);
|
||||
svc.recordPathResult(
|
||||
pubKey,
|
||||
const PathSelection(pathBytes: [0xA1], hopCount: 1, useFlood: false),
|
||||
success: true,
|
||||
);
|
||||
await _flush();
|
||||
|
||||
final counts = tally(pubKey);
|
||||
expect(counts['flood'], isNull);
|
||||
expect(counts[''] ?? 0, greaterThan(0), reason: 'direct must be tried');
|
||||
expect(counts['a1'] ?? 0, greaterThan(0));
|
||||
});
|
||||
|
||||
test('a lone direct path is used instead of flooding', () async {
|
||||
final pubKey = _hex('dir2');
|
||||
await _seed(svc, pubKey, pathBytes: const [], hopCount: 0);
|
||||
final pick = svc.selectPathForAttempt(
|
||||
pubKey,
|
||||
attemptIndex: 0,
|
||||
maxRetries: 5,
|
||||
);
|
||||
expect(pick.useFlood, isFalse);
|
||||
expect(pick.hopCount, 0);
|
||||
});
|
||||
|
||||
test('resolvePathSelection keeps a direct auto selection', () {
|
||||
final contact = _makeContact(
|
||||
publicKeyHex: _hex('dir3'),
|
||||
pathLength: 2,
|
||||
path: const [0x01, 0x02],
|
||||
);
|
||||
final resolved = resolvePathSelection(
|
||||
contact,
|
||||
selection: const PathSelection(
|
||||
pathBytes: [],
|
||||
hopCount: 0,
|
||||
useFlood: false,
|
||||
),
|
||||
);
|
||||
expect(resolved.useFlood, isFalse);
|
||||
expect(resolved.hopCount, 0);
|
||||
expect(resolved.pathBytes, isEmpty);
|
||||
});
|
||||
|
||||
test('final attempt is always flood regardless of known paths', () async {
|
||||
@@ -330,12 +349,8 @@ void main() {
|
||||
);
|
||||
await _flush();
|
||||
|
||||
final first = svc.selectPathForAttempt(
|
||||
pubKey,
|
||||
attemptIndex: 0,
|
||||
maxRetries: 5,
|
||||
);
|
||||
expect(first.pathBytes, equals([0x02]));
|
||||
final counts = tally(pubKey);
|
||||
expect(counts['2']!, greaterThan(counts['1'] ?? 0));
|
||||
});
|
||||
|
||||
test('lower latency wins when reliability is tied', () async {
|
||||
@@ -356,12 +371,8 @@ void main() {
|
||||
);
|
||||
await _flush();
|
||||
|
||||
final first = svc.selectPathForAttempt(
|
||||
pubKey,
|
||||
attemptIndex: 0,
|
||||
maxRetries: 5,
|
||||
);
|
||||
expect(first.pathBytes, equals([0x20]));
|
||||
final counts = tally(pubKey, n: 1000);
|
||||
expect(counts['20']!, greaterThan(counts['10'] ?? 0));
|
||||
});
|
||||
|
||||
test('fresher path wins when reliability and latency are tied', () async {
|
||||
@@ -396,57 +407,47 @@ void main() {
|
||||
svc.getRecentPaths(pubKey);
|
||||
await _flush();
|
||||
|
||||
final first = svc.selectPathForAttempt(
|
||||
pubKey,
|
||||
attemptIndex: 0,
|
||||
maxRetries: 5,
|
||||
);
|
||||
expect(first.pathBytes, equals([0x02]));
|
||||
final counts = tally(pubKey, n: 1000);
|
||||
expect(counts['2']!, greaterThan(counts['1'] ?? 0));
|
||||
});
|
||||
|
||||
test(
|
||||
'higher route weight wins when other factors are effectively tied',
|
||||
() async {
|
||||
final pubKey = _hex('rank4');
|
||||
final sharedTimestamp = DateTime.now().subtract(
|
||||
const Duration(minutes: 30),
|
||||
);
|
||||
storage._store[pubKey] = ContactPathHistory(
|
||||
contactPubKeyHex: pubKey,
|
||||
recentPaths: [
|
||||
PathRecord(
|
||||
hopCount: 1,
|
||||
tripTimeMs: 750,
|
||||
timestamp: sharedTimestamp,
|
||||
wasFloodDiscovery: false,
|
||||
pathBytes: const [0x01],
|
||||
successCount: 1,
|
||||
failureCount: 0,
|
||||
routeWeight: 4.0,
|
||||
),
|
||||
PathRecord(
|
||||
hopCount: 1,
|
||||
tripTimeMs: 750,
|
||||
timestamp: sharedTimestamp,
|
||||
wasFloodDiscovery: false,
|
||||
pathBytes: const [0x02],
|
||||
successCount: 1,
|
||||
failureCount: 0,
|
||||
routeWeight: 1.0,
|
||||
),
|
||||
],
|
||||
);
|
||||
svc.getRecentPaths(pubKey);
|
||||
await _flush();
|
||||
test('route weight alone does not decide between equal routes', () async {
|
||||
final pubKey = _hex('rank4');
|
||||
final sharedTimestamp = DateTime.now().subtract(
|
||||
const Duration(minutes: 30),
|
||||
);
|
||||
storage._store[pubKey] = ContactPathHistory(
|
||||
contactPubKeyHex: pubKey,
|
||||
recentPaths: [
|
||||
PathRecord(
|
||||
hopCount: 1,
|
||||
tripTimeMs: 750,
|
||||
timestamp: sharedTimestamp,
|
||||
wasFloodDiscovery: false,
|
||||
pathBytes: const [0x01],
|
||||
successCount: 1,
|
||||
failureCount: 0,
|
||||
routeWeight: 4.0,
|
||||
),
|
||||
PathRecord(
|
||||
hopCount: 1,
|
||||
tripTimeMs: 750,
|
||||
timestamp: sharedTimestamp,
|
||||
wasFloodDiscovery: false,
|
||||
pathBytes: const [0x02],
|
||||
successCount: 1,
|
||||
failureCount: 0,
|
||||
routeWeight: 1.0,
|
||||
),
|
||||
],
|
||||
);
|
||||
svc.getRecentPaths(pubKey);
|
||||
await _flush();
|
||||
|
||||
final first = svc.selectPathForAttempt(
|
||||
pubKey,
|
||||
attemptIndex: 0,
|
||||
maxRetries: 5,
|
||||
);
|
||||
expect(first.pathBytes, equals([0x01]));
|
||||
},
|
||||
);
|
||||
// Choice follows delivery results; weight only guards deletion.
|
||||
final counts = tally(pubKey, n: 1000);
|
||||
expect(counts['1']!, inInclusiveRange(350, 650));
|
||||
});
|
||||
});
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
@@ -545,6 +546,48 @@ void main() {
|
||||
expect(paths.first.routeWeight, closeTo(1.5, 0.001));
|
||||
});
|
||||
|
||||
test('a route that delivered this week survives a run of failures', () {
|
||||
// e.g. a repeater down for a day: the route must still be there when
|
||||
// it comes back. Faded stats keep it out of use meanwhile.
|
||||
var clock = DateTime(2026, 11, 1);
|
||||
final timed = PathHistoryService(
|
||||
FakeStorageService(),
|
||||
random: math.Random(1),
|
||||
clock: () => clock,
|
||||
);
|
||||
final pubKey = _hex('w0a1');
|
||||
const route = PathSelection(
|
||||
pathBytes: [0x01],
|
||||
hopCount: 1,
|
||||
useFlood: false,
|
||||
);
|
||||
return () async {
|
||||
timed.getRecentPaths(pubKey);
|
||||
await _flush();
|
||||
timed.recordPathResult(pubKey, route, success: true);
|
||||
clock = clock.add(const Duration(days: 1));
|
||||
for (var i = 0; i < 6; i++) {
|
||||
timed.recordPathResult(
|
||||
pubKey,
|
||||
route,
|
||||
success: false,
|
||||
failureDecrement: 0.5,
|
||||
);
|
||||
}
|
||||
expect(timed.getRecentPaths(pubKey), hasLength(1));
|
||||
|
||||
// A week without a delivery: the next failure removes it.
|
||||
clock = clock.add(const Duration(days: 8));
|
||||
timed.recordPathResult(
|
||||
pubKey,
|
||||
route,
|
||||
success: false,
|
||||
failureDecrement: 0.5,
|
||||
);
|
||||
expect(timed.getRecentPaths(pubKey), isEmpty);
|
||||
}();
|
||||
});
|
||||
|
||||
test('failure to 0 removes the path', () async {
|
||||
final pubKey = _hex('w004');
|
||||
await _seed(svc, pubKey, pathBytes: [0x01], hopCount: 1, weight: 0.3);
|
||||
@@ -735,6 +778,27 @@ void main() {
|
||||
expect(credited.tripTimeMs, equals(3000));
|
||||
});
|
||||
|
||||
test('a flood answered directly credits the direct path', () async {
|
||||
final pubKey = _hex('fa0d');
|
||||
await _seed(svc, pubKey, pathBytes: [0xAA], hopCount: 1, weight: 1.0);
|
||||
|
||||
svc.recordFloodPathAttribution(
|
||||
contactPubKeyHex: pubKey,
|
||||
pathBytes: const [],
|
||||
hopCount: 0,
|
||||
tripTimeMs: 800,
|
||||
successIncrement: 0.5,
|
||||
maxWeight: 5.0,
|
||||
);
|
||||
await _flush();
|
||||
|
||||
final direct = svc
|
||||
.getRecentPaths(pubKey)
|
||||
.firstWhere((p) => p.pathBytes.isEmpty && p.hopCount == 0);
|
||||
expect(direct.successCount, 1);
|
||||
expect(direct.routeWeight, closeTo(1.5, 0.001));
|
||||
});
|
||||
|
||||
test('creates new path record when path is unknown', () async {
|
||||
final pubKey = _hex('fa02');
|
||||
// Seed with a different path so the cache is warm.
|
||||
@@ -777,24 +841,27 @@ void main() {
|
||||
expect(paths.first.routeWeight, closeTo(5.0, 0.001));
|
||||
});
|
||||
|
||||
test('ignores empty pathBytes', () async {
|
||||
test('ignores empty pathBytes for a multi-hop path', () async {
|
||||
final pubKey = _hex('fa04');
|
||||
await _seed(svc, pubKey, pathBytes: [0x01], hopCount: 1, weight: 1.0);
|
||||
|
||||
final pathsBefore = svc.getRecentPaths(pubKey);
|
||||
final weightBefore = pathsBefore.first.routeWeight;
|
||||
|
||||
// Hops without their bytes can't be replayed; only zero hops (the
|
||||
// direct path) may be recorded without bytes.
|
||||
svc.recordFloodPathAttribution(
|
||||
contactPubKeyHex: pubKey,
|
||||
pathBytes: [],
|
||||
hopCount: 0,
|
||||
hopCount: 2,
|
||||
successIncrement: 0.5,
|
||||
maxWeight: 5.0,
|
||||
);
|
||||
await _flush();
|
||||
|
||||
// Existing path should be untouched.
|
||||
// Existing path should be untouched and nothing new recorded.
|
||||
final pathsAfter = svc.getRecentPaths(pubKey);
|
||||
expect(pathsAfter, hasLength(1));
|
||||
expect(pathsAfter.first.routeWeight, equals(weightBefore));
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,257 @@
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/models/path_history.dart';
|
||||
import 'package:meshcore_open/models/path_selection.dart';
|
||||
import 'package:meshcore_open/services/path_history_service.dart';
|
||||
import 'package:meshcore_open/services/route_chooser.dart';
|
||||
|
||||
import 'path_history_service_test.dart' show FakeStorageService;
|
||||
|
||||
final _now = DateTime(2026, 11, 8, 12);
|
||||
|
||||
PathRecord _route(
|
||||
List<int> bytes, {
|
||||
double success = 0,
|
||||
double failure = 0,
|
||||
DateTime? statsAt,
|
||||
int tripTimeMs = 0,
|
||||
}) => PathRecord(
|
||||
hopCount: bytes.length,
|
||||
tripTimeMs: tripTimeMs,
|
||||
timestamp: null,
|
||||
wasFloodDiscovery: false,
|
||||
pathBytes: bytes,
|
||||
successCount: success.round(),
|
||||
failureCount: failure.round(),
|
||||
recentSuccess: success,
|
||||
recentFailure: failure,
|
||||
statsAt: statsAt ?? _now,
|
||||
);
|
||||
|
||||
Map<List<int>, int> _tally(
|
||||
List<PathRecord> routes, {
|
||||
int draws = 2000,
|
||||
RouteContext context = RouteContext.unknown,
|
||||
}) {
|
||||
final random = math.Random(42);
|
||||
final counts = {for (final r in routes) r.pathBytes: 0};
|
||||
for (var i = 0; i < draws; i++) {
|
||||
final pick = pickRoute(routes, random: random, now: _now, context: context);
|
||||
counts[pick.pathBytes] = counts[pick.pathBytes]! + 1;
|
||||
}
|
||||
return counts;
|
||||
}
|
||||
|
||||
RouteContext _hearing(Set<int> firstHops, {bool contactDirect = false}) =>
|
||||
RouteContext(
|
||||
hasNeighbourInfo: true,
|
||||
contactHeardDirectly: contactDirect,
|
||||
firstHopHeard: (bytes, width) =>
|
||||
bytes.isNotEmpty && firstHops.contains(bytes.first),
|
||||
);
|
||||
|
||||
void main() {
|
||||
group('fading', () {
|
||||
test('results lose half their weight per half-life', () {
|
||||
expect(routeDecayFactor(_now, _now), 1.0);
|
||||
expect(
|
||||
routeDecayFactor(_now.subtract(routeStatsHalfLife), _now),
|
||||
closeTo(0.5, 1e-9),
|
||||
);
|
||||
expect(
|
||||
routeDecayFactor(_now.subtract(routeStatsHalfLife * 3), _now),
|
||||
closeTo(0.125, 1e-9),
|
||||
);
|
||||
expect(routeDecayFactor(null, _now), 1.0);
|
||||
});
|
||||
|
||||
test('a new result is added on top of the faded old ones', () {
|
||||
final old = _route(
|
||||
[1],
|
||||
success: 4,
|
||||
failure: 2,
|
||||
statsAt: _now.subtract(routeStatsHalfLife),
|
||||
);
|
||||
final next = addRouteResult(old, success: false, now: _now);
|
||||
expect(next.success, closeTo(2, 1e-9));
|
||||
expect(next.failure, closeTo(2, 1e-9));
|
||||
});
|
||||
|
||||
test('a route proven long ago ranks below one working today', () {
|
||||
final stale = _route(
|
||||
[1],
|
||||
success: 20,
|
||||
statsAt: _now.subtract(const Duration(days: 10)),
|
||||
);
|
||||
final fresh = _route([2], success: 3);
|
||||
double score(PathRecord r) =>
|
||||
routeExpectedScore(r, now: _now, fastestTripMs: null);
|
||||
expect(score(fresh), greaterThan(score(stale)));
|
||||
});
|
||||
|
||||
test('history saved before fading existed seeds from capped counts', () {
|
||||
final legacy = PathRecord.fromJson({
|
||||
'hop_count': 1,
|
||||
'trip_time_ms': 0,
|
||||
'timestamp': _now.toIso8601String(),
|
||||
'was_flood': false,
|
||||
'path_bytes': [1],
|
||||
'success_count': 40,
|
||||
'failure_count': 1,
|
||||
});
|
||||
expect(legacy.recentSuccess, 5);
|
||||
expect(legacy.recentFailure, 1);
|
||||
expect(legacy.statsAt, _now);
|
||||
});
|
||||
});
|
||||
|
||||
group('sampling', () {
|
||||
test('Beta samples average a / (a + b)', () {
|
||||
final random = math.Random(7);
|
||||
for (final (a, b) in [(1.0, 1.0), (8.0, 2.0), (0.6, 3.5)]) {
|
||||
var sum = 0.0;
|
||||
const n = 6000;
|
||||
for (var i = 0; i < n; i++) {
|
||||
final x = sampleBeta(random, a, b);
|
||||
expect(x, inInclusiveRange(0, 1));
|
||||
sum += x;
|
||||
}
|
||||
expect(sum / n, closeTo(a / (a + b), 0.02), reason: 'Beta($a, $b)');
|
||||
}
|
||||
});
|
||||
|
||||
test('a proven route wins most picks but others still get tried', () {
|
||||
final strong = _route([1], success: 20, failure: 1);
|
||||
final weak = _route([2], success: 1, failure: 10);
|
||||
final unknown = _route([3]);
|
||||
final counts = _tally([strong, weak, unknown]);
|
||||
expect(counts[strong.pathBytes]!, greaterThan(1700));
|
||||
// Exploration: an untested route is still tried now and then.
|
||||
expect(counts[unknown.pathBytes]!, greaterThan(20));
|
||||
expect(counts[weak.pathBytes]!, lessThan(counts[unknown.pathBytes]!));
|
||||
});
|
||||
});
|
||||
|
||||
group('context', () {
|
||||
test('a route whose first hop is heard beats an equal one that is not', () {
|
||||
final viaA = _route([0xA0, 0x10], success: 3, failure: 1);
|
||||
final viaB = _route([0xB0, 0x10], success: 3, failure: 1);
|
||||
final counts = _tally([viaA, viaB], context: _hearing({0xA0}));
|
||||
expect(counts[viaA.pathBytes]!, greaterThan(1300));
|
||||
});
|
||||
|
||||
test('direct is preferred when the contact was heard directly', () {
|
||||
final direct = _route([], success: 3, failure: 1);
|
||||
final relayed = _route([0xA0], success: 3, failure: 1);
|
||||
final heard = _tally([
|
||||
direct,
|
||||
relayed,
|
||||
], context: _hearing({0xA0}, contactDirect: true));
|
||||
final notHeard = _tally([direct, relayed], context: _hearing({0xA0}));
|
||||
expect(
|
||||
heard[direct.pathBytes]!,
|
||||
greaterThan(notHeard[direct.pathBytes]!),
|
||||
);
|
||||
expect(notHeard[relayed.pathBytes]!, greaterThan(1000));
|
||||
});
|
||||
|
||||
test('with nothing heard, context changes nothing', () {
|
||||
final route = _route([0xA0], success: 1);
|
||||
expect(routeContextFactor(route, RouteContext.unknown), 1.0);
|
||||
});
|
||||
});
|
||||
|
||||
// A tiny simulated mesh: each route delivers with a fixed probability.
|
||||
// Each message gets up to [maxRetries] attempts, the last one a flood.
|
||||
group('simulation', () {
|
||||
late PathHistoryService svc;
|
||||
late DateTime clock;
|
||||
const contact =
|
||||
'00000000000000000000000000000000000000000000000000000000000000aa';
|
||||
const maxRetries = 4;
|
||||
|
||||
setUp(() async {
|
||||
clock = _now;
|
||||
svc = PathHistoryService(
|
||||
FakeStorageService(),
|
||||
random: math.Random(1),
|
||||
clock: () => clock,
|
||||
);
|
||||
svc.getRecentPaths(contact);
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
});
|
||||
|
||||
void seed(List<int> bytes) => svc.recordPathAttempt(
|
||||
contact,
|
||||
PathSelection(pathBytes: bytes, hopCount: bytes.length, useFlood: false),
|
||||
);
|
||||
|
||||
/// Sends [messages] messages; returns the average number of route
|
||||
/// attempts before delivery (flood counts as one more).
|
||||
double run(
|
||||
int messages,
|
||||
double Function(List<int> bytes) deliveryRate, {
|
||||
RouteContext context = RouteContext.unknown,
|
||||
math.Random? rng,
|
||||
}) {
|
||||
final random = rng ?? math.Random(99);
|
||||
var attempts = 0;
|
||||
for (var m = 0; m < messages; m++) {
|
||||
clock = clock.add(const Duration(minutes: 10));
|
||||
final used = <PathSelection>[];
|
||||
for (var attempt = 0; attempt < maxRetries; attempt++) {
|
||||
attempts++;
|
||||
final pick = svc.selectPathForAttempt(
|
||||
contact,
|
||||
attemptIndex: attempt,
|
||||
maxRetries: maxRetries,
|
||||
recentSelections: used,
|
||||
context: context,
|
||||
);
|
||||
if (pick.useFlood) break; // flood always gets through here
|
||||
final ok = random.nextDouble() < deliveryRate(pick.pathBytes);
|
||||
svc.recordPathResult(contact, pick, success: ok);
|
||||
if (ok) break;
|
||||
used.add(pick);
|
||||
}
|
||||
}
|
||||
return attempts / messages;
|
||||
}
|
||||
|
||||
test('settles on the reliable route', () {
|
||||
seed([0x01]);
|
||||
seed([0x02]);
|
||||
seed([0x03]);
|
||||
final rates = {0x01: 0.95, 0x02: 0.5, 0x03: 0.1};
|
||||
run(100, (b) => rates[b.first]!); // learn
|
||||
final avg = run(200, (b) => rates[b.first]!);
|
||||
expect(avg, lessThan(1.25));
|
||||
});
|
||||
|
||||
test('moves off a route that stops working', () {
|
||||
seed([0x01]);
|
||||
seed([0x02]);
|
||||
var rates = {0x01: 0.95, 0x02: 0.8};
|
||||
run(100, (b) => rates[b.first]!);
|
||||
// The best repeater goes offline.
|
||||
rates = {0x01: 0.0, 0x02: 0.8};
|
||||
run(10, (b) => rates[b.first]!); // a few messages to notice
|
||||
final avg = run(100, (b) => rates[b.first]!);
|
||||
expect(avg, lessThan(1.5));
|
||||
});
|
||||
|
||||
test('home and work routes follow what the radio hears', () {
|
||||
seed([0xA0, 0x10]); // via the home repeater
|
||||
seed([0xB0, 0x10]); // via the work repeater
|
||||
double homeRates(List<int> b) => b.first == 0xA0 ? 0.9 : 0.05;
|
||||
double workRates(List<int> b) => b.first == 0xB0 ? 0.9 : 0.05;
|
||||
|
||||
run(60, homeRates, context: _hearing({0xA0}));
|
||||
final atWork = run(60, workRates, context: _hearing({0xB0}));
|
||||
final backHome = run(60, homeRates, context: _hearing({0xA0}));
|
||||
expect(atWork, lessThan(1.6));
|
||||
expect(backHome, lessThan(1.6));
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/services/app_settings_service.dart';
|
||||
import 'package:meshcore_open/services/translation_service.dart';
|
||||
import 'package:meshcore_open/storage/prefs_manager.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
test('outgoing translation skips contact-share tokens', () async {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
await PrefsManager.initialize();
|
||||
final settings = AppSettingsService();
|
||||
await settings.loadSettings();
|
||||
await settings.setComposerTranslationEnabled(true);
|
||||
final translation = TranslationService(settings);
|
||||
const token =
|
||||
'<50ba28f599799142622d188469a63f3890d495cdcedd24239052abd364c0283d:1:CC>';
|
||||
|
||||
expect(
|
||||
translation.shouldTranslateOutgoing(
|
||||
text: token,
|
||||
targetLanguageCode: 'de',
|
||||
),
|
||||
isFalse,
|
||||
);
|
||||
expect(
|
||||
translation.shouldTranslateOutgoing(
|
||||
text: 'hello there',
|
||||
targetLanguageCode: 'de',
|
||||
),
|
||||
isTrue,
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -119,7 +119,8 @@ void main() {
|
||||
test('the archive follows the channel ID', () async {
|
||||
await _init();
|
||||
final store = ChannelMessageStore()..setPublicKeyHex = _deviceA;
|
||||
store.setArchived(_idOne, [_ch('old', 1), _ch('older', 2)]);
|
||||
await store.saveChannelMessages(_idOne, [_ch('old', 1), _ch('older', 2)]);
|
||||
store.setArchivedCount(_idOne, 2);
|
||||
expect(store.archivedCount(_idOne), 2);
|
||||
expect(store.archivedCount(_idTwo), isNull);
|
||||
|
||||
|
||||
@@ -0,0 +1,511 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/connector/meshcore_connector.dart';
|
||||
import 'package:meshcore_open/models/app_settings.dart';
|
||||
import 'dart:typed_data';
|
||||
import 'package:meshcore_open/models/channel.dart';
|
||||
import 'package:meshcore_open/storage/channel_storage_migration.dart';
|
||||
import 'package:meshcore_open/storage/channel_store.dart';
|
||||
import 'package:meshcore_open/services/app_settings_service.dart';
|
||||
import 'package:meshcore_open/services/backup_service.dart';
|
||||
import 'package:meshcore_open/review_mode/review_mode_storage.dart';
|
||||
import 'package:meshcore_open/review_mode/review_radio.dart';
|
||||
import 'package:meshcore_open/services/storage_service.dart';
|
||||
import 'package:meshcore_open/models/path_history.dart';
|
||||
import 'package:meshcore_open/storage/history_store.dart';
|
||||
import 'package:meshcore_open/storage/legacy_key_migration.dart';
|
||||
import 'package:meshcore_open/storage/history_store_io.dart';
|
||||
import 'package:meshcore_open/storage/prefs_manager.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.dart';
|
||||
import 'package:shared_preferences_platform_interface/types.dart';
|
||||
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
|
||||
|
||||
class _DelayedHistoryStore extends PreferencesHistoryStore {
|
||||
_DelayedHistoryStore(this.delayedKey, this.gate);
|
||||
final String delayedKey;
|
||||
final Completer<void> gate;
|
||||
@override
|
||||
Future<String?> getString(String key) async {
|
||||
if (key == delayedKey) await gate.future;
|
||||
return super.getString(key);
|
||||
}
|
||||
}
|
||||
|
||||
class _FailingCleanupPreferences extends InMemorySharedPreferencesStore {
|
||||
_FailingCleanupPreferences() : super.withData({'flutter.messages_a': '[1]'});
|
||||
bool fail = true;
|
||||
@override
|
||||
Future<bool> clearWithParameters(ClearParameters parameters) async =>
|
||||
fail ? false : super.clearWithParameters(parameters);
|
||||
}
|
||||
|
||||
class _BackupConnector extends MeshCoreConnector {
|
||||
_BackupConnector(this.radioKey);
|
||||
final String radioKey;
|
||||
@override
|
||||
bool get isConnected => true;
|
||||
@override
|
||||
String get selfPublicKeyHex => radioKey;
|
||||
}
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
late SqliteHistoryStore store;
|
||||
|
||||
setUp(() async {
|
||||
sqfliteFfiInit();
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
PrefsManager.reset();
|
||||
await PrefsManager.initialize();
|
||||
store = await SqliteHistoryStore.open(
|
||||
inMemoryDatabasePath,
|
||||
factory: databaseFactoryFfiNoIsolate,
|
||||
);
|
||||
HistoryStore.use(store);
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
await store.close();
|
||||
PrefsManager.reset();
|
||||
});
|
||||
|
||||
test('native history writes leave small preferences untouched', () async {
|
||||
await PrefsManager.instance.setString('theme', 'dark');
|
||||
await store.setString('messages_a', '[{"text":"hello"}]');
|
||||
await store.setString('path_history_a', '{"recentPaths":[]}');
|
||||
expect(PrefsManager.instance.getKeys(), {'theme'});
|
||||
expect(await store.getString('messages_a'), '[{"text":"hello"}]');
|
||||
expect(await store.getString('path_history_a'), '{"recentPaths":[]}');
|
||||
});
|
||||
|
||||
test('sequence reads return only the requested ordered page', () async {
|
||||
await store.setString(
|
||||
'channel_messages_a',
|
||||
jsonEncode([
|
||||
for (var i = 0; i < 1000; i++) {'id': i},
|
||||
]),
|
||||
);
|
||||
expect(await store.entryCount('channel_messages_a'), 1000);
|
||||
expect(
|
||||
await store.readEntries('channel_messages_a', offset: 950, limit: 3),
|
||||
['{"id":950}', '{"id":951}', '{"id":952}'],
|
||||
);
|
||||
expect(
|
||||
await store.readEntries('channel_messages_a', offset: 1000, limit: 3),
|
||||
isEmpty,
|
||||
);
|
||||
expect(await store.readEntries('channel_messages_a', limit: 0), isEmpty);
|
||||
});
|
||||
|
||||
test(
|
||||
'tail replacement preserves history, deletes and storage limits',
|
||||
() async {
|
||||
await store.setString('messages_a', '[0,1,2,3,4]');
|
||||
expect(
|
||||
await store.replaceTail('messages_a', 3, ['4', '5'], maxEntries: 4),
|
||||
2,
|
||||
);
|
||||
expect(await store.readEntries('messages_a'), ['1', '2', '4', '5']);
|
||||
expect(await store.replaceTail('messages_a', 2, ['6'], maxEntries: 4), 2);
|
||||
expect(await store.readEntries('messages_a'), ['1', '2', '6']);
|
||||
expect(
|
||||
await store.replaceTail('messages_a', 50, ['7'], maxEntries: 4),
|
||||
3,
|
||||
);
|
||||
expect(await store.readEntries('messages_a'), ['1', '2', '6', '7']);
|
||||
expect(await store.replaceTail('messages_a', 0, [], maxEntries: 4), 0);
|
||||
expect(await store.getString('messages_a'), '[]');
|
||||
},
|
||||
);
|
||||
|
||||
test('history data survives database reopen', () async {
|
||||
final dir = await Directory.systemTemp.createTemp('meshcore-history-test-');
|
||||
addTearDown(() => dir.delete(recursive: true));
|
||||
final path = '${dir.path}/history_v1.db';
|
||||
final disk = await SqliteHistoryStore.open(
|
||||
path,
|
||||
factory: databaseFactoryFfiNoIsolate,
|
||||
);
|
||||
await disk.setString('messages_a', '[1,2,3]');
|
||||
await disk.setString('path_history_a', '{"sample":true}');
|
||||
await disk.close();
|
||||
final reopened = await SqliteHistoryStore.open(
|
||||
path,
|
||||
factory: databaseFactoryFfiNoIsolate,
|
||||
);
|
||||
addTearDown(reopened.close);
|
||||
expect(await reopened.getString('messages_a'), '[1,2,3]');
|
||||
expect(await reopened.getString('path_history_a'), '{"sample":true}');
|
||||
});
|
||||
|
||||
test('versioned import removes only committed valid histories', () async {
|
||||
final prefs = PrefsManager.instance;
|
||||
await prefs.setString('messages_a', '[{"text":"hello"},42]');
|
||||
await prefs.setString('path_history_a', '{"recentPaths":[]}');
|
||||
await prefs.setString('messages_unreadable', '{broken');
|
||||
await prefs.setString('path_history_wrong_shape', '[]');
|
||||
await prefs.setBool('notification', true);
|
||||
await store.migratePreferences();
|
||||
expect(prefs.getKeys(), {
|
||||
'messages_unreadable',
|
||||
'path_history_wrong_shape',
|
||||
'notification',
|
||||
});
|
||||
expect(await store.readEntries('messages_a'), ['{"text":"hello"}', '42']);
|
||||
expect(await store.getString('messages_unreadable'), '{broken');
|
||||
expect(
|
||||
await store.getKeys(),
|
||||
containsAll(['messages_a', 'path_history_a', 'messages_unreadable']),
|
||||
);
|
||||
final metadata = await store.database.query('history_metadata');
|
||||
expect(metadata.single['value'], SqliteHistoryStore.schemaVersion);
|
||||
// Current versions skip another scan/import.
|
||||
await prefs.setString('messages_added_later', '[1]');
|
||||
await store.migratePreferences();
|
||||
expect(prefs.containsKey('messages_added_later'), isTrue);
|
||||
expect(
|
||||
await store.database.query(
|
||||
'history_keys',
|
||||
where: 'key = ?',
|
||||
whereArgs: ['messages_added_later'],
|
||||
),
|
||||
isEmpty,
|
||||
);
|
||||
});
|
||||
|
||||
test(
|
||||
'interrupted import does not replace committed newer database values',
|
||||
() async {
|
||||
await store.setString('messages_a', '[2]');
|
||||
await PrefsManager.instance.setString('messages_a', '[1]');
|
||||
await store.migratePreferences();
|
||||
expect(await store.getString('messages_a'), '[2]');
|
||||
expect(PrefsManager.instance.containsKey('messages_a'), isFalse);
|
||||
},
|
||||
);
|
||||
|
||||
test('histories saved by a run without the database are merged', () async {
|
||||
final prefs = PrefsManager.instance;
|
||||
await store.migratePreferences();
|
||||
await store.setString(
|
||||
'messages_a',
|
||||
'[{"messageId":"1","text":"old"},{"messageId":"2","text":"sent"}]',
|
||||
);
|
||||
await store.setString('path_history_a', '{"stored":true}');
|
||||
// What the fallback run saved: it started from an empty history.
|
||||
await prefs.setString(
|
||||
'messages_a',
|
||||
'[{"messageId":"2","text":"delivered"},{"messageId":"3","text":"new"}]',
|
||||
);
|
||||
await prefs.setString('messages_b', '[{"messageId":"4"}]');
|
||||
await prefs.setString('path_history_a', '{"stored":false}');
|
||||
await prefs.setString('messages_unreadable', '{broken');
|
||||
|
||||
await store.adoptFallbackHistories();
|
||||
|
||||
expect(await store.readEntries('messages_a'), [
|
||||
'{"messageId":"1","text":"old"}',
|
||||
'{"messageId":"2","text":"delivered"}',
|
||||
'{"messageId":"3","text":"new"}',
|
||||
]);
|
||||
expect(await store.readEntries('messages_b'), ['{"messageId":"4"}']);
|
||||
expect(await store.getString('path_history_a'), '{"stored":true}');
|
||||
expect(prefs.getKeys(), {'messages_unreadable'});
|
||||
});
|
||||
|
||||
test('initialize falls back to preferences and flags the run', () async {
|
||||
// No path provider is registered here, so the database cannot be opened.
|
||||
await HistoryStore.initialize();
|
||||
addTearDown(HistoryStore.reset);
|
||||
expect(HistoryStore.instance, isA<PreferencesHistoryStore>());
|
||||
expect(PrefsManager.instance.getBool(HistoryStore.fallbackRunKey), isTrue);
|
||||
});
|
||||
|
||||
test('a save lands beside an unreadable preference', () async {
|
||||
await PrefsManager.instance.setString('messages_a', '{broken');
|
||||
await store.migratePreferences();
|
||||
expect(await store.replaceTail('messages_a', 0, ['1', '2']), 0);
|
||||
expect(await store.readEntries('messages_a'), ['1', '2']);
|
||||
expect(await store.replaceTail('messages_a', 2, ['3']), 2);
|
||||
expect(await store.getString('messages_a'), '[1,2,3]');
|
||||
expect(PrefsManager.instance.getString('messages_a'), '{broken');
|
||||
});
|
||||
|
||||
test('the preferences store replaces an unreadable history', () async {
|
||||
final prefs = PreferencesHistoryStore();
|
||||
await PrefsManager.instance.setString('messages_a', '{broken');
|
||||
expect(await prefs.replaceTail('messages_a', 3, ['1', '2']), 0);
|
||||
expect(
|
||||
await prefs.replaceTail('messages_a', 2, ['3', '4'], maxEntries: 3),
|
||||
1,
|
||||
);
|
||||
expect(await prefs.getString('messages_a'), '[2,3,4]');
|
||||
// A value written behind the store's back is read fresh.
|
||||
await PrefsManager.instance.setString('messages_a', '[9]');
|
||||
expect(await prefs.readEntries('messages_a'), ['9']);
|
||||
expect(await prefs.entryCount('messages_a'), 1);
|
||||
});
|
||||
|
||||
test('future import versions are left untouched', () async {
|
||||
await store.database.insert('history_metadata', {
|
||||
'key': 'preferences_import_version',
|
||||
'value': 99,
|
||||
});
|
||||
await PrefsManager.instance.setString('messages_a', '[1]');
|
||||
await store.migratePreferences();
|
||||
expect(PrefsManager.instance.containsKey('messages_a'), isTrue);
|
||||
expect(
|
||||
(await store.database.query('history_metadata')).single['value'],
|
||||
99,
|
||||
);
|
||||
});
|
||||
|
||||
test('review cleanup removes only its database histories', () async {
|
||||
final prefix = ReviewRadio.storagePrefix;
|
||||
await store.setString('messages_${prefix}c1', '[1]');
|
||||
await store.setString('channel_messages_${prefix}_id', '[2]');
|
||||
await store.setString('messages_real_c1', '[3]');
|
||||
await clearReviewModeData();
|
||||
expect(await store.getKeys(), {'messages_real_c1'});
|
||||
});
|
||||
|
||||
test(
|
||||
'path history scoping and clearing work through database storage',
|
||||
() async {
|
||||
final a = StorageService()..setPublicKeyHex = 'aaaaaaaaaaaa';
|
||||
final b = StorageService()..setPublicKeyHex = 'bbbbbbbbbbbb';
|
||||
await store.setString(
|
||||
'path_history_c1',
|
||||
jsonEncode(
|
||||
ContactPathHistory(contactPubKeyHex: 'c1', recentPaths: []).toJson(),
|
||||
),
|
||||
);
|
||||
expect(await a.loadPathHistory('c1'), isNotNull);
|
||||
expect(await b.loadPathHistory('c1'), isNull);
|
||||
await b.savePathHistory(
|
||||
'c1',
|
||||
ContactPathHistory(contactPubKeyHex: 'c1', recentPaths: []),
|
||||
);
|
||||
await a.clearAllPathHistories();
|
||||
expect(await store.getKeys(), {'path_history_bbbbbbbbbb_c1'});
|
||||
},
|
||||
);
|
||||
test(
|
||||
'backup exports native histories and restores into the destination scope',
|
||||
() async {
|
||||
final source = _BackupConnector('a' * 64);
|
||||
final destination = _BackupConnector('b' * 64);
|
||||
final settings = AppSettingsService();
|
||||
addTearDown(source.dispose);
|
||||
addTearDown(destination.dispose);
|
||||
addTearDown(settings.dispose);
|
||||
await store.setString('messages_aaaaaaaaaac1', '[{"text":"original"}]');
|
||||
await store.setString(
|
||||
'channel_messages_aaaaaaaaaa_0123456789abcdef',
|
||||
'[{"text":"channel"}]',
|
||||
);
|
||||
const service = BackupService();
|
||||
final backup = await service.createBackup(
|
||||
items: {BackupItem.contactHistory, BackupItem.channelHistory},
|
||||
connector: source,
|
||||
settings: AppSettings(),
|
||||
password: '',
|
||||
);
|
||||
final decoded = jsonDecode(backup) as Map<String, dynamic>;
|
||||
final contacts = decoded['sections']['contacts']['preferences'] as Map;
|
||||
expect(contacts['messages_aaaaaaaaaac1'], [
|
||||
{'text': 'original'},
|
||||
]);
|
||||
await store.setString('messages_bbbbbbbbbbc1', '[{"text":"old"}]');
|
||||
await service.restoreBackup(
|
||||
contents: backup,
|
||||
password: '',
|
||||
items: {BackupItem.contactHistory, BackupItem.channelHistory},
|
||||
connector: destination,
|
||||
appSettingsService: settings,
|
||||
);
|
||||
expect(
|
||||
await store.getString('messages_bbbbbbbbbbc1'),
|
||||
'[{"text":"original"}]',
|
||||
);
|
||||
expect(
|
||||
await store.getString('channel_messages_bbbbbbbbbb_0123456789abcdef'),
|
||||
'[{"text":"channel"}]',
|
||||
);
|
||||
expect(
|
||||
await store.getString('messages_aaaaaaaaaac1'),
|
||||
'[{"text":"original"}]',
|
||||
);
|
||||
expect(
|
||||
PrefsManager.instance.getKeys().where(HistoryStore.isHistoryKey),
|
||||
isEmpty,
|
||||
);
|
||||
},
|
||||
);
|
||||
test(
|
||||
'failed preference cleanup leaves source and import version available for retry',
|
||||
() async {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
final platform = _FailingCleanupPreferences();
|
||||
SharedPreferencesStorePlatform.instance = platform;
|
||||
PrefsManager.reset();
|
||||
await PrefsManager.initialize();
|
||||
HistoryStore.use(store);
|
||||
await expectLater(store.migratePreferences(), throwsStateError);
|
||||
expect(PrefsManager.instance.getString('messages_a'), '[1]');
|
||||
expect(await store.getString('messages_a'), '[1]');
|
||||
expect(await store.database.query('history_metadata'), isEmpty);
|
||||
platform.fail = false;
|
||||
await store.migratePreferences();
|
||||
expect(PrefsManager.instance.containsKey('messages_a'), isFalse);
|
||||
expect(
|
||||
(await store.database.query('history_metadata')).single['value'],
|
||||
1,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'failed database import preserves original preferences and can retry',
|
||||
() async {
|
||||
await PrefsManager.instance.setString('messages_a', '[1]');
|
||||
await PrefsManager.instance.setString('messages_b', '[2]');
|
||||
await store.database.execute(
|
||||
"CREATE TRIGGER fail_history BEFORE INSERT ON history_entries WHEN NEW.key = 'messages_b' BEGIN SELECT RAISE(ABORT, 'test failure'); END",
|
||||
);
|
||||
await expectLater(
|
||||
store.migratePreferences(),
|
||||
throwsA(isA<DatabaseException>()),
|
||||
);
|
||||
expect(PrefsManager.instance.getString('messages_a'), '[1]');
|
||||
expect(PrefsManager.instance.getString('messages_b'), '[2]');
|
||||
expect(await store.database.query('history_metadata'), isEmpty);
|
||||
await store.database.execute('DROP TRIGGER fail_history');
|
||||
await store.migratePreferences();
|
||||
expect(await store.readEntries('messages_a'), ['1']);
|
||||
expect(await store.readEntries('messages_b'), ['2']);
|
||||
expect(PrefsManager.instance.getKeys(), isEmpty);
|
||||
},
|
||||
);
|
||||
test(
|
||||
'channel migration removes old database keys after committing the new ID',
|
||||
() async {
|
||||
const scope = 'aaaaaaaaaa';
|
||||
final channel = Channel(
|
||||
index: 0,
|
||||
name: 'Public',
|
||||
psk: Uint8List.fromList(List.filled(16, 1)),
|
||||
);
|
||||
await (ChannelStore()..setPublicKeyHex = '${scope}xx').saveChannels([
|
||||
channel,
|
||||
]);
|
||||
final oldKey = 'channel_messages_${scope}0';
|
||||
final newKey = 'channel_messages_${scope}_${channel.storageId}';
|
||||
await store.setString(oldKey, '[{"messageId":"legacy","text":"keep"}]');
|
||||
|
||||
await ChannelStorageMigration.migrate(scope);
|
||||
|
||||
expect(await store.getKeys(), {newKey});
|
||||
expect(
|
||||
await store.getString(newKey),
|
||||
'[{"messageId":"legacy","text":"keep"}]',
|
||||
);
|
||||
expect(
|
||||
PrefsManager.instance.getBool('channel_storage_v2_$scope'),
|
||||
isTrue,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'channel migration leaves malformed sources in place and still completes',
|
||||
() async {
|
||||
const scope = 'aaaaaaaaaa';
|
||||
final psk = Uint8List.fromList(List.filled(16, 1));
|
||||
final id = Channel.storageIdForPsk(psk)!;
|
||||
await PrefsManager.instance.setString(
|
||||
'channels$scope',
|
||||
jsonEncode([
|
||||
{
|
||||
'index': 0,
|
||||
'name': 'Public',
|
||||
'psk': base64Encode(psk),
|
||||
'unreadCount': 0,
|
||||
},
|
||||
]),
|
||||
);
|
||||
await PrefsManager.instance.setString(
|
||||
'channel_messages_${scope}0',
|
||||
'{broken',
|
||||
);
|
||||
await store.setString(
|
||||
'channel_messages_${scope}_$id',
|
||||
'[{"messageId":"existing","text":"keep"}]',
|
||||
);
|
||||
await ChannelStorageMigration.migrate(scope);
|
||||
expect(
|
||||
PrefsManager.instance.getString('channel_messages_${scope}0'),
|
||||
'{broken',
|
||||
);
|
||||
expect(
|
||||
await store.getString('channel_messages_${scope}_$id'),
|
||||
'[{"messageId":"existing","text":"keep"}]',
|
||||
);
|
||||
expect(
|
||||
PrefsManager.instance.getBool('channel_storage_v2_$scope'),
|
||||
isTrue,
|
||||
);
|
||||
// An array that cannot be merged safely is left alone as well.
|
||||
await PrefsManager.instance.remove('channel_storage_v2_$scope');
|
||||
await PrefsManager.instance.setString(
|
||||
'channel_messages_${scope}0',
|
||||
'[42]',
|
||||
);
|
||||
await ChannelStorageMigration.migrate(scope);
|
||||
expect(
|
||||
PrefsManager.instance.getString('channel_messages_${scope}0'),
|
||||
'[42]',
|
||||
);
|
||||
expect(
|
||||
await store.getString('channel_messages_${scope}_$id'),
|
||||
'[{"messageId":"existing","text":"keep"}]',
|
||||
);
|
||||
expect(
|
||||
PrefsManager.instance.getBool('channel_storage_v2_$scope'),
|
||||
isTrue,
|
||||
);
|
||||
},
|
||||
);
|
||||
test(
|
||||
'path migration keeps the original scope policy while reading asynchronously',
|
||||
() async {
|
||||
final reviewScope = ReviewRadio.storagePrefix;
|
||||
scopesWithoutLegacyMigration.add(reviewScope);
|
||||
addTearDown(() => scopesWithoutLegacyMigration.remove(reviewScope));
|
||||
await PrefsManager.instance.setString(
|
||||
'path_history_c1',
|
||||
jsonEncode(
|
||||
ContactPathHistory(contactPubKeyHex: 'c1', recentPaths: []).toJson(),
|
||||
),
|
||||
);
|
||||
final gate = Completer<void>();
|
||||
HistoryStore.use(
|
||||
_DelayedHistoryStore('path_history_${reviewScope}_c1', gate),
|
||||
);
|
||||
final service = StorageService()..setPublicKeyHex = '${reviewScope}xx';
|
||||
final pending = service.loadPathHistory('c1');
|
||||
service.setPublicKeyHex = 'bbbbbbbbbbbb';
|
||||
gate.complete();
|
||||
expect(await pending, isNull);
|
||||
expect(PrefsManager.instance.containsKey('path_history_c1'), isTrue);
|
||||
expect(
|
||||
PrefsManager.instance.containsKey('path_history_${reviewScope}_c1'),
|
||||
isFalse,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/storage/last_radio_store.dart';
|
||||
import 'package:meshcore_open/storage/prefs_manager.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
Future<void> _init([Map<String, Object> values = const {}]) async {
|
||||
SharedPreferences.setMockInitialValues(values);
|
||||
PrefsManager.reset();
|
||||
await PrefsManager.initialize();
|
||||
}
|
||||
|
||||
const _key = 'aabbccddeeff00112233445566778899aabbccddeeff00112233445566778899';
|
||||
|
||||
void main() {
|
||||
test('save and load round-trip a BLE radio', () async {
|
||||
await _init();
|
||||
final store = LastRadioStore();
|
||||
final saved = LastRadio(
|
||||
publicKeyHex: _key,
|
||||
name: 'Base',
|
||||
transport: LastRadio.transportBle,
|
||||
bleRemoteId: 'AA:BB:CC:DD:EE:FF',
|
||||
bleDisplayName: 'MeshCore-Base',
|
||||
savedAt: DateTime.fromMillisecondsSinceEpoch(1234),
|
||||
);
|
||||
await store.save(saved);
|
||||
|
||||
final loaded = store.load()!;
|
||||
expect(loaded.publicKeyHex, _key);
|
||||
expect(loaded.name, 'Base');
|
||||
expect(loaded.transport, LastRadio.transportBle);
|
||||
expect(loaded.bleRemoteId, 'AA:BB:CC:DD:EE:FF');
|
||||
expect(loaded.bleDisplayName, 'MeshCore-Base');
|
||||
expect(loaded.tcpHost, isNull);
|
||||
expect(loaded.savedAt.millisecondsSinceEpoch, 1234);
|
||||
expect(loaded.canReconnectBle, isTrue);
|
||||
expect(loaded.canReconnectTcp, isFalse);
|
||||
});
|
||||
|
||||
test('TCP radio keeps host and port', () async {
|
||||
await _init();
|
||||
final store = LastRadioStore();
|
||||
await store.save(
|
||||
LastRadio(
|
||||
publicKeyHex: _key,
|
||||
name: 'Roof',
|
||||
transport: LastRadio.transportTcp,
|
||||
tcpHost: '192.168.1.5',
|
||||
tcpPort: 5000,
|
||||
savedAt: DateTime.now(),
|
||||
),
|
||||
);
|
||||
final loaded = store.load()!;
|
||||
expect(loaded.tcpHost, '192.168.1.5');
|
||||
expect(loaded.tcpPort, 5000);
|
||||
expect(loaded.canReconnectTcp, isTrue);
|
||||
expect(loaded.canReconnectBle, isFalse);
|
||||
});
|
||||
|
||||
test('clear removes the record', () async {
|
||||
await _init();
|
||||
final store = LastRadioStore();
|
||||
await store.save(
|
||||
LastRadio(
|
||||
publicKeyHex: _key,
|
||||
name: 'x',
|
||||
transport: LastRadio.transportUsb,
|
||||
savedAt: DateTime.now(),
|
||||
),
|
||||
);
|
||||
await store.clear();
|
||||
expect(store.load(), isNull);
|
||||
});
|
||||
|
||||
test('tolerates missing, corrupt and partial records', () async {
|
||||
await _init();
|
||||
expect(LastRadioStore().load(), isNull);
|
||||
|
||||
await _init({LastRadioStore.prefsKey: '{not json'});
|
||||
expect(LastRadioStore().load(), isNull);
|
||||
|
||||
await _init({
|
||||
LastRadioStore.prefsKey: jsonEncode([1, 2, 3]),
|
||||
});
|
||||
expect(LastRadioStore().load(), isNull);
|
||||
|
||||
await _init({
|
||||
LastRadioStore.prefsKey: jsonEncode({'publicKeyHex': 'abc'}),
|
||||
});
|
||||
expect(LastRadioStore().load(), isNull);
|
||||
|
||||
await _init({
|
||||
LastRadioStore.prefsKey: jsonEncode({
|
||||
'publicKeyHex': _key,
|
||||
'transport': 'carrier-pigeon',
|
||||
'tcpPort': '80',
|
||||
'savedAt': 'yesterday',
|
||||
}),
|
||||
});
|
||||
final loaded = LastRadioStore().load()!;
|
||||
expect(loaded.publicKeyHex, _key);
|
||||
expect(loaded.name, '');
|
||||
expect(loaded.transport, LastRadio.transportBle);
|
||||
expect(loaded.tcpPort, isNull);
|
||||
expect(loaded.canReconnectBle, isFalse);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/models/channel.dart';
|
||||
import 'package:meshcore_open/storage/channel_storage_migration.dart';
|
||||
import 'package:meshcore_open/storage/channel_store.dart';
|
||||
import 'package:meshcore_open/storage/community_store.dart';
|
||||
import 'package:meshcore_open/storage/contact_discovery_store.dart';
|
||||
import 'package:meshcore_open/storage/contact_group_store.dart';
|
||||
import 'package:meshcore_open/storage/contact_settings_store.dart';
|
||||
import 'package:meshcore_open/storage/contact_store.dart';
|
||||
import 'package:meshcore_open/storage/legacy_key_migration.dart';
|
||||
import 'package:meshcore_open/storage/message_store.dart';
|
||||
import 'package:meshcore_open/storage/prefs_manager.dart';
|
||||
import 'package:meshcore_open/storage/unread_store.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.dart';
|
||||
|
||||
const _device = 'aaaaaaaaaa012345';
|
||||
const _scope = 'aaaaaaaaaa';
|
||||
|
||||
class _RecordingPreferences extends InMemorySharedPreferencesStore {
|
||||
_RecordingPreferences(Map<String, Object> values)
|
||||
: super.withData({
|
||||
for (final e in values.entries) 'flutter.${e.key}': e.value,
|
||||
});
|
||||
|
||||
final calls = <(String, String)>[];
|
||||
final failedKeys = <String>{};
|
||||
Completer<void>? writeGate;
|
||||
|
||||
@override
|
||||
Future<bool> setValue(String valueType, String key, Object value) async {
|
||||
calls.add(('set', key));
|
||||
if (failedKeys.contains(key)) return false;
|
||||
await writeGate?.future;
|
||||
return super.setValue(valueType, key, value);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<bool> remove(String key) async {
|
||||
calls.add(('remove', key));
|
||||
return super.remove(key);
|
||||
}
|
||||
}
|
||||
|
||||
Future<_RecordingPreferences> _init([
|
||||
Map<String, Object> values = const {},
|
||||
]) async {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
final platform = _RecordingPreferences(values);
|
||||
SharedPreferencesStorePlatform.instance = platform;
|
||||
PrefsManager.reset();
|
||||
await PrefsManager.initialize();
|
||||
return platform;
|
||||
}
|
||||
|
||||
String _cachedChannel(Uint8List psk) => jsonEncode([
|
||||
{'index': 0, 'name': 'Public', 'psk': base64Encode(psk), 'unreadCount': 0},
|
||||
]);
|
||||
|
||||
void main() {
|
||||
tearDown(() {
|
||||
scopesWithoutLegacyMigration.clear();
|
||||
PrefsManager.reset();
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
});
|
||||
|
||||
test('loading absent legacy data performs no platform writes', () async {
|
||||
final platform = await _init();
|
||||
await (MessageStore()..setPublicKeyHex = _device).loadMessages('c1');
|
||||
await (ContactSettingsStore()..setPublicKeyHex = _device).loadSmazEnabled(
|
||||
'c1',
|
||||
);
|
||||
await (ContactStore()..setPublicKeyHex = _device).loadContacts();
|
||||
await (ChannelStore()..setPublicKeyHex = _device).loadChannels();
|
||||
await (CommunityStore()..setPublicKeyHex = _device).loadCommunities();
|
||||
await (ContactGroupStore()..setPublicKeyHex = _device).loadGroups();
|
||||
await (UnreadStore()..setPublicKeyHex = _device).loadContactUnreadCount();
|
||||
await (ContactDiscoveryStore()..setPublicKeyHex = _device).loadContacts();
|
||||
expect(platform.calls, isEmpty);
|
||||
});
|
||||
|
||||
test(
|
||||
'string migration waits for persistence before deleting the source',
|
||||
() async {
|
||||
final platform = await _init({'messages_c1': '[]'});
|
||||
final gate = Completer<void>();
|
||||
platform.writeGate = gate;
|
||||
final pending = (MessageStore()..setPublicKeyHex = _device).loadMessages(
|
||||
'c1',
|
||||
);
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
expect(platform.calls, [('set', 'flutter.messages_${_scope}c1')]);
|
||||
expect((await platform.getAll())['flutter.messages_c1'], '[]');
|
||||
gate.complete();
|
||||
await pending;
|
||||
expect(platform.calls, [
|
||||
('set', 'flutter.messages_${_scope}c1'),
|
||||
('remove', 'flutter.messages_c1'),
|
||||
]);
|
||||
await (MessageStore()..setPublicKeyHex = _device).loadMessages('c1');
|
||||
expect(platform.calls, hasLength(2));
|
||||
},
|
||||
);
|
||||
|
||||
test('a failed string migration retains persisted legacy data', () async {
|
||||
final platform = await _init({'messages_c1': '[]'});
|
||||
platform.failedKeys.add('flutter.messages_${_scope}c1');
|
||||
await (MessageStore()..setPublicKeyHex = _device).loadMessages('c1');
|
||||
expect(platform.calls, [('set', 'flutter.messages_${_scope}c1')]);
|
||||
final persisted = await platform.getAll();
|
||||
expect(persisted['flutter.messages_c1'], '[]');
|
||||
expect(persisted, isNot(contains('flutter.messages_${_scope}c1')));
|
||||
});
|
||||
|
||||
test(
|
||||
'false legacy settings migrate, but stay persisted when writing fails',
|
||||
() async {
|
||||
final platform = await _init({'contact_smaz_c1': false});
|
||||
platform.failedKeys.add('flutter.contact_smaz_${_scope}c1');
|
||||
expect(
|
||||
await (ContactSettingsStore()..setPublicKeyHex = _device)
|
||||
.loadSmazEnabled('c1'),
|
||||
isFalse,
|
||||
);
|
||||
expect(platform.calls, [('set', 'flutter.contact_smaz_${_scope}c1')]);
|
||||
expect((await platform.getAll())['flutter.contact_smaz_c1'], isFalse);
|
||||
},
|
||||
);
|
||||
|
||||
test('review scopes never adopt legacy strings or settings', () async {
|
||||
final platform = await _init({
|
||||
'messages_c1': '[]',
|
||||
'contact_smaz_c1': true,
|
||||
});
|
||||
scopesWithoutLegacyMigration.add(_scope);
|
||||
expect(
|
||||
await (MessageStore()..setPublicKeyHex = _device).loadMessages('c1'),
|
||||
isEmpty,
|
||||
);
|
||||
expect(
|
||||
await (ContactSettingsStore()..setPublicKeyHex = _device).loadSmazEnabled(
|
||||
'c1',
|
||||
),
|
||||
isFalse,
|
||||
);
|
||||
expect(platform.calls, isEmpty);
|
||||
});
|
||||
|
||||
test('channel migration skips removals of absent old keys', () async {
|
||||
final psk = Uint8List.fromList(List.filled(16, 1));
|
||||
final platform = await _init({'channels$_scope': _cachedChannel(psk)});
|
||||
await ChannelStorageMigration.migrate(_scope);
|
||||
expect(platform.calls.where((c) => c.$1 == 'remove'), isEmpty);
|
||||
expect(PrefsManager.instance.getBool('channel_storage_v2_$_scope'), isTrue);
|
||||
});
|
||||
|
||||
test(
|
||||
'channel migration keeps sources and stays unfinished when a write fails',
|
||||
() async {
|
||||
final psk = Uint8List.fromList(List.filled(16, 1));
|
||||
final id = Channel.storageIdForPsk(psk)!;
|
||||
final sourceKey = 'channel_messages_${_scope}0';
|
||||
final platform = await _init({
|
||||
'channels$_scope': _cachedChannel(psk),
|
||||
sourceKey: '[]',
|
||||
});
|
||||
platform.failedKeys.add('flutter.channel_messages_${_scope}_$id');
|
||||
await expectLater(
|
||||
ChannelStorageMigration.migrate(_scope),
|
||||
throwsStateError,
|
||||
);
|
||||
expect((await platform.getAll())['flutter.$sourceKey'], '[]');
|
||||
expect(
|
||||
PrefsManager.instance.getBool('channel_storage_v2_$_scope'),
|
||||
isNull,
|
||||
);
|
||||
expect(platform.calls.where((c) => c.$1 == 'remove'), isEmpty);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'false legacy settings migrate successfully without extra writes',
|
||||
() async {
|
||||
final platform = await _init({'contact_smaz_c1': false});
|
||||
final store = ContactSettingsStore()..setPublicKeyHex = _device;
|
||||
expect(await store.loadSmazEnabled('c1'), isFalse);
|
||||
expect(await store.loadSmazEnabled('c1'), isFalse);
|
||||
expect(platform.calls, [
|
||||
('set', 'flutter.contact_smaz_${_scope}c1'),
|
||||
('remove', 'flutter.contact_smaz_c1'),
|
||||
]);
|
||||
final persisted = await platform.getAll();
|
||||
expect(persisted['flutter.contact_smaz_${_scope}c1'], isFalse);
|
||||
expect(persisted, isNot(contains('flutter.contact_smaz_c1')));
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'channel migration is not marked done before its slot map is durable',
|
||||
() async {
|
||||
final psk = Uint8List.fromList(List.filled(16, 1));
|
||||
final platform = await _init({'channels$_scope': _cachedChannel(psk)});
|
||||
platform.failedKeys.add('flutter.channel_slot_ids_$_scope');
|
||||
await expectLater(
|
||||
ChannelStorageMigration.migrate(_scope),
|
||||
throwsStateError,
|
||||
);
|
||||
expect(
|
||||
PrefsManager.instance.getBool('channel_storage_v2_$_scope'),
|
||||
isNull,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/models/channel_message.dart';
|
||||
import 'package:meshcore_open/models/message.dart';
|
||||
import 'package:meshcore_open/storage/channel_message_store.dart';
|
||||
import 'package:meshcore_open/storage/history_store.dart';
|
||||
import 'package:meshcore_open/storage/message_store.dart';
|
||||
|
||||
const _device = 'abcdef012345';
|
||||
const _contact = 'contact';
|
||||
const _channel = 'channel';
|
||||
|
||||
class _History extends HistoryStore {
|
||||
final data = <String, List<String>>{};
|
||||
int reads = 0;
|
||||
bool failNextWrite = false;
|
||||
bool failNextRemove = false;
|
||||
Completer<void>? nextWriteGate;
|
||||
Completer<void>? nextWriteStarted;
|
||||
|
||||
@override
|
||||
Future<String?> getString(String key) async {
|
||||
reads++;
|
||||
final entries = data[key];
|
||||
return entries == null ? null : '[${entries.join(',')}]';
|
||||
}
|
||||
|
||||
@override
|
||||
Future<bool> setString(String key, String value) async {
|
||||
data[key] = (jsonDecode(value) as List).map(jsonEncode).toList();
|
||||
return true;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<bool> remove(String key) async {
|
||||
if (failNextRemove) {
|
||||
failNextRemove = false;
|
||||
return false;
|
||||
}
|
||||
data.remove(key);
|
||||
return true;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Set<String>> getKeys() async => data.keys.toSet();
|
||||
|
||||
@override
|
||||
Future<int> entryCount(String key) async => data[key]?.length ?? 0;
|
||||
|
||||
@override
|
||||
Future<List<String>> readEntries(
|
||||
String key, {
|
||||
int offset = 0,
|
||||
int? limit,
|
||||
}) async {
|
||||
reads++;
|
||||
final entries = (data[key] ?? []).skip(offset);
|
||||
return (limit == null ? entries : entries.take(limit)).toList();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<int> replaceTail(
|
||||
String key,
|
||||
int preservedCount,
|
||||
List<String> entries, {
|
||||
int maxEntries = 1000,
|
||||
}) async {
|
||||
final gate = nextWriteGate;
|
||||
nextWriteGate = null;
|
||||
nextWriteStarted?.complete();
|
||||
nextWriteStarted = null;
|
||||
await gate?.future;
|
||||
if (failNextWrite) {
|
||||
failNextWrite = false;
|
||||
throw StateError('Disk unavailable');
|
||||
}
|
||||
final prefix = (data[key] ?? []).take(preservedCount).toList();
|
||||
final all = [...prefix, ...entries];
|
||||
final dropped = (all.length - maxEntries).clamp(0, all.length);
|
||||
data[key] = all.skip(dropped).toList();
|
||||
return (prefix.length - dropped).clamp(0, prefix.length);
|
||||
}
|
||||
|
||||
List<String> texts(String key) => [
|
||||
for (final entry in data[key] ?? [])
|
||||
(jsonDecode(entry) as Map)['text'] as String,
|
||||
];
|
||||
}
|
||||
|
||||
Message _dm(int i, {String? id, String? text}) => Message(
|
||||
senderKey: Uint8List.fromList([1, 2, 3]),
|
||||
text: text ?? 'm$i',
|
||||
timestamp: DateTime.fromMillisecondsSinceEpoch(1000 * i),
|
||||
isOutgoing: false,
|
||||
messageId: id ?? 'id$i',
|
||||
);
|
||||
|
||||
ChannelMessage _ch(int i) => ChannelMessage(
|
||||
senderKey: null,
|
||||
senderName: 'Bob',
|
||||
text: 'c$i',
|
||||
timestamp: DateTime.fromMillisecondsSinceEpoch(1000 * i),
|
||||
isOutgoing: false,
|
||||
status: ChannelMessageStatus.sent,
|
||||
channelIndex: 0,
|
||||
messageId: 'cid$i',
|
||||
);
|
||||
|
||||
void main() {
|
||||
late _History history;
|
||||
late MessageStore direct;
|
||||
late ChannelMessageStore channel;
|
||||
late String directKey;
|
||||
late String channelKey;
|
||||
|
||||
setUp(() {
|
||||
history = _History();
|
||||
HistoryStore.use(history);
|
||||
direct = MessageStore()..setPublicKeyHex = _device;
|
||||
channel = ChannelMessageStore()..setPublicKeyHex = _device;
|
||||
directKey = '${direct.keyFor}$_contact';
|
||||
channelKey = '${channel.keyFor}_$_channel';
|
||||
});
|
||||
|
||||
tearDown(HistoryStore.reset);
|
||||
|
||||
test(
|
||||
'reconciled saves preserve prefixes without reading archived JSON',
|
||||
() async {
|
||||
await direct.saveMessages(_contact, [for (var i = 0; i < 8; i++) _dm(i)]);
|
||||
await channel.saveChannelMessages(_channel, [
|
||||
for (var i = 0; i < 8; i++) _ch(i),
|
||||
]);
|
||||
direct.setArchivedCount(_contact, 6);
|
||||
channel.setArchivedCount(_channel, 6);
|
||||
history.reads = 0;
|
||||
|
||||
await direct.saveMessages(_contact, [_dm(6), _dm(8)]);
|
||||
await channel.saveChannelMessages(_channel, [_ch(6), _ch(8)]);
|
||||
|
||||
expect(history.reads, 0);
|
||||
expect(history.texts(directKey), [
|
||||
for (var i = 0; i <= 6; i++) 'm$i',
|
||||
'm8',
|
||||
]);
|
||||
expect(history.texts(channelKey), [
|
||||
for (var i = 0; i <= 6; i++) 'c$i',
|
||||
'c8',
|
||||
]);
|
||||
},
|
||||
);
|
||||
|
||||
test('overlapping saves consume each unsaved trim once', () async {
|
||||
direct.setArchivedCount(_contact, 0);
|
||||
await direct.saveMessages(_contact, [_dm(0), _dm(1), _dm(2)]);
|
||||
direct.archive(_contact, [_dm(0)]);
|
||||
final gate = Completer<void>();
|
||||
final started = Completer<void>();
|
||||
history.nextWriteGate = gate;
|
||||
history.nextWriteStarted = started;
|
||||
final first = direct.saveMessages(_contact, [_dm(1), _dm(2), _dm(3)]);
|
||||
await started.future;
|
||||
|
||||
direct.archive(_contact, [_dm(1)]);
|
||||
final second = direct.saveMessages(_contact, [_dm(2), _dm(3), _dm(4)]);
|
||||
gate.complete();
|
||||
await Future.wait([first, second]);
|
||||
|
||||
expect(history.texts(directKey), [for (var i = 0; i <= 4; i++) 'm$i']);
|
||||
expect(direct.archivedCount(_contact), 2);
|
||||
});
|
||||
|
||||
test('failed writes retain unsaved trims for retry', () async {
|
||||
direct.setArchivedCount(_contact, 0);
|
||||
await direct.saveMessages(_contact, [_dm(0), _dm(1)]);
|
||||
direct.archive(_contact, [_dm(0)]);
|
||||
history.failNextWrite = true;
|
||||
await expectLater(
|
||||
direct.saveMessages(_contact, [_dm(1), _dm(2)]),
|
||||
throwsStateError,
|
||||
);
|
||||
expect(direct.archivedCount(_contact), 1);
|
||||
expect(history.texts(directKey), ['m0', 'm1']);
|
||||
|
||||
await direct.saveMessages(_contact, [_dm(1), _dm(2)]);
|
||||
expect(history.texts(directKey), ['m0', 'm1', 'm2']);
|
||||
expect(direct.archivedCount(_contact), 1);
|
||||
});
|
||||
|
||||
test(
|
||||
'queued snapshots survive scope switches without restoring old bookkeeping',
|
||||
() async {
|
||||
direct.setArchivedCount(_contact, 0);
|
||||
final messages = [_dm(0)];
|
||||
final gate = Completer<void>();
|
||||
final started = Completer<void>();
|
||||
history.nextWriteGate = gate;
|
||||
history.nextWriteStarted = started;
|
||||
final pending = direct.saveMessages(_contact, messages);
|
||||
await started.future;
|
||||
messages.clear();
|
||||
direct.forgetArchive();
|
||||
direct.setPublicKeyHex = '0123456789abcd';
|
||||
final newKey = '${direct.keyFor}$_contact';
|
||||
await direct.saveMessages(_contact, [_dm(1)]);
|
||||
gate.complete();
|
||||
await pending;
|
||||
|
||||
expect(history.texts(directKey), ['m0']);
|
||||
expect(history.texts(newKey), ['m1']);
|
||||
direct.setPublicKeyHex = _device;
|
||||
expect(direct.archivedCount(_contact), isNull);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'a clear through another instance is ordered after in-flight saves',
|
||||
() async {
|
||||
channel.setArchivedCount(_channel, 0);
|
||||
final gate = Completer<void>();
|
||||
final started = Completer<void>();
|
||||
history.nextWriteGate = gate;
|
||||
history.nextWriteStarted = started;
|
||||
final save = channel.saveChannelMessages(_channel, [_ch(0)]);
|
||||
await started.future;
|
||||
final clear = (ChannelMessageStore()..setPublicKeyHex = _device)
|
||||
.clearChannelMessages(_channel);
|
||||
final laterSave = channel.saveChannelMessages(_channel, [_ch(1)]);
|
||||
gate.complete();
|
||||
await Future.wait([save, clear, laterSave]);
|
||||
|
||||
expect(history.texts(channelKey), ['c1']);
|
||||
expect(channel.archivedCount(_channel), 0);
|
||||
},
|
||||
);
|
||||
|
||||
test('cap reductions remain correct across queued saves', () async {
|
||||
const cap = MessageStore.maxStoredMessages;
|
||||
await direct.saveMessages(_contact, [for (var i = 0; i < cap; i++) _dm(i)]);
|
||||
direct.setArchivedCount(_contact, cap - 2);
|
||||
final first = direct.saveMessages(_contact, [
|
||||
_dm(cap - 2),
|
||||
_dm(cap - 1),
|
||||
_dm(cap),
|
||||
]);
|
||||
final second = direct.saveMessages(_contact, [
|
||||
_dm(cap - 2),
|
||||
_dm(cap - 1),
|
||||
_dm(cap),
|
||||
_dm(cap + 1),
|
||||
]);
|
||||
await Future.wait([first, second]);
|
||||
|
||||
expect(history.texts(directKey).first, 'm2');
|
||||
expect(history.texts(directKey).last, 'm${cap + 1}');
|
||||
expect(history.data[directKey], hasLength(cap));
|
||||
expect(direct.archivedCount(_contact), cap - 4);
|
||||
});
|
||||
|
||||
test(
|
||||
'unreconciled merge preserves distinct duplicates without message IDs',
|
||||
() async {
|
||||
final duplicate = _dm(0, id: '', text: 'same');
|
||||
await direct.saveMessages(_contact, [duplicate, duplicate]);
|
||||
direct.forgetArchive();
|
||||
await direct.saveMessages(_contact, [duplicate, _dm(1)]);
|
||||
expect(history.texts(directKey), ['same', 'same', 'm1']);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'backend replacement cannot reuse another backend archive counts',
|
||||
() async {
|
||||
direct.setArchivedCount(_contact, 100);
|
||||
final replacement = _History();
|
||||
HistoryStore.use(replacement);
|
||||
expect(direct.archivedCount(_contact), isNull);
|
||||
await direct.saveMessages(_contact, [_dm(0)]);
|
||||
expect(replacement.texts(directKey), ['m0']);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -55,7 +55,7 @@ void main() {
|
||||
|
||||
final loaded = await store.loadMessages(_contact);
|
||||
final window = loaded.sublist(6);
|
||||
store.setArchived(_contact, loaded.sublist(0, 6));
|
||||
store.setArchivedCount(_contact, 6);
|
||||
await store.saveMessages(_contact, [...window, _dm(10)]);
|
||||
|
||||
final reloaded = await store.loadMessages(_contact);
|
||||
@@ -67,7 +67,7 @@ void main() {
|
||||
test('trimmed messages are archived, deletes stay deleted', () async {
|
||||
await _init();
|
||||
final store = _messageStore();
|
||||
store.setArchived(_contact, const []);
|
||||
store.setArchivedCount(_contact, 0);
|
||||
final window = [for (var i = 0; i < 4; i++) _dm(i)];
|
||||
await store.saveMessages(_contact, window);
|
||||
|
||||
@@ -79,9 +79,23 @@ void main() {
|
||||
final reloaded = await store.loadMessages(_contact);
|
||||
expect(reloaded.map((m) => m.text), ['m0', 'm1', 'm3', 'm4']);
|
||||
expect(store.archivedCount(_contact), 2);
|
||||
});
|
||||
|
||||
store.unarchiveNewest(_contact, 1);
|
||||
expect(store.archivedCount(_contact), 1);
|
||||
test('an unreadable stored history does not block later saves', () async {
|
||||
await _init();
|
||||
final store = _messageStore();
|
||||
final key = '${store.keyFor}$_contact';
|
||||
await PrefsManager.instance.setString(key, '{broken');
|
||||
|
||||
// Unreconciled: nothing was loaded before the first save.
|
||||
await store.saveMessages(_contact, [_dm(0)]);
|
||||
expect((await store.loadMessages(_contact)).map((m) => m.text), ['m0']);
|
||||
|
||||
// Reconciled to zero by a load that found nothing readable.
|
||||
await PrefsManager.instance.setString(key, '{broken');
|
||||
store.setArchivedCount(_contact, 0);
|
||||
await store.saveMessages(_contact, [_dm(1)]);
|
||||
expect((await store.loadMessages(_contact)).map((m) => m.text), ['m1']);
|
||||
});
|
||||
|
||||
test('an unreconciled save merges with what is stored', () async {
|
||||
@@ -100,8 +114,8 @@ void main() {
|
||||
test('clearMessages wipes archived history too', () async {
|
||||
await _init();
|
||||
final store = _messageStore();
|
||||
store.setArchived(_contact, [_dm(0), _dm(1)]);
|
||||
await store.saveMessages(_contact, [_dm(2)]);
|
||||
await store.saveMessages(_contact, [_dm(0), _dm(1), _dm(2)]);
|
||||
store.setArchivedCount(_contact, 2);
|
||||
|
||||
await store.clearMessages(_contact);
|
||||
await store.saveMessages(_contact, [_dm(3)]);
|
||||
@@ -114,7 +128,10 @@ void main() {
|
||||
await _init();
|
||||
final store = _messageStore();
|
||||
const cap = MessageStore.maxStoredMessages;
|
||||
store.setArchived(_contact, [for (var i = 0; i < cap; i++) _dm(i)]);
|
||||
await store.saveMessages(_contact, [
|
||||
for (var i = 0; i < cap; i++) _dm(i),
|
||||
]);
|
||||
store.setArchivedCount(_contact, cap);
|
||||
await store.saveMessages(_contact, [_dm(cap), _dm(cap + 1)]);
|
||||
|
||||
final reloaded = await store.loadMessages(_contact);
|
||||
@@ -184,7 +201,7 @@ void main() {
|
||||
await store.saveChannelMessages(_channelId, all);
|
||||
|
||||
final loaded = await store.loadChannelMessages(_channelId);
|
||||
store.setArchived(_channelId, loaded.sublist(0, 5));
|
||||
store.setArchivedCount(_channelId, 5);
|
||||
await store.saveChannelMessages(_channelId, [
|
||||
...loaded.sublist(5),
|
||||
_ch(8),
|
||||
@@ -197,8 +214,8 @@ void main() {
|
||||
test('clearing through another instance resets the archive', () async {
|
||||
await _init();
|
||||
final store = ChannelMessageStore()..setPublicKeyHex = _device;
|
||||
store.setArchived(_channelId, [_ch(0), _ch(1)]);
|
||||
await store.saveChannelMessages(_channelId, [_ch(2)]);
|
||||
await store.saveChannelMessages(_channelId, [_ch(0), _ch(1), _ch(2)]);
|
||||
store.setArchivedCount(_channelId, 2);
|
||||
|
||||
await (ChannelMessageStore()..setPublicKeyHex = _device)
|
||||
.clearChannelMessages(_channelId);
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/utils/coalesced_writes.dart';
|
||||
|
||||
@@ -63,4 +65,44 @@ void main() {
|
||||
await writes.flush();
|
||||
expect(ran, isTrue);
|
||||
});
|
||||
|
||||
test('flush waits for writes already started by the timer', () async {
|
||||
final writes = CoalescedWrites(delay: Duration.zero);
|
||||
final started = Completer<void>();
|
||||
final persisted = Completer<void>();
|
||||
writes.schedule('history', () {
|
||||
started.complete();
|
||||
return persisted.future;
|
||||
});
|
||||
await started.future;
|
||||
|
||||
var finished = false;
|
||||
final flush = writes.flush().then((_) => finished = true);
|
||||
await _wait(0);
|
||||
expect(finished, isFalse);
|
||||
persisted.complete();
|
||||
await flush;
|
||||
expect(finished, isTrue);
|
||||
});
|
||||
|
||||
test(
|
||||
'a later flush waits for both existing and newly queued writes',
|
||||
() async {
|
||||
final writes = CoalescedWrites();
|
||||
final first = Completer<void>();
|
||||
final second = Completer<void>();
|
||||
writes.schedule('first', () => first.future);
|
||||
final firstFlush = writes.flush();
|
||||
writes.schedule('second', () => second.future);
|
||||
var finished = false;
|
||||
final secondFlush = writes.flush().then((_) => finished = true);
|
||||
|
||||
second.complete();
|
||||
await _wait(0);
|
||||
expect(finished, isFalse);
|
||||
first.complete();
|
||||
await Future.wait([firstFlush, secondFlush]);
|
||||
expect(finished, isTrue);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/widgets/mesh_ui.dart';
|
||||
|
||||
Widget _segments(double width, List<String> labels) {
|
||||
return MaterialApp(
|
||||
home: Scaffold(
|
||||
body: Center(
|
||||
child: SizedBox(
|
||||
width: width,
|
||||
child: SegmentedButton<int>(
|
||||
showSelectedIcon: false,
|
||||
segments: [
|
||||
for (var i = 0; i < labels.length; i++)
|
||||
ButtonSegment(value: i, label: MeshSegmentLabel(labels[i])),
|
||||
],
|
||||
selected: const {0},
|
||||
onSelectionChanged: (_) {},
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void main() {
|
||||
testWidgets('short labels lay out on one line at full size', (tester) async {
|
||||
await tester.pumpWidget(_segments(360, ['Auto', 'Flood', 'Manual']));
|
||||
expect(tester.takeException(), isNull);
|
||||
expect(find.bySemanticsLabel('Flood'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('long labels in narrow segments do not overflow', (tester) async {
|
||||
await tester.pumpWidget(
|
||||
_segments(240, [
|
||||
'Padrão do sistema',
|
||||
'Inundação',
|
||||
'Automatisch',
|
||||
'Manual',
|
||||
]),
|
||||
);
|
||||
expect(tester.takeException(), isNull);
|
||||
final labels = find.byType(MeshSegmentLabel);
|
||||
final multi = tester.getSize(labels.at(0));
|
||||
final longWord = tester.getSize(labels.at(1));
|
||||
final single = tester.getSize(labels.at(3));
|
||||
// The multi-word label wraps at its space instead of shrinking further;
|
||||
// a single long word stays on one line.
|
||||
expect(multi.height, greaterThan(single.height));
|
||||
expect(longWord.height, lessThanOrEqualTo(single.height));
|
||||
for (var i = 0; i < 4; i++) {
|
||||
final box = tester.renderObject<RenderBox>(labels.at(i));
|
||||
final parent = box.parent! as RenderBox;
|
||||
expect(box.size.width, lessThanOrEqualTo(parent.size.width));
|
||||
}
|
||||
});
|
||||
|
||||
testWidgets('a colour-only style change reaches the painted text', (
|
||||
tester,
|
||||
) async {
|
||||
Widget label(Color color) => MaterialApp(
|
||||
home: Center(
|
||||
child: DefaultTextStyle(
|
||||
style: TextStyle(fontSize: 14, color: color),
|
||||
child: const MeshSegmentLabel('Flood'),
|
||||
),
|
||||
),
|
||||
);
|
||||
Color? painted() =>
|
||||
(tester.renderObject(find.byType(MeshSegmentLabel)) as dynamic)
|
||||
.debugPaintedColor
|
||||
as Color?;
|
||||
|
||||
await tester.pumpWidget(label(const Color(0xFF112233)));
|
||||
expect(painted(), const Color(0xFF112233));
|
||||
await tester.pumpWidget(label(const Color(0xFFEEDDCC)));
|
||||
expect(painted(), const Color(0xFFEEDDCC));
|
||||
});
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/l10n/app_localizations.dart';
|
||||
import 'package:meshcore_open/models/image_codec_support.dart';
|
||||
import 'package:meshcore_open/services/image_chunk_transport.dart';
|
||||
import 'package:meshcore_open/widgets/image_send_codec_binding.dart';
|
||||
@@ -81,6 +82,8 @@ Future<void> _pumpBubble(
|
||||
}) async {
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
home: Scaffold(
|
||||
body: ReceivedImageMessage(
|
||||
streamId: streamId,
|
||||
@@ -112,6 +115,8 @@ void main() {
|
||||
);
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
home: Scaffold(
|
||||
body: ReceivedImageMessage(
|
||||
streamId: entry.streamId,
|
||||
@@ -146,6 +151,8 @@ void main() {
|
||||
await store2.load();
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
home: Scaffold(
|
||||
body: ReceivedImageMessage(
|
||||
streamId: 'incoming',
|
||||
@@ -159,7 +166,7 @@ void main() {
|
||||
await tester.pump();
|
||||
await tester.pump();
|
||||
expect(find.text('AI-reconstructed'), findsOneWidget);
|
||||
expect(find.textContaining('Fine detail is generated'), findsOneWidget);
|
||||
expect(find.textContaining('fine detail is generated'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('receiving state shows the packet count', (tester) async {
|
||||
@@ -178,6 +185,8 @@ void main() {
|
||||
expect(entry!.state, ReceivedImageState.receiving);
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
home: Scaffold(
|
||||
body: ReceivedImageMessage(
|
||||
streamId: entry.streamId,
|
||||
@@ -215,6 +224,8 @@ void main() {
|
||||
final store = await _awaitingStore(bytes: 209, packets: 3);
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
home: Scaffold(
|
||||
body: ReceivedImageMessage(
|
||||
streamId: 'await1',
|
||||
@@ -412,8 +423,8 @@ void main() {
|
||||
await tester.pump();
|
||||
|
||||
expect(find.text('AI-reconstructed'), findsOneWidget);
|
||||
expect(find.textContaining('Reconstructed by an AI model'), findsOneWidget);
|
||||
expect(find.textContaining('Fine detail is generated'), findsOneWidget);
|
||||
expect(find.textContaining('AI-reconstructed from'), findsOneWidget);
|
||||
expect(find.textContaining('fine detail is generated'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('the caption quotes the real bitstream size, not a nominal one', (
|
||||
@@ -498,7 +509,7 @@ void main() {
|
||||
await tester.pump();
|
||||
|
||||
final caption = tester.widget<Text>(
|
||||
find.textContaining('Reconstructed by an AI model'),
|
||||
find.textContaining('AI-reconstructed from'),
|
||||
);
|
||||
expect(caption.maxLines, isNull, reason: 'the sentence must wrap in full');
|
||||
expect(caption.overflow, isNot(TextOverflow.ellipsis));
|
||||
|
||||
Reference in new issue
Block a user