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:
1 parent
d5f54dfa11
commit
d74587c167
105 files changed
+6419
-2072
No files matched your search
@@ -6,7 +6,7 @@ import 'package:meshcore_open/connector/meshcore_protocol.dart';
|
||||
void main() {
|
||||
// Frame layout per the doc comment on buildUpdateContactPathFrame:
|
||||
// [cmd][pub_key x32][type][flags][path_len][path x64][name x32]
|
||||
// [timestamp x4][Lat? x4, Lon? x4][timestamp? x4]
|
||||
// [last_advert x4][Lat? x4, Lon? x4][lastmod? x4]
|
||||
//
|
||||
// Base (mandatory) bytes:
|
||||
// 1 cmd + 32 pubKey + 1 type + 1 flags + 1 pathLen + 64 path
|
||||
@@ -101,5 +101,77 @@ void main() {
|
||||
expect(latBytes.getInt32(0, Endian.little), (49.123456 * 1e6).round());
|
||||
expect(lonBytes.getInt32(0, Endian.little), (-123.123456 * 1e6).round());
|
||||
});
|
||||
|
||||
int lastAdvertField(Uint8List frame) => ByteData.sublistView(
|
||||
frame,
|
||||
baseFrameLength - 4,
|
||||
baseFrameLength,
|
||||
).getUint32(0, Endian.little);
|
||||
|
||||
test('writes the contact advert timestamp, not the phone clock', () {
|
||||
final advert = DateTime.utc(2025, 6, 1, 12);
|
||||
final frame = buildUpdateContactPathFrame(
|
||||
pubKey,
|
||||
path,
|
||||
path.length,
|
||||
lastAdvert: advert,
|
||||
lastModified: DateTime.utc(2026, 1, 2),
|
||||
);
|
||||
|
||||
expect(lastAdvertField(frame), advert.millisecondsSinceEpoch ~/ 1000);
|
||||
expect(
|
||||
ByteData.sublistView(
|
||||
frame,
|
||||
baseFrameLength + 8,
|
||||
).getUint32(0, Endian.little),
|
||||
DateTime.utc(2026, 1, 2).millisecondsSinceEpoch ~/ 1000,
|
||||
);
|
||||
});
|
||||
|
||||
test('writes 0 for last advert when unknown', () {
|
||||
final frame = buildUpdateContactPathFrame(pubKey, path, path.length);
|
||||
expect(lastAdvertField(frame), 0);
|
||||
});
|
||||
});
|
||||
|
||||
group('auto-add / repeat freq frames', () {
|
||||
test('SET_AUTOADD_CONFIG appends max hops only when given', () {
|
||||
final withoutHops = buildSetAutoAddConfigFrame(
|
||||
autoAddChat: true,
|
||||
autoAddRepeater: false,
|
||||
autoAddRoomServer: false,
|
||||
autoAddSensor: false,
|
||||
overwriteOldest: true,
|
||||
);
|
||||
expect(withoutHops, [
|
||||
cmdSetAutoAddConfig,
|
||||
autoAddChatFlag | autoAddOverwriteOldestFlag,
|
||||
]);
|
||||
|
||||
final withHops = buildSetAutoAddConfigFrame(
|
||||
autoAddChat: false,
|
||||
autoAddRepeater: false,
|
||||
autoAddRoomServer: false,
|
||||
autoAddSensor: false,
|
||||
overwriteOldest: false,
|
||||
maxHops: 3,
|
||||
);
|
||||
expect(withHops, [cmdSetAutoAddConfig, 0, 3]);
|
||||
});
|
||||
|
||||
test('parses RESP_ALLOWED_REPEAT_FREQ ranges', () {
|
||||
final data = ByteData(1 + 16);
|
||||
data.setUint8(0, respCodeAllowedRepeatFreq);
|
||||
data.setUint32(1, 433000, Endian.little);
|
||||
data.setUint32(5, 433000, Endian.little);
|
||||
data.setUint32(9, 869495, Endian.little);
|
||||
data.setUint32(13, 869600, Endian.little);
|
||||
final ranges = parseAllowedRepeatFreqFrame(data.buffer.asUint8List());
|
||||
expect(ranges, [
|
||||
(lowKHz: 433000, highKHz: 433000),
|
||||
(lowKHz: 869495, highKHz: 869600),
|
||||
]);
|
||||
expect(buildGetAllowedRepeatFreqFrame(), [cmdGetAllowedRepeatFreq]);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
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/storage/prefs_manager.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
Uint8List _contactFrame(int code, Uint8List key, String name) {
|
||||
final data = ByteData(1 + 32 + 3 + 64 + 32 + 4 + 12);
|
||||
final bytes = data.buffer.asUint8List();
|
||||
bytes[0] = code;
|
||||
bytes.setRange(1, 33, key);
|
||||
bytes[33] = advTypeChat;
|
||||
bytes[35] = 0xFF; // path unknown
|
||||
bytes.setRange(100, 100 + name.length, name.codeUnits);
|
||||
data.setUint32(132, 1700000000, Endian.little);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
setUp(() async {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
PrefsManager.reset();
|
||||
await PrefsManager.initialize();
|
||||
});
|
||||
|
||||
final key = Uint8List.fromList(List<int>.generate(32, (i) => i + 1));
|
||||
|
||||
test('NEW_ADVERT is discovered only, not a firmware contact', () {
|
||||
final connector = MeshCoreConnector();
|
||||
connector.handleFrameForTest(_contactFrame(pushCodeNewAdvert, key, 'Bob'));
|
||||
|
||||
expect(connector.contacts, isEmpty);
|
||||
expect(connector.discoveredContacts.map((c) => c.name), contains('Bob'));
|
||||
});
|
||||
|
||||
test('CONTACT_DELETED removes the firmware contact', () {
|
||||
final connector = MeshCoreConnector();
|
||||
connector.handleFrameForTest(_contactFrame(respCodeContact, key, 'Bob'));
|
||||
expect(connector.contacts.length, 1);
|
||||
|
||||
connector.handleFrameForTest([pushCodeContactDeleted, ...key]);
|
||||
expect(connector.contacts, isEmpty);
|
||||
});
|
||||
|
||||
test('CONTACTS_FULL raises the storage-full signal', () async {
|
||||
final connector = MeshCoreConnector();
|
||||
final events = connector.contactsFullEvents.first;
|
||||
connector.handleFrameForTest([pushCodeContactsFull]);
|
||||
|
||||
expect(connector.contactsStorageFull, isTrue);
|
||||
await events;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/connector/meshcore_protocol.dart';
|
||||
import 'package:meshcore_open/connector/pending_command_replies.dart';
|
||||
|
||||
void main() {
|
||||
Uint8List frame(List<int> bytes) => Uint8List.fromList(bytes);
|
||||
final keyA = Uint8List.fromList(List<int>.generate(32, (i) => i + 1));
|
||||
final keyB = Uint8List.fromList(List<int>.generate(32, (i) => i + 100));
|
||||
|
||||
PendingCommandReplies newQueue() =>
|
||||
PendingCommandReplies(staleAfter: const Duration(seconds: 10));
|
||||
|
||||
test('ERR goes to the oldest pending command (firmware order)', () {
|
||||
final queue = newQueue();
|
||||
final time = queue.track(buildSetDeviceTimeFrame(1));
|
||||
queue.track(buildSetAdvertNameFrame('x'));
|
||||
|
||||
final failed = queue.takeErr(6);
|
||||
expect(failed, same(time));
|
||||
expect(queue.takeOk()?.commandCode, cmdSetAdvertName);
|
||||
expect(queue.length, 0);
|
||||
});
|
||||
|
||||
test('OK skips commands whose success is a specific RESP_CODE', () {
|
||||
final queue = newQueue();
|
||||
queue.track(buildSendTextMsgFrame(keyA, 'hi'));
|
||||
queue.track(buildRemoveContactFrame(keyA));
|
||||
|
||||
expect(queue.takeOk()?.commandCode, cmdRemoveContact);
|
||||
expect(queue.completeReply(frame([respCodeSent, 0, 0, 0, 0, 0])), isTrue);
|
||||
expect(queue.length, 0);
|
||||
});
|
||||
|
||||
test('specific replies clear their entry so a later ERR is not misread', () {
|
||||
final queue = newQueue();
|
||||
queue.track(buildGetChannelFrame(0));
|
||||
queue.track(buildSetChannelFrame(1, 'c', Uint8List(16)));
|
||||
|
||||
expect(queue.completeReply(frame([respCodeChannelInfo, 0])), isTrue);
|
||||
expect(queue.takeErr(2)?.commandCode, cmdSetChannel);
|
||||
});
|
||||
|
||||
test('CONTACT only completes GET_CONTACT_BY_KEY for the same key', () {
|
||||
final queue = newQueue();
|
||||
queue.track(buildGetContactByKeyFrame(keyA));
|
||||
|
||||
expect(queue.completeReply(frame([respCodeContact, ...keyB])), isFalse);
|
||||
expect(queue.completeReply(frame([respCodeContact, ...keyA])), isTrue);
|
||||
expect(queue.length, 0);
|
||||
});
|
||||
|
||||
test('untracked commands are not enrolled', () {
|
||||
final queue = newQueue();
|
||||
expect(queue.track(buildSyncNextMessageFrame()), isNull);
|
||||
expect(queue.track(buildRebootFrame()), isNull);
|
||||
expect(queue.takeErr(1), isNull);
|
||||
});
|
||||
|
||||
test('awaited command completes with error on ERR', () async {
|
||||
final queue = newQueue();
|
||||
final pending = queue.track(
|
||||
buildSetRadioParamsFrame(869525, 250000, 11, 5),
|
||||
waitForReply: true,
|
||||
);
|
||||
queue.takeErr(6);
|
||||
await expectLater(pending!.completer!.future, throwsException);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/helpers/utf8_length_limiter.dart';
|
||||
|
||||
TextEditingValue _value(String text, [int? cursor]) => TextEditingValue(
|
||||
text: text,
|
||||
selection: TextSelection.collapsed(offset: cursor ?? text.length),
|
||||
);
|
||||
|
||||
void main() {
|
||||
const formatter = Utf8LengthLimitingTextInputFormatter(5);
|
||||
|
||||
test('accepts edits within the limit', () {
|
||||
final result = formatter.formatEditUpdate(_value('ab'), _value('abc'));
|
||||
expect(result.text, 'abc');
|
||||
});
|
||||
|
||||
test('clips only the inserted text and keeps the end of the draft', () {
|
||||
// Paste "XYZ" at the start of "abc" (limit 5 bytes).
|
||||
final result = formatter.formatEditUpdate(
|
||||
_value('abc', 0),
|
||||
_value('XYZabc', 3),
|
||||
);
|
||||
expect(result.text, 'XYabc');
|
||||
expect(result.selection.baseOffset, 2);
|
||||
});
|
||||
|
||||
test('rejects an insertion in the middle when full', () {
|
||||
final result = formatter.formatEditUpdate(
|
||||
_value('abcde', 2),
|
||||
_value('abXcde', 3),
|
||||
);
|
||||
expect(result.text, 'abcde');
|
||||
expect(result.selection.baseOffset, 2);
|
||||
});
|
||||
|
||||
test('does not split a multi-code-point grapheme', () {
|
||||
// Family emoji is 18 UTF-8 bytes, so it cannot fit in the 4 bytes left.
|
||||
final result = formatter.formatEditUpdate(
|
||||
_value('a'),
|
||||
_value('a\u{1F468}\u{1F469}\u{1F467}'),
|
||||
);
|
||||
expect(result.text, 'a');
|
||||
});
|
||||
|
||||
test('keeps whole emoji that fit', () {
|
||||
const limiter = Utf8LengthLimitingTextInputFormatter(9);
|
||||
final result = limiter.formatEditUpdate(
|
||||
_value('a'),
|
||||
_value('a\u{1F600}\u{1F601}'),
|
||||
);
|
||||
expect(result.text, 'a\u{1F600}\u{1F601}');
|
||||
final clipped = const Utf8LengthLimitingTextInputFormatter(
|
||||
8,
|
||||
).formatEditUpdate(_value('a'), _value('a\u{1F600}\u{1F601}'));
|
||||
expect(clipped.text, 'a\u{1F600}');
|
||||
});
|
||||
|
||||
test('replacing one emoji with another sharing a surrogate stays valid', () {
|
||||
const limiter = Utf8LengthLimitingTextInputFormatter(5);
|
||||
final result = limiter.formatEditUpdate(
|
||||
_value('a\u{1F600}'),
|
||||
_value('a\u{1F601}\u{1F602}'),
|
||||
);
|
||||
expect(result.text, 'a\u{1F601}');
|
||||
});
|
||||
|
||||
test('allows deletions even when the text is already over the limit', () {
|
||||
final result = formatter.formatEditUpdate(
|
||||
_value('abcdefg'),
|
||||
_value('abcdef'),
|
||||
);
|
||||
expect(result.text, 'abcdef');
|
||||
});
|
||||
}
|
||||
@@ -956,6 +956,55 @@ void main() {
|
||||
});
|
||||
});
|
||||
|
||||
group('oversized data body', () {
|
||||
test('a 159-byte data body is rejected and parity cannot overrun', () {
|
||||
final failed = <ImageReassemblyFailure>[];
|
||||
final r = ImageReassembler(onFailed: failed.add);
|
||||
// Header: sender 0x1234, img 5, idx 0 of 2; body one byte past the cap.
|
||||
final oversized = Uint8List.fromList(<int>[
|
||||
0x12,
|
||||
0x34,
|
||||
5,
|
||||
(0 << 4) | 2,
|
||||
...List<int>.filled(kImageChunkBodyBytes + 1, 0xAA),
|
||||
]);
|
||||
expect(oversized.length, kImageChunkBlobBytes);
|
||||
expect(r.addChunk(oversized).status, ImageChunkStatus.malformed);
|
||||
expect(r.pendingCount, 0);
|
||||
|
||||
// A parity chunk for the same stream must not throw.
|
||||
final parity = Uint8List.fromList(<int>[
|
||||
0x12,
|
||||
0x34,
|
||||
5,
|
||||
(2 << 4) | 2,
|
||||
...List<int>.filled(kImageChunkBodyBytes + 1, 0x55),
|
||||
]);
|
||||
expect(() => r.addChunk(parity), returnsNormally);
|
||||
});
|
||||
});
|
||||
|
||||
group('clear()', () {
|
||||
test('reports in-progress streams as failed (disconnected)', () {
|
||||
final failed = <ImageReassemblyFailure>[];
|
||||
final r = ImageReassembler(onFailed: failed.add);
|
||||
final set = buildImageChunks(
|
||||
payload: payloadOf(400, seed: 3),
|
||||
metadata: stdMeta,
|
||||
senderPrefix: senderA,
|
||||
imgId: 8,
|
||||
);
|
||||
r.addChunk(set.blobs[0]);
|
||||
expect(r.pendingCount, 1);
|
||||
r.clear();
|
||||
expect(r.pendingCount, 0);
|
||||
expect(failed, hasLength(1));
|
||||
expect(failed.single.reason, ImageReassemblyFailureReason.disconnected);
|
||||
expect(failed.single.isCorrupt, isFalse);
|
||||
expect(r.evictExpired(now: DateTime(2100)), isEmpty);
|
||||
});
|
||||
});
|
||||
|
||||
group('completed-image map is capped', () {
|
||||
/// A lone parity chunk of a `total == 1` image completes that image by
|
||||
/// itself — one packet, one remembered entry. That is the amplification the
|
||||
|
||||
+63
-11
@@ -5,6 +5,7 @@ import 'package:meshcore_open/services/image_chunk_transport.dart';
|
||||
import 'package:meshcore_open/widgets/image_send_codec_binding.dart';
|
||||
import 'package:meshcore_open/models/radio_settings.dart';
|
||||
import 'package:meshcore_open/utils/lora_airtime.dart';
|
||||
import 'package:meshcore_open/connector/meshcore_protocol.dart' as protocol;
|
||||
|
||||
double _ms(Duration d) => d.inMicroseconds / 1000.0;
|
||||
|
||||
@@ -22,24 +23,24 @@ RadioSettings _radio({
|
||||
|
||||
void main() {
|
||||
group('loraTimeOnAir reference values (255-byte packet)', () {
|
||||
test('SF9, CR 4/8, BW 250 kHz -> 975 ms', () {
|
||||
test('SF9, CR 4/8, BW 250 kHz -> 992 ms', () {
|
||||
final toa = loraTimeOnAir(
|
||||
payloadBytes: 255,
|
||||
spreadingFactor: 9,
|
||||
bandwidthHz: 250000,
|
||||
codingRate: 8,
|
||||
);
|
||||
expect(_ms(toa), closeTo(975, 1));
|
||||
expect(_ms(toa), closeTo(991.744, 1));
|
||||
});
|
||||
|
||||
test('SF10, CR 4/5, BW 250 kHz -> 1148 ms', () {
|
||||
test('SF10, CR 4/5, BW 250 kHz -> 1181 ms', () {
|
||||
final toa = loraTimeOnAir(
|
||||
payloadBytes: 255,
|
||||
spreadingFactor: 10,
|
||||
bandwidthHz: 250000,
|
||||
codingRate: 5,
|
||||
);
|
||||
expect(_ms(toa), closeTo(1148, 1));
|
||||
expect(_ms(toa), closeTo(1180.672, 1));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -52,8 +53,8 @@ void main() {
|
||||
codingRate: 5,
|
||||
);
|
||||
// DE = 1 -> denominator 4*(12-2) = 40 -> 51 * 5 = 255 payload symbols
|
||||
// ToA = (12.25 + 263) * 32.768 ms
|
||||
expect(_ms(toa), closeTo(9019.392, 1));
|
||||
// ToA = (20.25 + 263) * 32.768 ms
|
||||
expect(_ms(toa), closeTo(9281.536, 1));
|
||||
});
|
||||
|
||||
test('SF12 / BW 500 kHz does NOT engage LDRO (Tsym = 8.192 ms)', () {
|
||||
@@ -64,8 +65,8 @@ void main() {
|
||||
codingRate: 5,
|
||||
);
|
||||
// DE = 0 -> denominator 48 -> 43 * 5 = 215 payload symbols
|
||||
// ToA = (12.25 + 223) * 8.192 ms
|
||||
expect(_ms(toa), closeTo(1927.9296, 1));
|
||||
// ToA = (20.25 + 223) * 8.192 ms
|
||||
expect(_ms(toa), closeTo(1992.704, 1));
|
||||
});
|
||||
|
||||
test('SF11 / BW 250 kHz does NOT engage LDRO (Tsym = 8.192 ms)', () {
|
||||
@@ -77,9 +78,60 @@ void main() {
|
||||
codingRate: 5,
|
||||
);
|
||||
// DE = 0 -> denominator 44 -> 47 * 5 = 235 payload symbols
|
||||
// ToA = (12.25 + 243) * 8.192 ms
|
||||
expect(_ms(withSf11), closeTo(2091.008, 1));
|
||||
// ToA = (20.25 + 243) * 8.192 ms
|
||||
expect(_ms(withSf11), closeTo(2156.544, 1));
|
||||
});
|
||||
|
||||
test('calculateLoRaAirtime derives LDRO off for SF11 / BW 250 kHz', () {
|
||||
// cr is in the 1..4 domain here; 16-symbol preamble at SF11.
|
||||
expect(
|
||||
protocol.calculateLoRaAirtime(
|
||||
payloadBytes: 255,
|
||||
spreadingFactor: 11,
|
||||
bandwidthHz: 250000,
|
||||
codingRate: 1,
|
||||
),
|
||||
2157,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
group('preamble matches firmware (32 symbols <= SF8, 16 above)', () {
|
||||
test('meshCorePreambleSymbols', () {
|
||||
expect(meshCorePreambleSymbols(7), 32);
|
||||
expect(meshCorePreambleSymbols(8), 32);
|
||||
expect(meshCorePreambleSymbols(9), 16);
|
||||
expect(meshCorePreambleSymbols(12), 16);
|
||||
});
|
||||
|
||||
for (final sf in [7, 8, 9, 12]) {
|
||||
test('SF$sf default preamble equals explicit firmware length', () {
|
||||
final preamble = sf <= 8 ? 32 : 16;
|
||||
Duration toa({int? preambleSymbols}) => loraTimeOnAir(
|
||||
payloadBytes: 100,
|
||||
spreadingFactor: sf,
|
||||
bandwidthHz: 125000,
|
||||
codingRate: 5,
|
||||
preambleSymbols: preambleSymbols,
|
||||
);
|
||||
expect(toa(), toa(preambleSymbols: preamble));
|
||||
expect(
|
||||
protocol.calculateLoRaAirtime(
|
||||
payloadBytes: 100,
|
||||
spreadingFactor: sf,
|
||||
bandwidthHz: 125000,
|
||||
codingRate: 1,
|
||||
),
|
||||
protocol.calculateLoRaAirtime(
|
||||
payloadBytes: 100,
|
||||
spreadingFactor: sf,
|
||||
bandwidthHz: 125000,
|
||||
codingRate: 1,
|
||||
preambleSymbols: preamble,
|
||||
),
|
||||
);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
group('airtime monotonicity / sanity', () {
|
||||
@@ -136,7 +188,7 @@ void main() {
|
||||
codingRate: normalizeCodingRate(8),
|
||||
);
|
||||
expect(a, b);
|
||||
expect(_ms(a), closeTo(975, 1));
|
||||
expect(_ms(a), closeTo(991.744, 1));
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/connector/meshcore_protocol.dart';
|
||||
import 'package:meshcore_open/helpers/path_helper.dart';
|
||||
import 'package:meshcore_open/models/channel_message.dart';
|
||||
import 'package:meshcore_open/models/contact.dart';
|
||||
import 'package:meshcore_open/storage/contact_discovery_store.dart';
|
||||
import 'package:meshcore_open/storage/contact_store.dart';
|
||||
import 'package:meshcore_open/storage/prefs_manager.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
Uint8List _contactFrame(int pathLen, List<int> path) {
|
||||
final writer = BytesBuilder();
|
||||
writer.addByte(respCodeContact);
|
||||
writer.add(List.generate(32, (i) => i + 1));
|
||||
writer.addByte(advTypeRepeater);
|
||||
writer.addByte(0);
|
||||
writer.addByte(pathLen);
|
||||
writer.add(Uint8List(64)..setRange(0, path.length, path));
|
||||
writer.add(Uint8List(32)..setRange(0, 4, 'Node'.codeUnits));
|
||||
writer.add([0x01, 0x00, 0x00, 0x00]);
|
||||
writer.add(Uint8List(12));
|
||||
return writer.toBytes();
|
||||
}
|
||||
|
||||
Contact _contact({required int pathHashWidth}) => Contact(
|
||||
publicKey: Uint8List.fromList(List.generate(32, (i) => i + 1)),
|
||||
name: 'Node',
|
||||
type: advTypeRepeater,
|
||||
pathLength: 2,
|
||||
path: Uint8List.fromList([0xA1, 0xA2, 0xB1, 0xB2]),
|
||||
pathHashWidth: pathHashWidth,
|
||||
lastSeen: DateTime.fromMillisecondsSinceEpoch(1000),
|
||||
);
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
setUp(() async {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
PrefsManager.reset();
|
||||
await PrefsManager.initialize();
|
||||
});
|
||||
|
||||
group('Contact.fromFrame keeps the path hash width', () {
|
||||
test('2-byte hops', () {
|
||||
final contact = Contact.fromFrame(
|
||||
_contactFrame((1 << 6) | 2, [0xA1, 0xA2, 0xB1, 0xB2]),
|
||||
)!;
|
||||
expect(contact.pathLength, 2);
|
||||
expect(contact.pathHashWidth, 2);
|
||||
expect(contact.path, [0xA1, 0xA2, 0xB1, 0xB2]);
|
||||
expect(PathHelper.splitPathBytes(contact.path, contact.pathHashWidth), [
|
||||
[0xA1, 0xA2],
|
||||
[0xB1, 0xB2],
|
||||
]);
|
||||
});
|
||||
|
||||
test('3-byte hops', () {
|
||||
final contact = Contact.fromFrame(
|
||||
_contactFrame((2 << 6) | 1, [0xA1, 0xA2, 0xA3]),
|
||||
)!;
|
||||
expect(contact.pathLength, 1);
|
||||
expect(contact.pathHashWidth, 3);
|
||||
expect(contact.path, [0xA1, 0xA2, 0xA3]);
|
||||
});
|
||||
|
||||
test('flood defaults to width 1', () {
|
||||
final contact = Contact.fromFrame(_contactFrame(0xFF, const []))!;
|
||||
expect(contact.pathLength, -1);
|
||||
expect(contact.pathHashWidth, 1);
|
||||
});
|
||||
|
||||
test('copyWith preserves width', () {
|
||||
final contact = _contact(pathHashWidth: 2).copyWith(name: 'Renamed');
|
||||
expect(contact.pathHashWidth, 2);
|
||||
});
|
||||
});
|
||||
|
||||
group('Contact.inferPathHashWidth', () {
|
||||
test('divides bytes by hops', () {
|
||||
expect(Contact.inferPathHashWidth(2, 4), 2);
|
||||
expect(Contact.inferPathHashWidth(1, 3), 3);
|
||||
});
|
||||
|
||||
test('falls back to 1', () {
|
||||
expect(Contact.inferPathHashWidth(0, 0), 1);
|
||||
expect(Contact.inferPathHashWidth(-1, 0), 1);
|
||||
expect(Contact.inferPathHashWidth(2, 3), 1);
|
||||
expect(Contact.inferPathHashWidth(1, 4), 1);
|
||||
});
|
||||
});
|
||||
|
||||
group('Contact stores persist the path hash width', () {
|
||||
test('ContactStore round-trip', () async {
|
||||
final store = ContactStore()..publicKeyHex = '1234567890';
|
||||
await store.saveContacts([_contact(pathHashWidth: 2)]);
|
||||
final loaded = await store.loadContacts();
|
||||
expect(loaded.single.pathHashWidth, 2);
|
||||
expect(loaded.single.path, [0xA1, 0xA2, 0xB1, 0xB2]);
|
||||
});
|
||||
|
||||
test('ContactDiscoveryStore round-trip', () async {
|
||||
final store = ContactDiscoveryStore()..setPublicKeyHex = 'AABBCCDDEEFF00';
|
||||
await store.saveContacts([_contact(pathHashWidth: 2)]);
|
||||
final loaded = await store.loadContacts();
|
||||
expect(loaded.single.pathHashWidth, 2);
|
||||
});
|
||||
|
||||
test('legacy data without width is inferred from hops', () async {
|
||||
final store = ContactStore()..publicKeyHex = '1234567890';
|
||||
final json = {
|
||||
'publicKey': base64Encode(List.generate(32, (i) => i + 1)),
|
||||
'name': 'Legacy',
|
||||
'type': advTypeRepeater,
|
||||
'pathLength': 2,
|
||||
'path': base64Encode([0xA1, 0xA2, 0xB1, 0xB2]),
|
||||
'lastSeen': 1000,
|
||||
};
|
||||
await PrefsManager.instance.setString(store.keyFor, jsonEncode([json]));
|
||||
final loaded = await store.loadContacts();
|
||||
expect(loaded.single.pathHashWidth, 2);
|
||||
});
|
||||
|
||||
test('legacy flood data without width falls back to 1', () async {
|
||||
final store = ContactStore()..publicKeyHex = '1234567890';
|
||||
final json = {
|
||||
'publicKey': base64Encode(List.generate(32, (i) => i + 1)),
|
||||
'name': 'Legacy',
|
||||
'type': advTypeRepeater,
|
||||
'pathLength': -1,
|
||||
'path': base64Encode(const <int>[]),
|
||||
'lastSeen': 1000,
|
||||
};
|
||||
await PrefsManager.instance.setString(store.keyFor, jsonEncode([json]));
|
||||
final loaded = await store.loadContacts();
|
||||
expect(loaded.single.pathHashWidth, 1);
|
||||
});
|
||||
|
||||
test('legacy mode-encoded pathLength yields its width', () async {
|
||||
final store = ContactStore()..publicKeyHex = '1234567890';
|
||||
final json = {
|
||||
'publicKey': base64Encode(List.generate(32, (i) => i + 1)),
|
||||
'name': 'Legacy',
|
||||
'type': advTypeRepeater,
|
||||
'pathLength': (2 << 6) | 1,
|
||||
'path': base64Encode([0xA1, 0xA2, 0xA3]),
|
||||
'lastSeen': 1000,
|
||||
};
|
||||
await PrefsManager.instance.setString(store.keyFor, jsonEncode([json]));
|
||||
final loaded = await store.loadContacts();
|
||||
expect(loaded.single.pathLength, 1);
|
||||
expect(loaded.single.pathHashWidth, 3);
|
||||
});
|
||||
});
|
||||
|
||||
group('ChannelMessage.fromFrame path_len 0xFF (direct)', () {
|
||||
Uint8List frame({required bool v3}) {
|
||||
final writer = BytesBuilder();
|
||||
if (v3) {
|
||||
writer.add([respCodeChannelMsgRecvV3, 0x10, 0x01, 0x00]);
|
||||
} else {
|
||||
writer.addByte(respCodeChannelMsgRecv);
|
||||
}
|
||||
writer.addByte(3); // channel index
|
||||
writer.addByte(0xFF);
|
||||
writer.addByte(txtTypePlain);
|
||||
writer.add([0x01, 0x00, 0x00, 0x00]);
|
||||
writer.add(utf8.encode('Alice: hi'));
|
||||
writer.addByte(0);
|
||||
return writer.toBytes();
|
||||
}
|
||||
|
||||
test('V3 does not read 63 x 4-byte hops', () {
|
||||
final message = ChannelMessage.fromFrame(frame(v3: true))!;
|
||||
expect(message.text, 'hi');
|
||||
expect(message.senderName, 'Alice');
|
||||
expect(message.pathLength, isNull);
|
||||
expect(message.pathBytes, isEmpty);
|
||||
expect(message.pathHashWidth, isNull);
|
||||
expect(message.channelIndex, 3);
|
||||
});
|
||||
|
||||
test('non-V3 reads path_len unsigned', () {
|
||||
final message = ChannelMessage.fromFrame(frame(v3: false))!;
|
||||
expect(message.text, 'hi');
|
||||
expect(message.pathLength, isNull);
|
||||
});
|
||||
});
|
||||
|
||||
test('PathHelper treats width 4 as invalid and clamps to 3', () {
|
||||
expect(PathHelper.splitPathBytes([1, 2, 3, 4], 4), [
|
||||
[1, 2, 3],
|
||||
[4],
|
||||
]);
|
||||
});
|
||||
|
||||
test('buildSetPathHashModeFrame rejects reserved mode 3', () {
|
||||
expect(buildSetPathHashModeFrame(3), [cmdSetPathHashMode, 0, 2]);
|
||||
});
|
||||
}
|
||||
@@ -616,7 +616,8 @@ void main() {
|
||||
test(
|
||||
'ContactDiscoveryStore decodes and migrates legacy mode-encoded paths',
|
||||
() async {
|
||||
final store = ContactDiscoveryStore();
|
||||
final store = ContactDiscoveryStore()
|
||||
..setPublicKeyHex = 'AABBCCDDEEFF00112233';
|
||||
|
||||
final rawPath = Uint8List(64)
|
||||
..[0] = 0x11
|
||||
@@ -641,6 +642,8 @@ void main() {
|
||||
expect(contacts, hasLength(1));
|
||||
expect(contacts.first.pathLength, equals(1));
|
||||
expect(contacts.first.path, equals(Uint8List.fromList([0x11, 0x22])));
|
||||
expect(prefs.getString('discovered_contacts'), isNull);
|
||||
expect(prefs.getString(store.keyFor), isNotNull);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/models/remote_node_stats.dart';
|
||||
|
||||
Uint8List _frame(int statsSize, void Function(ByteData stats) fill) {
|
||||
final frame = Uint8List(RemoteNodeStats.payloadOffset + statsSize);
|
||||
fill(ByteData.sublistView(frame, RemoteNodeStats.payloadOffset));
|
||||
return frame;
|
||||
}
|
||||
|
||||
void _fillCommon(ByteData d) {
|
||||
d.setUint16(0, 4100, Endian.little);
|
||||
d.setInt16(4, -110, Endian.little);
|
||||
d.setUint32(16, 300, Endian.little);
|
||||
d.setUint32(20, 3600, Endian.little);
|
||||
d.setInt16(42, -22, Endian.little);
|
||||
d.setUint16(46, 9, Endian.little);
|
||||
}
|
||||
|
||||
void main() {
|
||||
test('decodes repeater stats with rx airtime and recv errors', () {
|
||||
final frame = _frame(56, (d) {
|
||||
_fillCommon(d);
|
||||
d.setUint32(48, 120, Endian.little);
|
||||
d.setUint32(52, 7, Endian.little);
|
||||
});
|
||||
final stats = RemoteNodeStats.tryParse(frame, isRoom: false)!;
|
||||
expect(stats.batteryMv, 4100);
|
||||
expect(stats.noiseFloor, -110);
|
||||
expect(stats.txAirSecs, 300);
|
||||
expect(stats.uptimeSecs, 3600);
|
||||
expect(stats.lastSnr, -5.5);
|
||||
expect(stats.floodDups, 9);
|
||||
expect(stats.rxAirSecs, 120);
|
||||
expect(stats.recvErrors, 7);
|
||||
expect(stats.posted, isNull);
|
||||
});
|
||||
|
||||
test('older repeater frame without recv errors', () {
|
||||
final frame = _frame(52, (d) {
|
||||
_fillCommon(d);
|
||||
d.setUint32(48, 120, Endian.little);
|
||||
});
|
||||
final stats = RemoteNodeStats.tryParse(frame, isRoom: false)!;
|
||||
expect(stats.rxAirSecs, 120);
|
||||
expect(stats.recvErrors, isNull);
|
||||
});
|
||||
|
||||
test('decodes room server posted / pushed counters', () {
|
||||
final frame = _frame(52, (d) {
|
||||
_fillCommon(d);
|
||||
d.setUint16(48, 42, Endian.little);
|
||||
d.setUint16(50, 17, Endian.little);
|
||||
});
|
||||
final stats = RemoteNodeStats.tryParse(frame, isRoom: true)!;
|
||||
expect(stats.posted, 42);
|
||||
expect(stats.postPushes, 17);
|
||||
expect(stats.rxAirSecs, isNull);
|
||||
expect(stats.recvErrors, isNull);
|
||||
});
|
||||
|
||||
test('rejects frames shorter than the common layout', () {
|
||||
expect(RemoteNodeStats.tryParse(Uint8List(50), isRoom: false), isNull);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/screens/map_screen.dart';
|
||||
|
||||
void main() {
|
||||
test('parseMarkerText accepts in-range coordinates', () {
|
||||
final payload = parseMarkerText('m:45.5,-122.6|Camp|x');
|
||||
expect(payload, isNotNull);
|
||||
expect(payload!.position.latitude, 45.5);
|
||||
expect(payload.position.longitude, -122.6);
|
||||
expect(payload.label, 'Camp');
|
||||
});
|
||||
|
||||
test('parseMarkerText rejects out-of-range coordinates', () {
|
||||
expect(parseMarkerText('m:999,999|x|'), isNull);
|
||||
expect(parseMarkerText('m:90.1,0|x|'), isNull);
|
||||
expect(parseMarkerText('m:0,-180.5|x|'), isNull);
|
||||
expect(parseMarkerText('m:-90,180|edge|'), isNotNull);
|
||||
});
|
||||
}
|
||||
@@ -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');
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/models/community.dart';
|
||||
import 'package:meshcore_open/services/storage_service.dart';
|
||||
import 'package:meshcore_open/storage/channel_message_store.dart';
|
||||
import 'package:meshcore_open/storage/community_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 _device = 'abcdef012345';
|
||||
|
||||
Future<void> _init(Map<String, Object> values) async {
|
||||
SharedPreferences.setMockInitialValues(values);
|
||||
PrefsManager.reset();
|
||||
await PrefsManager.initialize();
|
||||
}
|
||||
|
||||
void main() {
|
||||
test(
|
||||
'message store skips a malformed record instead of dropping all',
|
||||
() async {
|
||||
final good = {
|
||||
'senderKey': base64Encode([1, 2, 3]),
|
||||
'text': 'hello',
|
||||
'timestamp': 1000,
|
||||
'status': 1,
|
||||
};
|
||||
await _init({
|
||||
'messages_${_device.substring(0, 10)}c1': jsonEncode([
|
||||
good,
|
||||
{'text': 'no timestamp'},
|
||||
]),
|
||||
});
|
||||
final store = MessageStore()..setPublicKeyHex = _device;
|
||||
final messages = await store.loadMessages('c1');
|
||||
expect(messages.map((m) => m.text), ['hello']);
|
||||
expect(messages.single.isOutgoing, isFalse);
|
||||
},
|
||||
);
|
||||
|
||||
test('channel message store skips a malformed record', () async {
|
||||
await _init({
|
||||
'channel_messages_${_device.substring(0, 10)}0': jsonEncode([
|
||||
{'text': 'hi', 'timestamp': 1000, 'status': 1},
|
||||
'garbage',
|
||||
]),
|
||||
});
|
||||
final store = ChannelMessageStore()..setPublicKeyHex = _device;
|
||||
final messages = await store.loadChannelMessages(0);
|
||||
expect(messages.map((m) => m.text), ['hi']);
|
||||
});
|
||||
|
||||
test('community store keeps valid communities next to a bad one', () async {
|
||||
final community = Community.create(id: 'c1', name: 'Ops');
|
||||
await _init({
|
||||
'communities_v1${_device.substring(0, 10)}': jsonEncode([
|
||||
community.toJson(),
|
||||
{'id': 'broken'},
|
||||
]),
|
||||
});
|
||||
final store = CommunityStore()..setPublicKeyHex = _device;
|
||||
final communities = await store.loadCommunities();
|
||||
expect(communities.map((c) => c.id), ['c1']);
|
||||
});
|
||||
|
||||
test('delivery observations skip malformed entries', () async {
|
||||
await _init({
|
||||
'delivery_observations': jsonEncode([
|
||||
{
|
||||
'contact_key': 'k',
|
||||
'path_length': 1,
|
||||
'message_bytes': 10,
|
||||
'delivery_ms': 500,
|
||||
'timestamp': DateTime(2026).toIso8601String(),
|
||||
},
|
||||
{'contact_key': 'bad'},
|
||||
]),
|
||||
});
|
||||
final observations = await StorageService().loadDeliveryObservations();
|
||||
expect(observations, hasLength(1));
|
||||
expect(observations.single.isFlood, isFalse);
|
||||
});
|
||||
|
||||
test('community hashtag normalization trims before stripping #', () {
|
||||
final community = Community.create(id: 'c1', name: 'Ops');
|
||||
expect(
|
||||
community.deriveCommunityHashtagPsk(' #ops'),
|
||||
community.deriveCommunityHashtagPsk('#ops'),
|
||||
);
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user