Refactor LoRa airtime tests and add new functionality

- Updated LoRa airtime calculations in `lora_airtime_test.dart` to reflect new reference values.
- Introduced new tests for LDRO behavior and preamble symbol calculations.
- Added `contact_path_width_test.dart` to validate path hash width handling in contacts.
- Enhanced `model_changes_test.dart` to ensure legacy data migration works correctly.
- Created `remote_node_stats_test.dart` to decode and validate remote node statistics.
- Implemented `map_marker_parse_test.dart` for parsing marker text with coordinate validation.
- Developed `map_tile_cache_key_test.dart` to ensure API keys are excluded from cache keys.
- Added `message_retry_failure_test.dart` to test message retry service behavior on failures.
- Extended `path_history_service_test.dart` to preserve learned state across path attempts.
- Enhanced `received_image_store_test.dart` to handle concurrent writes and review fixes.
- Implemented `repeater_command_service_test.dart` to validate command response handling.
- Created `store_tolerant_parsing_test.dart` to ensure stores skip malformed records gracefully.
- Cleared untranslated JSON file for localization updates.
This commit is contained in:
Zach committed 2026-09-25 10:01:18 -07:00
1 parent d5f54dfa11
commit d74587c167
105 files changed
+6419 -2072

No files matched your search

@@ -0,0 +1,23 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/services/map_tile_cache_service.dart';
void main() {
test('tile cache key drops api_key and keeps everything else', () {
expect(
MapTileCacheService.tileCacheKey(
'https://tiles.stadiamaps.com/tiles/outdoors/10/1/2@2x.png?api_key=k1',
),
'https://tiles.stadiamaps.com/tiles/outdoors/10/1/2@2x.png',
);
expect(
MapTileCacheService.tileCacheKey('https://x/t/1/2/3.png?a=1&api_key=k2'),
'https://x/t/1/2/3.png?a=1',
);
expect(
MapTileCacheService.tileCacheKey(
'https://tile.openstreetmap.org/1/2/3.png',
),
'https://tile.openstreetmap.org/1/2/3.png',
);
});
}
@@ -0,0 +1,85 @@
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/services/message_retry_service.dart';
Contact _contact() => Contact(
publicKey: Uint8List.fromList(List<int>.generate(32, (i) => 0xAA + i)),
name: 'Test',
type: 1,
pathLength: -1,
path: Uint8List(0),
lastSeen: DateTime.now(),
);
void main() {
late MessageRetryService service;
late Map<String, Message> latest;
late List<String> sentTexts;
late bool failSends;
Uint8List? selfKey;
setUp(() {
service = MessageRetryService();
latest = {};
sentTexts = [];
failSends = false;
selfKey = Uint8List(32);
service.initialize(
RetryServiceConfig(
sendMessage: (_, text, _, _) async {
if (failSends) throw StateError('Not connected');
sentTexts.add(text);
},
addMessage: (_, m) => latest[m.messageId] = m,
updateMessage: (m) => latest[m.messageId] = m,
getSelfPublicKey: () => selfKey,
),
);
});
tearDown(() => service.dispose());
Message byText(String text) =>
latest.values.firstWhere((m) => m.text == text);
test('failed send fails the message and frees the contact slot', () async {
failSends = true;
final contact = _contact();
await service.sendMessageWithRetry(contact: contact, text: 'a');
await pumpEventQueue();
expect(byText('a').status, MessageStatus.failed);
failSends = false;
await service.sendMessageWithRetry(contact: contact, text: 'b');
await pumpEventQueue();
expect(sentTexts, ['b']);
});
test('unknown self key fails instead of waiting forever', () async {
selfKey = null;
await service.sendMessageWithRetry(contact: _contact(), text: 'a');
await pumpEventQueue();
expect(byText('a').status, MessageStatus.failed);
expect(sentTexts, isEmpty);
expect(service.hasPendingMessages, isFalse);
});
test('failAllPending fails in-flight and queued messages', () async {
final contact = _contact();
await service.sendMessageWithRetry(contact: contact, text: 'a');
await service.sendMessageWithRetry(contact: contact, text: 'b');
await pumpEventQueue();
expect(sentTexts, ['a']);
service.failAllPending();
await pumpEventQueue();
expect(byText('a').status, MessageStatus.failed);
expect(byText('b').status, MessageStatus.failed);
expect(service.hasPendingMessages, isFalse);
expect(sentTexts, ['a']);
});
}
@@ -823,4 +823,70 @@ void main() {
expect(paths.first.routeWeight, closeTo(1.5, 0.001));
});
});
group('learned state is preserved', () {
const sel = PathSelection(pathBytes: [0x01], hopCount: 1, useFlood: false);
test('recordPathAttempt keeps the learned route weight', () async {
final pubKey = _hex('k001');
await _seed(svc, pubKey, pathBytes: [0x01], weight: 1.0);
svc.recordPathResult(pubKey, sel, success: true, successIncrement: 1.0);
await _flush();
svc.recordPathAttempt(pubKey, sel);
await _flush();
expect(svc.getRecentPaths(pubKey).first.routeWeight, closeTo(2.0, 1e-9));
});
test('handlePathUpdated keeps the learned route weight', () async {
final pubKey = _hex('k002');
await _seed(svc, pubKey, pathBytes: [0x01], weight: 3.0);
svc.handlePathUpdated(
_makeContact(publicKeyHex: pubKey, pathLength: 1, path: [0x01]),
);
await _flush();
expect(svc.getRecentPaths(pubKey).first.routeWeight, closeTo(3.0, 1e-9));
});
test('recordPathResult after eviction merges with stored counts', () async {
final pubKey = _hex('k003');
await _seed(svc, pubKey, pathBytes: [0x01], weight: 1.0);
for (var i = 0; i < 3; i++) {
svc.recordPathResult(pubKey, sel, success: true, successIncrement: 0.5);
}
await _flush();
final fresh = PathHistoryService(storage);
fresh.recordPathResult(pubKey, sel, success: true, successIncrement: 0.5);
await _flush();
final record = fresh.getRecentPaths(pubKey).first;
expect(record.successCount, equals(4));
expect(record.routeWeight, closeTo(3.0, 1e-9));
});
test('getRecentPaths load does not drop a concurrent add', () async {
final pubKey = _hex('k004');
await _seed(svc, pubKey, pathBytes: [0x01], weight: 1.0);
final fresh = PathHistoryService(storage);
fresh.getRecentPaths(pubKey);
fresh.handlePathUpdated(
_makeContact(publicKeyHex: pubKey, pathLength: 1, path: [0x02]),
);
await _flush();
final paths = fresh.getRecentPaths(pubKey).map((p) => p.pathBytes);
expect(
paths,
containsAll([
[0x01],
[0x02],
]),
);
});
});
}
@@ -990,6 +990,16 @@ void main() {
FileReceivedImageBlobStore newStore() =>
FileReceivedImageBlobStore(baseDirectory: () async => tempDir);
test('concurrent sidecar writes for one id land the last one', () async {
final blobs = newStore();
await Future.wait<void>([
for (var i = 0; i < 20; i++)
blobs.writeSidecar('1a2b0700693f21', '{"n":$i}'),
]);
final sidecars = await blobs.readSidecars();
expect(sidecars['1a2b0700693f21'], '{"n":19}');
});
test('round-trips bytes and sidecars through real files', () async {
final blobs = newStore();
await blobs.writeBitstream('1a2b0700693f21', _payload(155));
@@ -1170,6 +1180,109 @@ void main() {
expect(listenable.value!.state, ReceivedImageState.decoded);
},
);
group('review fixes 2026-09-24', () {
Future<ReceivedImageEntry> startTwoChunk(_Rig h, int imgId) async {
final set = buildImageChunks(
payload: _payload(kImageChunkFirstCapacity + 20, imgId),
metadata: const ImageStreamMetadata(rate: ImageCodecRatePoint.standard),
senderPrefix: kSender,
imgId: imgId,
);
final entry = await h.store.handleOutcome(
h.reassembler.addChunk(set.blobs[0], channelIndex: 3, now: h.clock()),
channelIndex: 3,
at: h.clock(),
);
return entry!;
}
Future<void> failIt(_Rig h, ReceivedImageEntry entry) async {
await h.store.handleFailure(
ImageReassemblyFailure(
key: entry.key,
total: 2,
receivedDataChunks: 1,
hadParity: false,
firstSeen: entry.firstSeen,
expiredAt: h.clock(),
),
);
}
test('a reused img_id does not overwrite a decoded image', () async {
final h = _build();
final first = await _completeOne(h, imgId: 11, seed: 1);
await h.store.settle();
expect(
h.store.entryFor(first.streamId)!.state,
ReceivedImageState.decoded,
);
h.advance(const Duration(minutes: 1));
final second = await startTwoChunk(h, 11);
expect(second.streamId, isNot(first.streamId));
expect(second.state, ReceivedImageState.receiving);
expect(
h.store.entryFor(first.streamId)!.state,
ReceivedImageState.decoded,
);
h.advance(const Duration(minutes: 10));
h.reassembler.clear();
final third = await _completeOne(h, imgId: 11, seed: 9);
expect(third.streamId, isNot(first.streamId));
expect(
h.store.entryFor(first.streamId)!.state,
ReceivedImageState.decoded,
);
});
test('failed entries are capped by count, oldest first', () async {
final h = _build(maxImages: 2);
final ids = <String>[];
for (var i = 0; i < 4; i++) {
final entry = await startTwoChunk(h, 70 + i);
await failIt(h, entry);
ids.add(entry.streamId);
h.advance(const Duration(seconds: 5));
}
expect(h.store.entries.length, 2);
expect(h.store.entryFor(ids[0]), isNull);
expect(h.blobs.hasSidecar(ids[0]), isFalse);
expect(
h.store.entryFor(ids[3])!.state,
ReceivedImageState.failedIncomplete,
);
});
test('failed entries past maxAge are deleted outright', () async {
final h = _build(maxAge: const Duration(days: 1));
final entry = await startTwoChunk(h, 80);
await failIt(h, entry);
h.advance(const Duration(days: 2));
await h.store.evictToBudget();
expect(h.store.entryFor(entry.streamId), isNull);
expect(h.blobs.hasSidecar(entry.streamId), isFalse);
});
test('foreground memory pressure mid-decode parks, not corrupt', () async {
final decoder = _FakeDecoder(mode: 'fail')
..delay = const Duration(milliseconds: 50);
final h = _build(decoder: decoder);
final entry = await _completeOne(h);
await Future<void>.delayed(const Duration(milliseconds: 10));
expect(
h.store.entryFor(entry.streamId)!.state,
ReceivedImageState.decoding,
);
await h.store.handleMemoryPressure();
await h.store.settle();
final after = h.store.entryFor(entry.streamId)!;
expect(after.state, ReceivedImageState.reassembled);
expect(after.needsManualDecode, isTrue);
});
});
}
/// Delivers a whole single-chunk image and returns its entry (state
@@ -1,6 +1,35 @@
import 'dart:async';
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/connector/meshcore_connector.dart';
import 'package:meshcore_open/models/contact.dart';
import 'package:meshcore_open/models/path_selection.dart';
import 'package:meshcore_open/services/repeater_command_service.dart';
class _FakeConnector extends MeshCoreConnector {
@override
Future<PathSelection> preparePathForContactSend(Contact contact) async =>
const PathSelection(pathBytes: [], hopCount: -1, useFlood: true);
@override
Future<void> sendFrame(
Uint8List data, {
String? channelSendQueueId,
bool expectsGenericAck = false,
bool waitForGenericAck = false,
}) async {}
}
Contact _repeater(int seed) => Contact(
publicKey: Uint8List.fromList(List<int>.generate(32, (i) => seed + i)),
name: 'R$seed',
type: 2,
pathLength: -1,
path: Uint8List(0),
lastSeen: DateTime.now(),
);
void main() {
group('normalizeRepeaterClockSyncCommand', () {
test('translates "clock sync" to explicit time command', () {
@@ -19,7 +48,10 @@ void main() {
});
test('passes other commands through unchanged', () {
expect(normalizeRepeaterClockSyncCommand('clock', nowSeconds: 1), 'clock');
expect(
normalizeRepeaterClockSyncCommand('clock', nowSeconds: 1),
'clock',
);
expect(
normalizeRepeaterClockSyncCommand('get radio', nowSeconds: 1),
'get radio',
@@ -40,4 +72,50 @@ void main() {
expect(epoch, inInclusiveRange(before, after));
});
});
group('RepeaterCommandService.handleResponse', () {
late RepeaterCommandService service;
setUp(() => service = RepeaterCommandService(_FakeConnector()));
tearDown(() => service.dispose());
test('unknown prefix does not complete the pending command', () async {
final repeater = _repeater(1);
String? result;
unawaited(
service
.sendCommand(repeater, 'ver', retries: 1)
.then((r) => result = r, onError: (_) {}),
);
await pumpEventQueue();
service.handleResponse(repeater, 'FE|late reply');
await pumpEventQueue();
expect(result, isNull);
service.handleResponse(repeater, '00|v1.0');
await pumpEventQueue();
expect(result, 'v1.0');
});
test('prefix owned by another repeater is ignored', () async {
final a = _repeater(1);
final b = _repeater(100);
String? result;
unawaited(
service
.sendCommand(a, 'ver', retries: 1)
.then((r) => result = r, onError: (_) {}),
);
await pumpEventQueue();
service.handleResponse(b, '00|wrong');
await pumpEventQueue();
expect(result, isNull);
service.handleResponse(a, 'unprefixed');
await pumpEventQueue();
expect(result, 'unprefixed');
});
});
}