Merge zjs81/dev into ez_share_urlimage_PR

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
ZIERandCopilot committed 2026-10-13 10:16:13 +02:00
commit 4000c49213
152 files changed
+28635 -8600

No files matched your search

+372
View File
@@ -0,0 +1,372 @@
import 'dart:convert';
import 'dart:typed_data';
import 'package:crypto/crypto.dart' as crypto;
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/review_mode/review_frames.dart';
import 'package:meshcore_open/review_mode/review_radio.dart';
import 'package:meshcore_open/review_mode/review_script.dart';
import 'package:meshcore_open/services/message_retry_service.dart';
import 'package:meshcore_open/services/path_history_service.dart';
import 'package:meshcore_open/services/storage_service.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:pointycastle/export.dart';
import 'package:shared_preferences/shared_preferences.dart';
final _scope = ReviewRadio.storagePrefix;
const _queuedHikingText = 'Planning to leave the trailhead at 8 on Saturday.';
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: 20));
}
}
Uint8List _psk(int slot) =>
Channel.parsePskHex(ReviewScript.channels[slot].pskHex);
String _id(Uint8List psk) => Channel.storageIdForPsk(psk)!;
String _messagesKey(String channelId) =>
'channel_messages_${_scope}_$channelId';
List<String> _storedTexts(String channelId) {
final raw = PrefsManager.instance.getString(_messagesKey(channelId));
if (raw == null) return [];
return [
for (final entry in jsonDecode(raw) as List<dynamic>)
(entry as Map<String, dynamic>)['text'] as String,
];
}
// SharedPreferences updates its in-memory cache synchronously.
void _seedMessages(String channelId, List<String> texts) =>
PrefsManager.instance.setString(
_messagesKey(channelId),
jsonEncode([
for (var i = 0; i < texts.length; i++)
{
'senderName': 'Ghost',
'text': texts[i],
'timestamp': 1000 * (i + 1),
'isOutgoing': false,
'status': ChannelMessageStatus.sent.index,
'messageId': 'seed-$channelId-$i',
'plainText': true,
},
]),
);
void _seedSlotMap(Map<int, String> slotIds) => PrefsManager.instance.setString(
'channel_slot_ids_$_scope',
jsonEncode({for (final e in slotIds.entries) '${e.key}': e.value}),
);
/// Review radio that records every frame the app sends and can swallow some.
class _TestRadio extends ReviewRadio {
_TestRadio({this.swallow, this.afterHandle})
: super(
scheduledMessageInterval: const Duration(hours: 1),
ackDelay: const Duration(milliseconds: 50),
replyDelay: const Duration(hours: 1),
);
final bool Function(Uint8List frame)? swallow;
final void Function(_TestRadio radio, Uint8List frame)? afterHandle;
final List<Uint8List> sent = [];
@override
void handle(Uint8List frame) {
sent.add(Uint8List.fromList(frame));
if (swallow?.call(frame) ?? false) return;
super.handle(frame);
afterHandle?.call(this, frame);
}
void deliver(Uint8List frame) => super.handle(frame);
List<int> codes() => [for (final f in sent) f.isEmpty ? -1 : f[0]];
}
late MeshCoreConnector _connector;
/// Connects a fresh review radio. [seed] runs after review mode has cleared
/// its storage and before SELF_INFO, standing in for a previous session.
Future<void> _connect(_TestRadio radio, {void Function()? seed}) async {
_connector.reviewRadioFactoryForTest = () {
// beginReviewModeSession wipes the review scope before this runs.
seed?.call();
return radio;
};
await _connector.connectReview();
addTearDown(_connector.disconnect);
await _waitFor(() => _connector.channelMapConfirmed);
}
Channel _channelAt(int slot) =>
_connector.channels.firstWhere((c) => c.index == slot);
List<String> _texts(int slot) =>
_connector.getChannelMessages(_channelAt(slot)).map((m) => m.text).toList();
Uint8List _logRxGroupText(Uint8List psk, String text, int timestampSecs) {
final plain = BytesBuilder()
..add(
Uint8List(4)
..buffer.asByteData().setUint32(0, timestampSecs, Endian.little),
)
..addByte(0)
..add(utf8.encode(text))
..addByte(0);
final padded = Uint8List(((plain.length + 15) ~/ 16) * 16)
..setRange(0, plain.length, plain.toBytes());
final cipher = ECBBlockCipher(AESEngine())..init(true, KeyParameter(psk));
final encrypted = Uint8List(padded.length);
for (var i = 0; i < padded.length; i += 16) {
cipher.processBlock(padded, i, encrypted, i);
}
final key32 = Uint8List(32)..setRange(0, 16, psk);
final mac = crypto.Hmac(crypto.sha256, key32).convert(encrypted).bytes;
final channelHash = crypto.sha256.convert(psk).bytes[0];
return Uint8List.fromList([
pushCodeLogRxData,
40, // snr
0xA0, // rssi
0x15, // flood route, GRP_TXT payload
0x00, // no path
channelHash,
mac[0],
mac[1],
...encrypted,
]);
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
setUpAll(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
_connector = MeshCoreConnector();
final retryService = MessageRetryService();
_connector.initialize(
retryService: retryService,
pathHistoryService: PathHistoryService(StorageService()),
);
addTearDown(() {
_connector.dispose();
retryService.dispose();
});
});
tearDown(() => _connector.channelSyncTimeoutMs = 2000);
final hikingId = _id(_psk(1));
final ghostPsk = Uint8List.fromList(List<int>.generate(16, (i) => 200 - i));
final ghostId = _id(ghostPsk);
test('a slot reused by another channel while away starts clean', () async {
await _connect(
_TestRadio(),
seed: () {
// Last session slot 1 held the ghost channel.
_seedSlotMap({0: _id(_psk(0)), 1: ghostId, 2: _id(_psk(2))});
_seedMessages(ghostId, ['ghost message']);
},
);
await _waitFor(() => _texts(1).contains(_queuedHikingText));
expect(_channelAt(1).name, 'Hiking Group');
expect(_texts(1), isNot(contains('ghost message')));
// The old channel's history is kept under its own ID.
expect(_storedTexts(ghostId), ['ghost message']);
expect(_storedTexts(hikingId), contains(_queuedHikingText));
expect(_connector.channelIdForSlot(1), hikingId);
expect(
jsonDecode(PrefsManager.instance.getString('channel_slot_ids_$_scope')!),
containsPair('1', hikingId),
);
});
test('a PSK edit in place starts clean, and re-adding the old PSK in '
'another slot brings its history back', () async {
await _connect(_TestRadio());
await _waitFor(() => _texts(1).contains(_queuedHikingText));
await _connector.setChannelSmazEnabled(1, true);
await _connector.setChannel(1, 'Hiking Group', ghostPsk);
expect(_connector.channelIdForSlot(1), ghostId);
expect(_texts(1), isEmpty);
expect(_connector.isChannelSmazEnabled(1), isFalse);
expect(_storedTexts(hikingId), contains(_queuedHikingText));
await _connector.setChannel(6, 'Hiking Group', _psk(1));
expect(_connector.channelIdForSlot(6), hikingId);
expect(_texts(6), contains(_queuedHikingText));
expect(_connector.isChannelSmazEnabled(6), isTrue);
// Restored history belongs to slot 6 now, so deleting from it works.
final restored = _connector
.getChannelMessages(_channelAt(6))
.firstWhere((m) => m.text == _queuedHikingText);
expect(restored.channelIndex, 6);
await _connector.deleteChannelMessage(restored);
expect(_texts(6), 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 {
await _connect(_TestRadio());
await _connector.setChannelOrder([1, 0, 2]);
expect(_connector.channels.first.index, 1);
await _connector.setChannel(1, 'Hiking Group', ghostPsk);
expect(_connector.channels.first.index, 1);
},
);
test('deleting a channel clears its stored history', () async {
await _connect(_TestRadio());
await _waitFor(() => _texts(1).contains(_queuedHikingText));
expect(_storedTexts(hikingId), isNotEmpty);
await _connector.deleteChannel(1);
expect(_storedTexts(hikingId), isEmpty);
});
test('a channel frame that arrives before the slot map is held, then filed '
'by the confirmed map', () async {
final radio = _TestRadio(
afterHandle: (radio, frame) {
if (frame[0] == cmdAppStart) {
radio.emitForTest(
ReviewFrames.channelMessage(
channelIndex: 1,
sender: 'Sam',
message: 'before the map',
timestampSecs: DateTime.now().millisecondsSinceEpoch ~/ 1000,
),
);
}
},
);
await _connect(
radio,
// A stale map from last session would file it under the ghost channel.
seed: () => _seedSlotMap({0: _id(_psk(0)), 1: ghostId, 2: _id(_psk(2))}),
);
await _waitFor(() => _texts(1).contains('before the map'));
expect(_storedTexts(hikingId), contains('before the map'));
expect(_storedTexts(ghostId), isNot(contains('before the map')));
});
test('MSG_WAITING before the channel sync waits for the slot map', () async {
// DEVICE_INFO is held back so MSG_WAITING lands between SELF_INFO and the
// start of the channel sync.
late final _TestRadio radio;
var deviceInfoHeld = false;
radio = _TestRadio(
swallow: (frame) {
if (frame[0] != cmdDeviceQuery || deviceInfoHeld) return false;
deviceInfoHeld = true;
Future<void>.delayed(
const Duration(milliseconds: 400),
() => radio.deliver(frame),
);
return true;
},
afterHandle: (radio, frame) {
if (frame[0] == cmdAppStart) {
radio.emitForTest(ReviewFrames.msgWaiting());
}
},
);
await _connect(radio);
await _waitFor(() => _texts(1).contains(_queuedHikingText));
final codes = radio.codes();
final firstSync = codes.indexOf(cmdSyncNextMessage);
final lastGetChannel = codes.lastIndexOf(cmdGetChannel);
expect(firstSync, isNonNegative);
expect(lastGetChannel, isNonNegative);
expect(firstSync, greaterThan(lastGetChannel));
});
test('a slot that never answers retries the sync, then releases the '
'queue with the saved map', () async {
_connector.channelSyncTimeoutMs = 30;
final radio = _TestRadio(
swallow: (frame) => frame[0] == cmdGetChannel && frame[1] == 1,
);
await _connect(
radio,
seed: () => _seedSlotMap({0: _id(_psk(0)), 1: hikingId, 2: _id(_psk(2))}),
);
await _waitFor(() => _storedTexts(hikingId).contains(_queuedHikingText));
final firstSync = radio.codes().indexOf(cmdSyncNextMessage);
final passes = radio.sent
.take(firstSync)
.where((f) => f[0] == cmdGetChannel && f[1] == 0)
.length;
expect(passes, 3);
expect(_connector.channelIdForSlot(1), hikingId);
});
test('two slots with the same PSK share one history', () async {
final radio = _TestRadio();
await _connect(
radio,
seed: () => radio.handle(buildSetChannelFrame(5, 'Hiking Twin', _psk(1))),
);
await _waitFor(() => _texts(1).contains(_queuedHikingText));
expect(_connector.channelIdForSlot(5), hikingId);
expect(_texts(5), _texts(1));
// Settings are stored per channel, so both slots see a change.
await _connector.setChannelSmazEnabled(5, true);
expect(_connector.isChannelSmazEnabled(1), isTrue);
await _connector.setChannelRegion(1, 'test-region');
expect(_connector.getChannelRegion(5), 'test-region');
radio.emitForTest(
ReviewFrames.channelMessage(
channelIndex: 5,
sender: 'Sam',
message: 'from the twin slot',
timestampSecs: DateTime.now().millisecondsSinceEpoch ~/ 1000,
),
);
await _waitFor(() => _texts(1).contains('from the twin slot'));
expect(_texts(5), contains('from the twin slot'));
expect(
_storedTexts(hikingId).where((t) => t == 'from the twin slot'),
hasLength(1),
);
});
test('an RX-log message is filed by its PSK-derived channel ID', () async {
final radio = _TestRadio();
await _connect(radio);
final localId = _id(_psk(2));
radio.emitForTest(
_logRxGroupText(
_psk(2),
'Ranger Pat: heard over the air',
DateTime.now().millisecondsSinceEpoch ~/ 1000,
),
);
await _waitFor(() => _texts(2).contains('heard over the air'));
expect(_storedTexts(localId), contains('heard over the air'));
expect(_texts(1), isNot(contains('heard over the air')));
});
}
+21 -6
View File
@@ -198,13 +198,28 @@ void main() {
expect(_connector.isTcpTransportConnected, isTrue);
// The companion goes away entirely: attempts fail and are rescheduled.
await companion.close();
await _waitFor(
() => _connector.state == MeshCoreConnectionState.disconnected,
);
await Future<void>.delayed(const Duration(milliseconds: 1500));
var sawRetryAttempt = false;
void observeRetryAttempt() {
if (_connector.state == MeshCoreConnectionState.connecting) {
sawRetryAttempt = true;
}
}
_connector.addListener(observeRetryAttempt);
try {
await companion.close();
// Wait for a retry to start and fail, then verify another backoff is
// scheduled. A fixed delay can observe the connector mid-attempt.
await _waitFor(
() =>
sawRetryAttempt &&
_connector.state == MeshCoreConnectionState.disconnected &&
_connector.isAutoReconnectScheduled,
);
} finally {
_connector.removeListener(observeRetryAttempt);
}
expect(_connector.isTcpTransportConnected, isFalse);
expect(_connector.isAutoReconnectScheduled, isTrue);
},
);
}
+34
View File
@@ -330,6 +330,40 @@ void main() {
);
expect(r.pendingCount, 2);
});
test('clearChannel stops a reused slot finishing with old bytes', () {
final oldSet = buildImageChunks(
payload: payloadOf(300, seed: 1),
metadata: stdMeta,
senderPrefix: senderA,
imgId: 9,
);
final newPayload = payloadOf(300, seed: 2);
final newSet = buildImageChunks(
payload: newPayload,
metadata: stdMeta,
senderPrefix: senderA,
imgId: 9,
);
expect(newSet.dataChunkCount, greaterThanOrEqualTo(2));
final failures = <ImageReassemblyFailure>[];
final r = ImageReassembler(onFailed: failures.add);
r.addChunk(oldSet.blobs[0], channelIndex: 3);
r.addChunk(oldSet.blobs[0], channelIndex: 4);
r.clearChannel(3);
expect(failures.single.key.channelIndex, 3);
expect(
failures.single.reason,
ImageReassemblyFailureReason.channelChanged,
);
expect(r.pendingKeys.single.channelIndex, 4);
// Without the clear, these would complete with the old chunk 0.
final dataBlobs = newSet.blobs.sublist(0, newSet.dataChunkCount);
expect(feed(r, dataBlobs.sublist(1), channelIndex: 3), isNull);
expect(feed(r, [dataBlobs[0]], channelIndex: 3)!.data, newPayload);
});
});
group('parity recovery', () {
+3 -2
View File
@@ -621,6 +621,7 @@ void main() {
() async {
final store = ChannelMessageStore()..publicKeyHex = '1234567890';
final channelIndex = 1;
const channelId = '0123456789abcdef';
final rawPath = Uint8List(64)
..[0] = 0xBB
@@ -640,11 +641,11 @@ void main() {
final prefs = PrefsManager.instance;
await prefs.setString(
'${store.keyFor}$channelIndex',
'${store.keyFor}_$channelId',
jsonEncode(messageJson),
);
final messages = await store.loadChannelMessages(channelIndex);
final messages = await store.loadChannelMessages(channelId);
expect(messages, hasLength(1));
expect(messages.first.pathLength, equals(1));
expect(
+6 -4
View File
@@ -36,6 +36,8 @@ ChannelMessage _ch(
channelIndex: 0,
);
const _channelId = '0123456789abcdef';
void main() {
final base = DateTime(2026, 10, 1, 12);
@@ -127,10 +129,10 @@ void main() {
await _init();
final store = ChannelMessageStore()..setPublicKeyHex = _device;
final received = base.add(const Duration(seconds: 42));
await store.saveChannelMessages(0, [
await store.saveChannelMessages(_channelId, [
_ch('one', timestamp: base, receivedAt: received),
]);
final loaded = await store.loadChannelMessages(0);
final loaded = await store.loadChannelMessages(_channelId);
expect(loaded.single.receivedAt, received);
expect(loaded.single.timestamp, base);
});
@@ -167,14 +169,14 @@ void main() {
'plainText': true,
};
await _init({
'channel_messages_${_device.substring(0, 10)}0': jsonEncode([
'channel_messages_${_device.substring(0, 10)}_$_channelId': jsonEncode([
record('old', past),
record('ahead', future),
]),
});
final store = ChannelMessageStore()..setPublicKeyHex = _device;
final before = DateTime.now();
final loaded = await store.loadChannelMessages(0);
final loaded = await store.loadChannelMessages(_channelId);
expect(loaded, hasLength(2));
expect(
loaded[0].receivedAt.millisecondsSinceEpoch,
@@ -0,0 +1,236 @@
import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
import 'package:meshcore_open/services/network_map/network_map_api_client.dart';
const _cell = {
'cell': '872830828ffffff',
'lat': 33.45,
'lon': -112.08,
'boundary': [
[33.46, -112.09],
[33.45, -112.07],
[33.44, -112.07],
[33.43, -112.08],
[33.44, -112.10],
[33.45, -112.10],
],
};
final _repeater = {
'key': 'AB' * 32,
'name': 'Hilltop RPT',
'type': 2,
'cell': _cell,
'locationSource': 'advert',
'confidence': 1.0,
'status': 'active',
'confirmed': true,
'sightings': 14,
'firstSeen': '2026-10-01T12:00:00Z',
'lastSeen': '2026-10-11T18:41:00Z',
};
const _bbox = NetworkMapBbox(
minLon: -113,
minLat: 33,
maxLon: -112,
maxLat: 34,
);
void main() {
group('visible area to request boxes', () {
List<List<double>>? boxes(double w, double s, double e, double n) =>
NetworkMapBbox.forVisibleArea(
west: w,
south: s,
east: e,
north: n,
)?.map((b) => [b.minLon, b.minLat, b.maxLon, b.maxLat]).toList();
test('normal area is one box', () {
expect(boxes(-112.5, 33, -111.5, 34), [
[-112.5, 33, -111.5, 34],
]);
});
test('wrapped across the antimeridian is split in two', () {
expect(boxes(179, -18, -179, -16), [
[179, -18, 180, -16],
[-180, -18, -179, -16],
]);
});
test('unwrapped longitudes beyond 180 are normalised and split', () {
expect(boxes(175, 0, 185, 5), [
[175, 0, 180, 5],
[-180, 0, -175, 5],
]);
expect(boxes(190, 0, 200, 5), [
[-170, 0, -160, 5],
]);
});
test('too large an area asks to zoom in', () {
expect(boxes(-130, 20, -60, 50), isNull);
expect(boxes(170, -40, -170, 40), isNull);
});
test('every box is valid for the server', () {
for (final b in boxes(179.5, 10, -170.25, 12)!) {
expect(b[0] < b[2], isTrue);
expect(b[0] >= -180 && b[2] <= 180, isTrue);
}
});
});
test('parses repeaters and sends bbox', () async {
late Uri requested;
final client = NetworkMapApiClient(
client: MockClient((request) async {
requested = request.url;
return http.Response(
jsonEncode({
'repeaters': [
_repeater,
{
..._repeater,
'key': 'cd' * 32,
'name': null,
'type': 3,
'locationSource': 'estimated',
'confidence': 0.4,
'status': 'stale',
'confirmed': false,
},
],
}),
200,
);
}),
);
final repeaters = await client.fetchRepeaters(_bbox);
expect(requested.path, '/v1/repeaters');
expect(requested.host, 'map.meshcoreopen.org');
expect(
requested.queryParameters['bbox'],
'-113.00000,33.00000,-112.00000,34.00000',
);
expect(requested.queryParameters['includeUnconfirmed'], 'true');
expect(repeaters, hasLength(2));
final first = repeaters.first;
expect(first.key, 'ab' * 32);
expect(first.name, 'Hilltop RPT');
expect(first.type, 2);
expect(first.cell.cell, '872830828ffffff');
expect(first.cell.center.latitude, 33.45);
expect(first.cell.boundary, hasLength(6));
expect(first.cell.boundary.first.latitude, 33.46);
expect(first.cell.boundary.first.longitude, -112.09);
expect(first.status, NetworkMapRepeaterStatus.active);
expect(first.confirmed, isTrue);
expect(first.isEstimated, isFalse);
expect(first.sightings, 14);
expect(first.lastSeen, DateTime.utc(2026, 10, 11, 18, 41));
final second = repeaters.last;
expect(second.name, isNull);
expect(second.type, 3);
expect(second.isEstimated, isTrue);
expect(second.status, NetworkMapRepeaterStatus.stale);
expect(second.confirmed, isFalse);
});
test('parses a single repeater and treats 404 as unknown', () async {
final client = NetworkMapApiClient(
client: MockClient((request) async {
if (request.url.path.endsWith('ab' * 32)) {
return http.Response(
jsonEncode({
..._repeater,
'links': 4,
'coverageCells': 12,
'reachableArea': '852830bffffffff',
}),
200,
);
}
return http.Response('{"error":"not_found"}', 404);
}),
);
final repeater = (await client.fetchRepeater('AB' * 32))!;
expect(repeater.links, 4);
expect(repeater.coverageCells, 12);
expect(repeater.reachableArea, '852830bffffffff');
expect(await client.fetchRepeater('ef' * 32), isNull);
});
test('parses links', () async {
late Uri requested;
final client = NetworkMapApiClient(
client: MockClient((request) async {
requested = request.url;
return http.Response(
jsonEncode({
'links': [
{
'a': 'ab' * 32,
'b': 'cd' * 32,
'aCell': _cell,
'bCell': _cell,
'packets': 120,
'snr': 6.5,
'confirmed': true,
},
{
'a': 'ab' * 32,
'b': 'ef' * 32,
'aCell': _cell,
'bCell': _cell,
'packets': 3,
'snr': null,
'confirmed': false,
},
],
}),
200,
);
}),
);
final links = await client.fetchLinks(_bbox, window: '24h');
expect(requested.path, '/v1/links');
expect(requested.queryParameters['window'], '24h');
expect(links, hasLength(2));
expect(links.first.packets, 120);
expect(links.first.snr, 6.5);
expect(links.first.confirmed, isTrue);
expect(links.first.aCell.boundary, hasLength(6));
expect(links.last.snr, isNull);
});
test('errors surface the status code', () async {
final client = NetworkMapApiClient(
client: MockClient((_) async => http.Response('bad', 400)),
);
expect(
() => client.fetchRepeaters(_bbox),
throwsA(isA<NetworkMapApiException>()),
);
});
test('bbox limit is 20 degrees per side', () {
expect(_bbox.isWithinLimit, isTrue);
expect(
const NetworkMapBbox(
minLon: -130,
minLat: 30,
maxLon: -105,
maxLat: 40,
).isWithinLimit,
isFalse,
);
});
}
@@ -0,0 +1,405 @@
import 'dart:convert';
import 'dart:typed_data';
import 'package:crypto/crypto.dart' as crypto;
import 'package:cryptography/cryptography.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/connector/meshcore_protocol.dart';
import 'package:meshcore_open/connector/raw_packet.dart';
import 'package:meshcore_open/services/network_map/network_map_records.dart';
const _packetFields = {
't',
'pt',
'rt',
'hw',
'path',
'snr',
'rssi',
'size',
'h',
'scoped',
};
const _advertFields = {
't',
'key',
'type',
'name',
'loc',
'hidden',
'snr',
'rssi',
'rt',
'hw',
'path',
};
final _receivedAt = DateTime.utc(2026, 10, 11, 18, 41, 37);
const _transportCodes = [0xDE, 0xAD, 0xBE, 0xEF];
String _hex(List<int> bytes) =>
bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join();
/// `[0x88][snr*4][rssi][header][transport?][path_len][path][payload]`.
Uint8List _rxFrame({
required int payloadType,
int routeType = 1,
int snrQuarters = 29,
int rssi = -92,
int pathLenRaw = 0,
List<int> path = const [],
required List<int> payload,
}) {
return Uint8List.fromList([
pushCodeLogRxData,
snrQuarters & 0xFF,
rssi & 0xFF,
(payloadType << 2) | routeType,
if (routeType == 0 || routeType == 3) ..._transportCodes,
pathLenRaw,
...path,
...payload,
]);
}
/// Payload whose every 3-byte window is distinctive, so any leak of it into
/// a record would show up as a substring.
List<int> _secretPayload(int length) =>
List<int>.generate(length, (i) => (0x5A + i * 37) & 0xFF);
Future<List<int>> _signedAdvertPayload({
required SimpleKeyPair keyPair,
required int type,
double? lat,
double? lon,
String? name,
bool corruptSignature = false,
List<int> unsignedSuffix = const [],
}) async {
final publicKey = (await keyPair.extractPublicKey()).bytes;
final timestamp = [0x10, 0x20, 0x30, 0x40];
var flags = type;
final appData = <int>[];
if (lat != null && lon != null) {
flags |= 0x10;
final loc = ByteData(8)
..setInt32(0, (lat * 1e6).round(), Endian.little)
..setInt32(4, (lon * 1e6).round(), Endian.little);
appData.addAll(loc.buffer.asUint8List());
}
if (name != null) {
flags |= 0x80;
appData.addAll(utf8.encode(name));
}
appData.insert(0, flags);
final signature = await Ed25519().sign([
...publicKey,
...timestamp,
...appData,
], keyPair: keyPair);
final sigBytes = List<int>.from(signature.bytes);
if (corruptSignature) sigBytes[10] ^= 0x01;
return [
...publicKey,
...timestamp,
...sigBytes,
...appData,
...unsignedSuffix,
];
}
void main() {
group('packet records', () {
test('every payload type yields header-only fields', () {
for (var pt = 0; pt < 16; pt++) {
for (final rt in [0, 1, 2, 3]) {
final payload = _secretPayload(40);
final frame = _rxFrame(
payloadType: pt,
routeType: rt,
pathLenRaw: 0x42, // 2 hops, 2-byte hashes
path: const [0xA1, 0xA2, 0xB1, 0xB2],
payload: payload,
);
final record = buildPacketRecord(frame, _receivedAt)!;
final json = record.toJson();
expect(json.keys.toSet(), _packetFields);
expect(json['pt'], pt);
expect(json['rt'], rt);
expect(json['hw'], 2);
expect(json['path'], 'a1a2b1b2');
expect(json['scoped'], rt == 0 || rt == 3);
expect(json['h'], computePacketHash(pt, Uint8List.fromList(payload)));
// Nothing outside the hash may carry payload or transport bytes.
final withoutHash = jsonEncode({...json}..remove('h'));
expect(withoutHash, isNot(contains('dead')));
expect(withoutHash, isNot(contains('beef')));
for (var i = 0; i + 3 <= payload.length; i++) {
expect(
withoutHash,
isNot(contains(_hex(payload.sublist(i, i + 3)))),
);
}
}
}
});
test('group text: channel hash and MAC never appear', () {
// [channel_hash][MAC x2][ciphertext]
final payload = [0x7C, 0x3E, 0x91, ..._secretPayload(32)];
final record = buildPacketRecord(
_rxFrame(payloadType: payloadTypeGRPTXT, payload: payload),
_receivedAt,
)!;
final json = jsonEncode(record.toJson()..remove('h'));
expect(json, isNot(contains('7c')));
expect(json, isNot(contains('3e91')));
expect(record.path, '');
});
test('direct message: source and destination hashes never appear', () {
// [dest_hash][src_hash][MAC x2][ciphertext]
final payload = [0xD7, 0x5C, 0x11, 0x22, ..._secretPayload(24)];
final record = buildPacketRecord(
_rxFrame(
payloadType: payloadTypeTXTMSG,
routeType: 2,
payload: payload,
),
_receivedAt,
)!;
final json = jsonEncode(record.toJson()..remove('h'));
expect(json, isNot(contains('d7')));
expect(json, isNot(contains('5c')));
});
test('snr is reported in quarter-dB steps and rssi passes through', () {
final record = buildPacketRecord(
_rxFrame(payloadType: 2, snrQuarters: -23, rssi: -110, payload: [1]),
_receivedAt,
)!;
expect(record.snr, -5.75);
expect(record.rssi, -110);
});
test('t is rounded down to the minute', () {
final record = buildPacketRecord(
_rxFrame(payloadType: 2, payload: [1]),
_receivedAt,
)!;
expect(record.t % 60, 0);
expect(
record.t,
DateTime.utc(2026, 10, 11, 18, 41).millisecondsSinceEpoch ~/ 1000,
);
});
test('size is the raw packet length rounded up to 16', () {
expect(roundUpPacketSize(0), 0);
expect(roundUpPacketSize(1), 16);
expect(roundUpPacketSize(16), 16);
expect(roundUpPacketSize(17), 32);
expect(roundUpPacketSize(48), 48);
expect(roundUpPacketSize(49), 64);
expect(roundUpPacketSize(255), 256);
// header + path_len + 30 payload bytes = 32 raw bytes.
final record = buildPacketRecord(
_rxFrame(payloadType: 2, payload: _secretPayload(30)),
_receivedAt,
)!;
expect(record.size, 32);
final scoped = buildPacketRecord(
_rxFrame(payloadType: 2, routeType: 0, payload: _secretPayload(30)),
_receivedAt,
)!;
expect(scoped.size, 48); // + 4 transport bytes = 36
});
test('hash matches the firmware packet hash', () {
final payload = Uint8List.fromList(_secretPayload(20));
final digest = crypto.sha256.convert([5, ...payload]).bytes;
final record = buildPacketRecord(
_rxFrame(payloadType: 5, payload: payload),
_receivedAt,
)!;
expect(record.h, _hex(digest.sublist(0, 8)));
expect(record.h, computePacketHash(5, payload));
expect(RegExp(r'^[0-9a-f]{16}$').hasMatch(record.h), isTrue);
});
test('unsupported hash width, oversized path and other frames dropped', () {
// Hash width code 3 -> 4-byte hashes.
expect(
buildPacketRecord(
_rxFrame(
payloadType: 2,
pathLenRaw: 0xC1,
path: const [1, 2, 3, 4],
payload: [1],
),
_receivedAt,
),
isNull,
);
// 22 hops of 3 bytes = 66 bytes > 64.
expect(
buildPacketRecord(
_rxFrame(
payloadType: 2,
pathLenRaw: 0x80 | 22,
path: List<int>.filled(66, 7),
payload: [1],
),
_receivedAt,
),
isNull,
);
expect(
buildPacketRecord(Uint8List.fromList([0x80, 1, 2, 3]), _receivedAt),
isNull,
);
expect(
buildPacketRecord(
Uint8List.fromList([pushCodeLogRxData, 1]),
_receivedAt,
),
isNull,
);
});
});
group('advert records', () {
late SimpleKeyPair keyPair;
late String keyHex;
setUpAll(() async {
keyPair = await Ed25519().newKeyPairFromSeed(List<int>.filled(32, 7));
keyHex = _hex((await keyPair.extractPublicKey()).bytes);
});
Future<Uint8List> advertFrame({
required int type,
double? lat,
double? lon,
String? name,
bool corrupt = false,
List<int> unsignedSuffix = const [],
}) async {
return _rxFrame(
payloadType: payloadTypeADVERT,
pathLenRaw: 0x01,
path: const [0xA1],
payload: await _signedAdvertPayload(
keyPair: keyPair,
type: type,
lat: lat,
lon: lon,
name: name,
corruptSignature: corrupt,
unsignedSuffix: unsignedSuffix,
),
);
}
test('verified repeater advert: snapped location, name, key', () async {
final frame = await advertFrame(
type: advTypeRepeater,
lat: 33.448376,
lon: -112.074036,
name: 'Hilltop RPT',
);
final advert = (await buildAdvertRecord(frame, _receivedAt))!;
final json = advert.toJson();
expect(json.keys.toSet(), _advertFields);
expect(json['key'], keyHex);
expect(json['type'], 2);
expect(json['name'], 'Hilltop RPT');
expect(json['loc'], {'lat': 33.45, 'lon': -112.080261});
expect(json['hidden'], false);
expect(json['snr'], 7.25);
expect(json['rssi'], -92);
expect(json['rt'], 1);
expect(json['hw'], 1);
expect(json['path'], 'a1');
expect(json['t'] % 60, 0);
// Exact coordinates never leave the phone.
expect(jsonEncode(json), isNot(contains('448376')));
// The same frame still produces a header-only packet record.
expect(buildPacketRecord(frame, _receivedAt)!.pt, payloadTypeADVERT);
});
test('room server adverts are uploaded too', () async {
final frame = await advertFrame(type: advTypeRoom, name: 'Room');
final advert = (await buildAdvertRecord(frame, _receivedAt))!;
expect(advert.type, 3);
expect(advert.loc, isNull);
});
test('chat and sensor adverts are packet records only', () async {
for (final type in [advTypeChat, advTypeSensor]) {
final frame = await advertFrame(
type: type,
lat: 47.6,
lon: -122.3,
name: 'Alice',
);
expect(await buildAdvertRecord(frame, _receivedAt), isNull);
final packet = buildPacketRecord(frame, _receivedAt)!;
final json = jsonEncode(packet.toJson());
expect(json, isNot(contains(keyHex.substring(0, 6))));
expect(json, isNot(contains('Alice')));
}
});
test('names containing the no-entry sign are hidden', () async {
final frame = await advertFrame(
type: advTypeRepeater,
lat: 47.6,
lon: -122.3,
name: 'Secret \u{1F6AB}',
);
final advert = (await buildAdvertRecord(frame, _receivedAt))!;
final json = advert.toJson();
expect(json['hidden'], true);
expect(json['name'], isNull);
expect(json['loc'], isNull);
expect(json['key'], keyHex);
});
test('bytes after the signed 32 app-data bytes are ignored', () async {
// flags (1) + location (8) + 23-byte name fill the signed 32 bytes.
const name = 'Hilltop Repeater North1';
expect(utf8.encode(name).length, 23);
final frame = await advertFrame(
type: advTypeRepeater,
lat: 47.6,
lon: -122.3,
name: name,
unsignedSuffix: utf8.encode(' \u{1F6AB} evil'),
);
final advert = (await buildAdvertRecord(frame, _receivedAt))!;
final json = advert.toJson();
expect(json['hidden'], false);
expect(json['name'], name);
expect(json['loc'], isNotNull);
});
test('adverts with a bad signature are dropped', () async {
final frame = await advertFrame(
type: advTypeRepeater,
name: 'Forged',
corrupt: true,
);
expect(await buildAdvertRecord(frame, _receivedAt), isNull);
});
test('non-advert packets never produce adverts', () async {
final frame = _rxFrame(payloadType: 5, payload: _secretPayload(120));
expect(await buildAdvertRecord(frame, _receivedAt), isNull);
});
});
}
@@ -0,0 +1,137 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
import 'package:meshcore_open/connector/meshcore_connector.dart';
import 'package:meshcore_open/services/app_settings_service.dart';
import 'package:meshcore_open/services/network_map/network_map_records.dart';
import 'package:meshcore_open/services/network_map/network_map_upload_service.dart';
import 'dart:async';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
setUp(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
});
test('off by default and never listens without a connected radio', () async {
final connector = MeshCoreConnector();
final settings = AppSettingsService();
await settings.loadSettings();
var requests = 0;
final service = NetworkMapUploadService(
connector: connector,
settings: settings,
client: MockClient((_) async {
requests++;
return http.Response('{}', 202);
}),
);
addTearDown(() {
service.dispose();
connector.dispose();
});
expect(service.enabled, isFalse);
expect(service.isActive, isFalse);
await service.setEnabled(true);
expect(service.enabled, isTrue);
expect(settings.settings.networkMapUploadEnabled, isTrue);
expect(service.isActive, isFalse);
expect(service.lastUploadAt, isNull);
expect(service.packetsSentToday, 0);
expect(requests, 0);
});
group('withdrawing consent mid-upload', () {
NetworkMapPacketRecord packet() => NetworkMapPacketRecord(
t: DateTime.now().millisecondsSinceEpoch ~/ 60000 * 60,
pt: 5,
rt: 1,
hw: 1,
path: 'aa',
snr: 6.5,
rssi: -90,
size: 48,
h: '0011223344556677',
scoped: false,
);
Future<(NetworkMapUploadService, AppSettingsService)> setUpService(
MockClient client,
) async {
final connector = _ConnectedConnector();
final settings = AppSettingsService();
await settings.loadSettings();
await settings.setNetworkMapUploadEnabled(true);
final service = NetworkMapUploadService(
connector: connector,
settings: settings,
client: client,
);
addTearDown(() {
service.dispose();
connector.dispose();
});
return (service, settings);
}
test(
'nothing is sent when sharing is turned off before the POST',
() async {
var requests = 0;
final (service, settings) = await setUpService(
MockClient((_) async {
requests++;
return http.Response('{}', 202);
}),
);
service.queuePacketForTest(packet());
final upload = service.uploadNowForTest();
await settings.setNetworkMapUploadEnabled(false);
await upload;
expect(requests, 0);
expect(service.queuedPacketCount, 0);
expect(service.lastUploadAt, isNull);
},
);
test('a late response never touches the refilled queue', () async {
final response = Completer<http.Response>();
final posted = Completer<void>();
final (service, settings) = await setUpService(
MockClient((_) {
posted.complete();
return response.future;
}),
);
service.queuePacketForTest(packet());
final upload = service.uploadNowForTest();
await posted.future;
// Off and on again while the first POST is in flight, then new records.
await settings.setNetworkMapUploadEnabled(false);
await settings.setNetworkMapUploadEnabled(true);
service.queuePacketForTest(packet());
service.queuePacketForTest(packet());
response.complete(http.Response('{}', 202));
await upload;
expect(service.queuedPacketCount, 2);
expect(service.lastUploadAt, isNull);
expect(service.packetsSentToday, 0);
});
});
}
class _ConnectedConnector extends MeshCoreConnector {
@override
bool get isConnected => true;
}
@@ -0,0 +1,216 @@
import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/services/network_map/network_map_records.dart';
import 'package:meshcore_open/services/network_map/network_map_upload_service.dart';
import 'package:shared_preferences/shared_preferences.dart';
NetworkMapPacketRecord _packet(int t) => NetworkMapPacketRecord(
t: t,
pt: 5,
rt: 1,
hw: 1,
path: 'a1b2c3',
snr: 7.25,
rssi: -92,
size: 48,
h: '0123456789abcdef',
scoped: false,
);
NetworkMapAdvertRecord _advert(int t, String key) => NetworkMapAdvertRecord(
t: t,
key: key,
type: 2,
name: 'Hilltop RPT',
loc: const NetworkMapLoc(33.47, -112.068234),
hidden: false,
snr: 9.5,
rssi: -80,
rt: 1,
hw: 1,
path: 'a1',
);
void main() {
group('upload body', () {
test('matches the contract field-for-field', () {
final body = buildUploadBody(
installId: 'AAAAAAAAAAAAAAAAAAAAAA',
app: 'meshcore-open/9.5.0',
loc: NetworkMapLoc.snapped(33.448376, -112.074036),
preset: NetworkMapPreset.fromRadio(
freqKhz: 910525,
bwHz: 62500,
sf: 7,
cr: 5,
),
listenSeconds: 60,
packets: [_packet(1791770400)],
adverts: [_advert(1791770400, 'ab' * 32)],
);
final decoded =
jsonDecode(jsonEncode(body)) as Map<String, dynamic>; // round trip
expect(decoded, {
'v': 1,
'installId': 'AAAAAAAAAAAAAAAAAAAAAA',
'token': null,
'app': 'meshcore-open/9.5.0',
'loc': {'lat': 33.45, 'lon': -112.080261},
'preset': {'freqKhz': 910525, 'bwKhz': 62.5, 'sf': 7, 'cr': 5},
'listenSeconds': 60,
'packets': [
{
't': 1791770400,
'pt': 5,
'rt': 1,
'hw': 1,
'path': 'a1b2c3',
'snr': 7.25,
'rssi': -92,
'size': 48,
'h': '0123456789abcdef',
'scoped': false,
},
],
'adverts': [
{
't': 1791770400,
'key': 'ab' * 32,
'type': 2,
'name': 'Hilltop RPT',
'loc': {'lat': 33.47, 'lon': -112.068234},
'hidden': false,
'snr': 9.5,
'rssi': -80,
'rt': 1,
'hw': 1,
'path': 'a1',
},
],
});
});
test('heartbeat has null loc/preset and empty lists', () {
final body = buildUploadBody(
installId: 'x',
app: 'meshcore-open',
loc: null,
preset: null,
listenSeconds: 900,
packets: const [],
adverts: const [],
);
expect(body['loc'], isNull);
expect(body['preset'], isNull);
expect(body['listenSeconds'], 600);
expect(body['packets'], isEmpty);
expect(body['adverts'], isEmpty);
});
test('preset maps radio units and rejects unknown values', () {
final preset = NetworkMapPreset.fromRadio(
freqKhz: 869525,
bwHz: 250000,
sf: 11,
cr: 1,
)!;
expect(preset.toJson(), {
'freqKhz': 869525,
'bwKhz': 250,
'sf': 11,
'cr': 5,
});
expect(
NetworkMapPreset.fromRadio(
freqKhz: 869525,
bwHz: 41700,
sf: 8,
cr: 8,
)!.bwKhz,
41.7,
);
expect(
NetworkMapPreset.fromRadio(freqKhz: 869525, bwHz: 12345, sf: 7, cr: 5),
isNull,
);
expect(
NetworkMapPreset.fromRadio(freqKhz: 50, bwHz: 62500, sf: 7, cr: 5),
isNull,
);
expect(NetworkMapPreset.fromRadio(), isNull);
});
});
group('install ID', () {
test('random, 16 bytes, rotated every 24 h', () async {
SharedPreferences.setMockInitialValues({});
final prefs = await SharedPreferences.getInstance();
var now = DateTime(2026, 10, 11, 12);
final installId = NetworkMapInstallId(prefs, now: () => now);
final first = installId.current();
expect(first.contains('='), isFalse);
expect(RegExp(r'^[A-Za-z0-9_-]+$').hasMatch(first), isTrue);
expect(base64Url.decode('$first=='), hasLength(16));
now = now.add(const Duration(hours: 23, minutes: 59));
expect(installId.current(), first);
now = now.add(const Duration(minutes: 2));
final second = installId.current();
expect(second, isNot(first));
expect(base64Url.decode('$second=='), hasLength(16));
now = now.add(const Duration(hours: 1));
expect(installId.current(), second);
});
});
group('upload queue', () {
final now = DateTime.utc(2026, 10, 11, 18, 41, 30);
final minute = networkMapMinute(now);
test('batches respect the contract caps', () {
final queue = NetworkMapUploadQueue();
for (var i = 0; i < 2500; i++) {
queue.addPacket(_packet(minute), now);
}
for (var i = 0; i < 250; i++) {
queue.addAdvert(
_advert(minute, i.toRadixString(16).padLeft(64, '0')),
now,
);
}
final batch = queue.peekBatch();
expect(batch.packets, hasLength(2000));
expect(batch.adverts, hasLength(200));
queue.remove(batch.packets.length, batch.adverts.length);
final rest = queue.peekBatch();
expect(rest.packets, hasLength(500));
expect(rest.adverts, hasLength(50));
});
test('one advert per key is kept', () {
final queue = NetworkMapUploadQueue();
queue.addAdvert(_advert(minute - 60, 'a' * 64), now);
queue.addAdvert(_advert(minute, 'a' * 64), now);
expect(queue.advertCount, 1);
expect(queue.peekBatch().adverts.single.t, minute);
});
test('drops data the server would reject or older than an hour', () {
final queue = NetworkMapUploadQueue();
queue.addPacket(_packet(minute), now);
queue.addPacket(_packet(minute - 61 * 60), now);
queue.addPacket(
_packet(minute),
now.subtract(const Duration(hours: 1, minutes: 1)),
);
queue.dropExpired(now);
expect(queue.packetCount, 1);
expect(queue.peekBatch().packets.single.t, minute);
});
});
}
+54 -2
View File
@@ -210,6 +210,54 @@ void main() {
expect(h.decoder.calls, 1);
});
test('a stream started before its slot had an ID picks one up', () async {
final h = _build();
final set = buildImageChunks(
payload: _payload(kImageChunkFirstCapacity + kImageChunkCapacity + 1),
metadata: const ImageStreamMetadata(rate: ImageCodecRatePoint.standard),
senderPrefix: kSender,
imgId: 5,
);
expect(set.dataChunkCount, 3);
final first = await h.store.handleOutcome(
h.reassembler.addChunk(set.blobs[0], channelIndex: 3),
channelIndex: 3,
);
expect(first!.channelId, isNull);
// A second data chunk of three neither completes nor recovers it.
final second = await h.store.handleOutcome(
h.reassembler.addChunk(set.blobs[1], channelIndex: 3),
channelIndex: 3,
channelId: 'chan-id',
);
expect(second!.state, ReceivedImageState.receiving);
expect(second.streamId, first.streamId);
expect(second.channelId, 'chan-id');
});
test('a stream completed after its slot got an ID keeps it', () async {
final h = _build();
final set = buildImageChunks(
payload: _payload(kImageChunkFirstCapacity + 1),
metadata: const ImageStreamMetadata(rate: ImageCodecRatePoint.standard),
senderPrefix: kSender,
imgId: 6,
);
final first = await h.store.handleOutcome(
h.reassembler.addChunk(set.blobs[0], channelIndex: 3),
channelIndex: 3,
);
expect(first!.channelId, isNull);
final done = await h.store.handleOutcome(
h.reassembler.addChunk(set.blobs[1], channelIndex: 3),
channelIndex: 3,
channelId: 'chan-id',
);
expect(done!.streamId, first.streamId);
expect(done.channelId, 'chan-id');
});
test('two-chunk image reports 1 of 2 while incomplete', () async {
final h = _build();
final set = buildImageChunks(
@@ -962,7 +1010,7 @@ void main() {
group('deletion hooks', () {
test(
'deleteImagesForChannel reclaims every image of one conversation',
'deleteImagesForChannelId reclaims every image of one conversation',
() async {
final h = _build();
final a = await _completeOne(h, imgId: 130);
@@ -972,6 +1020,7 @@ void main() {
// A third image on another channel must survive.
final other = await h.store.registerOutgoing(
channelIndex: 9,
channelId: 'fedcba9876543210',
senderPrefix: kSelf,
imgId: 5,
previewPng: Uint8List.fromList(List<int>.filled(32, 2)),
@@ -979,7 +1028,7 @@ void main() {
chunkCount: 1,
);
final removed = await h.store.deleteImagesForChannel(3);
final removed = await h.store.deleteImagesForChannelId(_channel3Id);
expect(removed, containsAll(<String>[a.streamId, b.streamId]));
expect(h.store.entryFor(a.streamId), isNull);
expect(h.store.entryFor(b.streamId), isNull);
@@ -1480,7 +1529,10 @@ Future<ReceivedImageEntry> _completeOne(
final entry = await h.store.handleOutcome(
h.reassembler.addChunk(set.blobs[0], channelIndex: 3, now: h.clock()),
channelIndex: 3,
channelId: _channel3Id,
at: h.clock(),
);
return entry!;
}
const _channel3Id = '0123456789abcdef';
@@ -0,0 +1,372 @@
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/models/channel_message.dart';
import 'package:meshcore_open/models/image_codec_support.dart';
import 'package:meshcore_open/services/received_image_store.dart';
import 'package:meshcore_open/storage/channel_message_store.dart';
import 'package:meshcore_open/storage/channel_order_store.dart';
import 'package:meshcore_open/storage/channel_region_store.dart';
import 'package:meshcore_open/storage/channel_settings_store.dart';
import 'package:meshcore_open/storage/channel_storage_migration.dart';
import 'package:meshcore_open/storage/channel_store.dart';
import 'package:meshcore_open/storage/legacy_key_migration.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:shared_preferences/shared_preferences.dart';
const _deviceA = 'aaaaaaaaaa0123456789';
const _deviceB = 'bbbbbbbbbb0123456789';
const _scopeA = 'aaaaaaaaaa';
final _pskOne = Uint8List.fromList(List<int>.generate(16, (i) => i + 1));
final _pskTwo = Uint8List.fromList(List<int>.generate(16, (i) => 100 + i));
final _idOne = Channel.storageIdForPsk(_pskOne)!;
final _idTwo = Channel.storageIdForPsk(_pskTwo)!;
Future<void> _init([Map<String, Object> values = const {}]) async {
SharedPreferences.setMockInitialValues(values);
PrefsManager.reset();
await PrefsManager.initialize();
ChannelMessageStore().forgetArchive();
}
ChannelMessage _ch(String text, int i) => ChannelMessage(
senderKey: null,
senderName: 'Bob',
text: text,
timestamp: DateTime.fromMillisecondsSinceEpoch(1000 * i),
isOutgoing: false,
status: ChannelMessageStatus.sent,
channelIndex: 0,
messageId: '$text-$i',
);
String _storedMessages(List<String> texts) => jsonEncode([
for (var i = 0; i < texts.length; i++)
{
'senderName': 'Bob',
'text': texts[i],
'timestamp': 1000 * (i + 1),
'isOutgoing': false,
'status': ChannelMessageStatus.sent.index,
'messageId': '${texts[i]}-$i',
'plainText': true,
},
]);
String _cachedChannels(Map<int, Uint8List> slots) => jsonEncode([
for (final entry in slots.entries)
{
'index': entry.key,
'name': 'ch${entry.key}',
'psk': base64Encode(entry.value),
'unreadCount': 0,
},
]);
void main() {
tearDown(scopesWithoutLegacyMigration.clear);
group('channel ID', () {
test('is stable, 16 hex chars, and absent for an empty slot', () {
expect(_idOne, hasLength(16));
expect(_idOne, matches(RegExp(r'^[0-9a-f]{16}$')));
expect(Channel.storageIdForPsk(Uint8List.fromList(_pskOne)), _idOne);
expect(_idOne, isNot(_idTwo));
expect(Channel.storageIdForPsk(Uint8List(16)), isNull);
expect(Channel.empty(3).storageId, isNull);
expect(Channel(index: 5, name: 'x', psk: _pskOne).storageId, _idOne);
});
});
group('ID-keyed stores', () {
test('messages save, load and clear by channel ID', () async {
await _init();
final store = ChannelMessageStore()..setPublicKeyHex = _deviceA;
await store.saveChannelMessages(_idOne, [_ch('one', 1)]);
await store.saveChannelMessages(_idTwo, [_ch('two', 1)]);
expect((await store.loadChannelMessages(_idOne)).single.text, 'one');
expect((await store.loadChannelMessages(_idTwo)).single.text, 'two');
expect(
PrefsManager.instance.containsKey(
'channel_messages_${_scopeA}_$_idOne',
),
isTrue,
);
await store.clearChannelMessages(_idOne);
expect(await store.loadChannelMessages(_idOne), isEmpty);
expect(await store.loadChannelMessages(_idTwo), hasLength(1));
});
test('the same channel ID is isolated per radio scope', () async {
await _init();
final a = ChannelMessageStore()..setPublicKeyHex = _deviceA;
final b = ChannelMessageStore()..setPublicKeyHex = _deviceB;
await a.saveChannelMessages(_idOne, [_ch('a', 1)]);
expect(await b.loadChannelMessages(_idOne), isEmpty);
final settingsB = ChannelSettingsStore()..setPublicKeyHex = _deviceB;
final settingsA = ChannelSettingsStore()..setPublicKeyHex = _deviceA;
await settingsA.saveSmazEnabled(_idOne, true);
expect(await settingsA.loadSmazEnabled(_idOne), isTrue);
expect(await settingsB.loadSmazEnabled(_idOne), isFalse);
});
test('the archive follows the channel ID', () async {
await _init();
final store = ChannelMessageStore()..setPublicKeyHex = _deviceA;
store.setArchived(_idOne, [_ch('old', 1), _ch('older', 2)]);
expect(store.archivedCount(_idOne), 2);
expect(store.archivedCount(_idTwo), isNull);
await store.saveChannelMessages(_idOne, [_ch('new', 3)]);
expect((await store.loadChannelMessages(_idOne)).map((m) => m.text), [
'old',
'older',
'new',
]);
store.forgetArchive(_idOne);
expect(store.archivedCount(_idOne), isNull);
});
test('settings, region and order are keyed by channel ID', () async {
await _init();
final settings = ChannelSettingsStore()..setPublicKeyHex = _deviceA;
await settings.saveCyr2LatEnabled(_idOne, true);
await settings.saveUrlImagesEnabled(_idOne, true);
await settings.saveCyr2LatProfileId(_idOne, 'sr');
expect(await settings.loadCyr2LatEnabled(_idOne), isTrue);
expect(await settings.loadUrlImagesEnabled(_idOne), isTrue);
expect(await settings.loadCyr2LatProfileId(_idOne), 'sr');
expect(await settings.loadCyr2LatEnabled(_idTwo), isFalse);
await settings.clearChannel(_idOne);
expect(await settings.loadCyr2LatEnabled(_idOne), isFalse);
expect(await settings.loadCyr2LatProfileId(_idOne), isNull);
final region = ChannelRegionStore()..setPublicKeyHex = _deviceA;
await region.saveRegion(_idOne, 'EU');
expect(await region.loadRegion(_idOne), 'EU');
expect(await region.loadRegion(_idTwo), '');
await ChannelRegionStore.clearRegionEverywhere('EU');
expect(await region.loadRegion(_idOne), '');
final order = ChannelOrderStore()..setPublicKeyHex = _deviceA;
await order.saveChannelOrder([_idTwo, _idOne]);
expect(await order.loadChannelOrder(), [_idTwo, _idOne]);
});
});
group('migration', () {
Map<String, Object> legacyValues() => {
'channels$_scopeA': _cachedChannels({0: _pskOne, 2: _pskTwo}),
'channel_messages_${_scopeA}0': _storedMessages(['hello']),
'channel_messages_2': _storedMessages(['unscoped']),
'channel_messages_${_scopeA}5': _storedMessages(['orphan']),
'channel_smaz_${_scopeA}0': true,
'channel_cyr2lat_${_scopeA}2': true,
'channel_url_images_${_scopeA}2': true,
'channel_cyr2lat_${_scopeA}profile_2': 'sr',
'channel_region_${_scopeA}0': 'EU',
'channel_order_$_scopeA': jsonEncode([2, 5, 0]),
};
test('moves messages, settings, region and order to channel IDs', () async {
await _init(legacyValues());
final mapping = await ChannelStorageMigration.migrate(_scopeA);
expect(mapping, {0: _idOne, 2: _idTwo});
final messages = ChannelMessageStore()..setPublicKeyHex = _deviceA;
expect((await messages.loadChannelMessages(_idOne)).single.text, 'hello');
// The unscoped legacy key migrates too.
expect(
(await messages.loadChannelMessages(_idTwo)).single.text,
'unscoped',
);
final settings = ChannelSettingsStore()..setPublicKeyHex = _deviceA;
expect(await settings.loadSmazEnabled(_idOne), isTrue);
expect(await settings.loadSmazEnabled(_idTwo), isFalse);
expect(await settings.loadCyr2LatEnabled(_idTwo), isTrue);
expect(await settings.loadUrlImagesEnabled(_idTwo), isTrue);
expect(await settings.loadCyr2LatProfileId(_idTwo), 'sr');
final region = ChannelRegionStore()..setPublicKeyHex = _deviceA;
expect(await region.loadRegion(_idOne), 'EU');
final order = ChannelOrderStore()..setPublicKeyHex = _deviceA;
expect(await order.loadChannelOrder(), [_idTwo, _idOne]);
final prefs = PrefsManager.instance;
expect(prefs.containsKey('channel_messages_${_scopeA}0'), isFalse);
expect(prefs.containsKey('channel_messages_2'), isFalse);
expect(prefs.containsKey('channel_smaz_${_scopeA}0'), isFalse);
expect(prefs.containsKey('channel_region_${_scopeA}0'), isFalse);
// A slot with no cached PSK is left alone.
expect(prefs.containsKey('channel_messages_${_scopeA}5'), isTrue);
// The slot map is seeded for the first post-migration diff.
expect(
await (ChannelStore()..setPublicKeyHex = _scopeA).loadSlotChannelIds(),
{0: _idOne, 2: _idTwo},
);
});
test('runs once per radio', () async {
await _init(legacyValues());
await ChannelStorageMigration.migrate(_scopeA);
await PrefsManager.instance.setString(
'channel_messages_${_scopeA}0',
_storedMessages(['late']),
);
expect(await ChannelStorageMigration.migrate(_scopeA), isEmpty);
final messages = ChannelMessageStore()..setPublicKeyHex = _deviceA;
expect((await messages.loadChannelMessages(_idOne)).single.text, 'hello');
expect(
PrefsManager.instance.containsKey('channel_messages_${_scopeA}0'),
isTrue,
);
});
test('a rerun after an interrupted migration loses and duplicates '
'nothing', () async {
// Killed after the new keys were written but before the old ones
// were removed and the done flag set.
await _init({
'channels$_scopeA': _cachedChannels({0: _pskOne, 2: _pskTwo}),
'channel_messages_${_scopeA}0': _storedMessages(['hello']),
'channel_messages_${_scopeA}_$_idOne': _storedMessages(['hello']),
'channel_order_$_scopeA': jsonEncode([_idTwo, _idOne]),
});
await ChannelStorageMigration.migrate(_scopeA);
final messages = ChannelMessageStore()..setPublicKeyHex = _deviceA;
expect((await messages.loadChannelMessages(_idOne)).map((m) => m.text), [
'hello',
]);
final order = ChannelOrderStore()..setPublicKeyHex = _deviceA;
expect(await order.loadChannelOrder(), [_idTwo, _idOne]);
expect(
PrefsManager.instance.containsKey('channel_messages_${_scopeA}0'),
isFalse,
);
});
test('images are stamped before the migration is marked done', () async {
await _init(legacyValues());
await expectLater(
ChannelStorageMigration.migrate(
_scopeA,
beforeDone: (_) async => throw StateError('killed'),
),
throwsStateError,
);
// Not marked done, so the next launch stamps again.
Map<int, String>? stamped;
await ChannelStorageMigration.migrate(
_scopeA,
beforeDone: (slotIds) async => stamped = slotIds,
);
expect(stamped, {0: _idOne, 2: _idTwo});
// Data moved by the first run is still there.
final messages = ChannelMessageStore()..setPublicKeyHex = _deviceA;
expect((await messages.loadChannelMessages(_idOne)).single.text, 'hello');
});
test('skips a scope that must not adopt legacy data', () async {
await _init(legacyValues());
scopesWithoutLegacyMigration.add(_scopeA);
expect(await ChannelStorageMigration.migrate(_scopeA), isEmpty);
final prefs = PrefsManager.instance;
expect(prefs.containsKey('channel_messages_${_scopeA}0'), isTrue);
expect(prefs.containsKey('channel_storage_v2_$_scopeA'), isFalse);
expect(prefs.containsKey('channel_messages_2'), isTrue);
});
test('two slots with the same PSK merge into one history', () async {
await _init({
'channels$_scopeA': _cachedChannels({1: _pskOne, 4: _pskOne}),
'channel_messages_${_scopeA}1': _storedMessages(['first']),
'channel_messages_${_scopeA}4': _storedMessages(['second', 'third']),
});
expect(await ChannelStorageMigration.migrate(_scopeA), {
1: _idOne,
4: _idOne,
});
final messages = ChannelMessageStore()..setPublicKeyHex = _deviceA;
expect(
(await messages.loadChannelMessages(_idOne)).map((m) => m.text),
unorderedEquals(['first', 'second', 'third']),
);
});
});
group('received images', () {
final png = Uint8List.fromList(List<int>.filled(32, 7));
Future<ReceivedImageEntry> outgoing(
ReceivedImageStore store, {
required int slot,
String? channelId,
int imgId = 1,
}) => store.registerOutgoing(
channelIndex: slot,
channelId: channelId,
senderPrefix: 0x1234,
imgId: imgId,
previewPng: png,
rate: AeicRatePoint.ft32,
chunkCount: 1,
);
test('an entry round-trips its channel ID', () async {
final store = ReceivedImageStore(decoder: null);
final entry = await outgoing(store, slot: 2, channelId: _idOne);
final json = entry.toJson();
expect(json['channelId'], _idOne);
expect(ReceivedImageEntry.fromJson(json).channelId, _idOne);
expect(ReceivedImageEntry.fromJson({'streamId': 'x'}).channelId, isNull);
});
test('legacy entries get the ID their slot held', () async {
final blobs = InMemoryReceivedImageBlobStore();
final first = ReceivedImageStore(blobs: blobs, decoder: null);
final onSlot2 = await outgoing(first, slot: 2, imgId: 1);
final onSlot6 = await outgoing(first, slot: 6, imgId: 2);
final stamped = await outgoing(first, slot: 2, imgId: 3, channelId: 'x');
final store = ReceivedImageStore(blobs: blobs, decoder: null);
await store.load();
await store.stampLegacyChannelIds({2: _idOne, 3: _idTwo});
expect(store.entryFor(onSlot2.streamId)!.channelId, _idOne);
expect(store.entryFor(onSlot6.streamId)!.channelId, isNull);
expect(store.entryFor(stamped.streamId)!.channelId, 'x');
// Persisted, so the next launch keeps the stamp.
final reloaded = ReceivedImageStore(blobs: blobs, decoder: null);
await reloaded.load();
expect(reloaded.entryFor(onSlot2.streamId)!.channelId, _idOne);
});
test('delete by channel ID leaves a reused slot alone', () async {
final store = ReceivedImageStore(decoder: null);
final old = await outgoing(store, slot: 1, channelId: _idOne, imgId: 1);
final reused = await outgoing(
store,
slot: 1,
channelId: _idTwo,
imgId: 2,
);
expect(store.entriesForChannel(_idTwo).map((e) => e.streamId), [
reused.streamId,
]);
final removed = await store.deleteImagesForChannelId(_idOne);
expect(removed, [old.streamId]);
expect(store.entryFor(old.streamId), isNull);
expect(store.entryFor(reused.streamId), isNotNull);
});
});
}
+15 -10
View File
@@ -43,6 +43,8 @@ ChannelMessage _ch(int i) => ChannelMessage(
MessageStore _messageStore() => MessageStore()..setPublicKeyHex = _device;
const _channelId = '0123456789abcdef';
void main() {
group('MessageStore window persistence', () {
test('saving the window keeps archived history ahead of it', () async {
@@ -179,27 +181,30 @@ void main() {
await _init();
final store = ChannelMessageStore()..setPublicKeyHex = _device;
final all = [for (var i = 0; i < 8; i++) _ch(i)];
await store.saveChannelMessages(0, all);
await store.saveChannelMessages(_channelId, all);
final loaded = await store.loadChannelMessages(0);
store.setArchived(0, loaded.sublist(0, 5));
await store.saveChannelMessages(0, [...loaded.sublist(5), _ch(8)]);
final loaded = await store.loadChannelMessages(_channelId);
store.setArchived(_channelId, loaded.sublist(0, 5));
await store.saveChannelMessages(_channelId, [
...loaded.sublist(5),
_ch(8),
]);
final reloaded = await store.loadChannelMessages(0);
final reloaded = await store.loadChannelMessages(_channelId);
expect(reloaded.map((m) => m.text), [for (var i = 0; i <= 8; i++) 'c$i']);
});
test('clearing through another instance resets the archive', () async {
await _init();
final store = ChannelMessageStore()..setPublicKeyHex = _device;
store.setArchived(0, [_ch(0), _ch(1)]);
await store.saveChannelMessages(0, [_ch(2)]);
store.setArchived(_channelId, [_ch(0), _ch(1)]);
await store.saveChannelMessages(_channelId, [_ch(2)]);
await (ChannelMessageStore()..setPublicKeyHex = _device)
.clearChannelMessages(0);
await store.saveChannelMessages(0, [_ch(3)]);
.clearChannelMessages(_channelId);
await store.saveChannelMessages(_channelId, [_ch(3)]);
final reloaded = await store.loadChannelMessages(0);
final reloaded = await store.loadChannelMessages(_channelId);
expect(reloaded.map((m) => m.text), ['c3']);
});
});
@@ -17,6 +17,8 @@ Future<void> _init(Map<String, Object> values) async {
await PrefsManager.initialize();
}
const _channelId = '0123456789abcdef';
void main() {
test(
'message store skips a malformed record instead of dropping all',
@@ -42,13 +44,13 @@ void main() {
test('channel message store skips a malformed record', () async {
await _init({
'channel_messages_${_device.substring(0, 10)}0': jsonEncode([
'channel_messages_${_device.substring(0, 10)}_$_channelId': jsonEncode([
{'text': 'hi', 'timestamp': 1000, 'status': 1},
'garbage',
]),
});
final store = ChannelMessageStore()..setPublicKeyHex = _device;
final messages = await store.loadChannelMessages(0);
final messages = await store.loadChannelMessages(_channelId);
expect(messages.map((m) => m.text), ['hi']);
});
+29
View File
@@ -0,0 +1,29 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/utils/location_grid.dart';
void main() {
const vectors = [
(33.448376, -112.074036, 33.45, -112.080261),
(47.606209, -122.332069, 47.61, -122.344218),
(-33.8688, 151.2093, -33.87, 151.215954),
(0.0, 0.0, 0.01, -0.009997),
(51.5007, -0.1246, 51.51, -0.125401),
];
test('matches the API contract test vectors', () {
for (final (lat, lon, wantLat, wantLon) in vectors) {
final snapped = snapToLocationGrid(lat, lon);
expect(snapped.lat, closeTo(wantLat, 1e-9), reason: '$lat,$lon lat');
expect(snapped.lon, closeTo(wantLon, 1e-9), reason: '$lat,$lon lon');
}
});
test('snapping a center is idempotent', () {
for (final (lat, lon, _, _) in vectors) {
final once = snapToLocationGrid(lat, lon);
final twice = snapToLocationGrid(once.lat, once.lon);
expect(twice.lat, closeTo(once.lat, 1e-6));
expect(twice.lon, closeTo(once.lon, 1e-6));
}
});
}
+48
View File
@@ -0,0 +1,48 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/l10n/app_localizations.dart';
import 'package:meshcore_open/widgets/get_node_banner.dart';
void main() {
Future<void> pumpBanner(
WidgetTester tester, {
required Size size,
required double textScale,
}) async {
tester.view.physicalSize = size;
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
await tester.pumpWidget(
MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: MediaQuery(
data: MediaQueryData(
size: size,
textScaler: TextScaler.linear(textScale),
),
child: const Scaffold(bottomNavigationBar: GetNodeBanner()),
),
),
);
}
testWidgets('shows the pitch and affiliate link', (tester) async {
await pumpBanner(tester, size: const Size(390, 844), textScale: 1);
expect(find.text('Need a new node?'), findsOneWidget);
expect(find.text('Get one here'), findsOneWidget);
expect(find.textContaining('Affiliate link'), findsOneWidget);
expect(getNodeUrl, contains('sensecap_affiliate=JFWID0g'));
// Leaves most of the screen for the device list.
expect(
tester.getSize(find.byType(GetNodeBanner)).height,
lessThan(844 * 0.4),
);
});
testWidgets('lays out on a narrow phone with large text', (tester) async {
await pumpBanner(tester, size: const Size(320, 800), textScale: 1.5);
expect(tester.takeException(), isNull);
});
}
@@ -0,0 +1,99 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/connector/meshcore_connector.dart';
import 'package:meshcore_open/l10n/app_localizations.dart';
import 'package:meshcore_open/services/app_settings_service.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:meshcore_open/widgets/network_map_opt_in_dialog.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
class _ConnectedConnector extends MeshCoreConnector {
@override
bool get isConnected => true;
}
void main() {
late AppSettingsService settings;
late MeshCoreConnector connector;
setUp(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
settings = AppSettingsService();
await settings.loadSettings();
connector = _ConnectedConnector();
});
tearDown(() => connector.dispose());
Future<void> pumpHost(WidgetTester tester) async {
await tester.pumpWidget(
MultiProvider(
providers: [
ChangeNotifierProvider<AppSettingsService>.value(value: settings),
ChangeNotifierProvider<MeshCoreConnector>.value(value: connector),
],
child: MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: Builder(
builder: (context) => TextButton(
onPressed: () => maybeShowNetworkMapOptInDialog(context),
child: const Text('open'),
),
),
),
),
);
}
testWidgets('Share turns uploading on and the prompt never returns', (
tester,
) async {
await pumpHost(tester);
await tester.tap(find.text('open'));
await tester.pumpAndSettle();
expect(find.text('Help build the network map?'), findsOneWidget);
await tester.tap(find.text('Share'));
await tester.pumpAndSettle();
expect(settings.settings.networkMapUploadEnabled, isTrue);
expect(settings.settings.networkMapPromptShown, isTrue);
await settings.setNetworkMapUploadEnabled(false);
await tester.tap(find.text('open'));
await tester.pumpAndSettle();
expect(find.text('Help build the network map?'), findsNothing);
});
testWidgets('No thanks leaves uploading off and is remembered', (
tester,
) async {
await pumpHost(tester);
await tester.tap(find.text('open'));
await tester.pumpAndSettle();
await tester.tap(find.text('No thanks'));
await tester.pumpAndSettle();
expect(settings.settings.networkMapUploadEnabled, isFalse);
expect(settings.settings.networkMapPromptShown, isTrue);
await tester.tap(find.text('open'));
await tester.pumpAndSettle();
expect(find.text('Help build the network map?'), findsNothing);
});
testWidgets('not shown while no radio is connected', (tester) async {
connector.dispose();
connector = MeshCoreConnector();
await pumpHost(tester);
await tester.tap(find.text('open'));
await tester.pumpAndSettle();
expect(find.text('Help build the network map?'), findsNothing);
expect(settings.settings.networkMapPromptShown, isFalse);
});
}
@@ -0,0 +1,144 @@
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/path_playback.dart';
import 'package:meshcore_open/widgets/path_map_scaffold.dart';
void main() {
for (final scenario in [
(
name: 'compact portrait',
size: const Size(320, 568),
scale: 1.0,
combined: false,
collapsed: false,
),
(
name: 'compact landscape',
size: const Size(568, 320),
scale: 1.0,
combined: false,
collapsed: false,
),
(
name: 'large text',
size: const Size(320, 568),
scale: 2.0,
combined: false,
collapsed: false,
),
(
name: 'combined paths',
size: const Size(320, 568),
scale: 1.0,
combined: true,
collapsed: false,
),
(
name: 'collapsed',
size: const Size(320, 568),
scale: 1.0,
combined: false,
collapsed: true,
),
]) {
testWidgets(
'path panel fits ${scenario.name} and keeps content accessible',
(tester) async {
tester.view.physicalSize = scenario.size;
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
final playback = PathPlaybackController(const TestVSync());
addTearDown(playback.dispose);
var animationToggles = 0;
const hopListKey = ValueKey('hop-list');
await tester.pumpWidget(
MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
builder: (context, child) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(textScaler: TextScaler.linear(scenario.scale)),
child: child!,
),
home: Scaffold(
body: Stack(
children: [
PathMapBottomPanel(
header: const Text('3 hops (2.00 km)'),
combined: scenario.combined,
showInferredLegend: true,
collapsed: scenario.collapsed,
onToggleCollapsed: () {},
playback: playback,
selected: null,
animationEnabled: true,
onToggleAnimation: () => animationToggles++,
followEnabled: false,
onToggleFollow: () {},
showNoSelfGpsNote: true,
pathCount: scenario.combined ? 3 : 1,
hopRowCount: 3,
summary: scenario.combined
? Column(
children: [
for (var i = 1; i <= 3; i++)
SizedBox(height: 40, child: Text('Path $i')),
],
)
: null,
hopList: ListView(
key: hopListKey,
children: [
for (var i = 1; i <= 3; i++)
SizedBox(height: 60, child: Text('Hop $i')),
],
),
),
],
),
),
),
);
expect(tester.takeException(), isNull);
final animationButton = find.widgetWithIcon(
IconButton,
Icons.animation,
);
await tester.ensureVisible(animationButton);
await tester.pumpAndSettle();
await tester.tap(animationButton);
expect(animationToggles, 1);
if (!scenario.collapsed) {
expect(
tester.getSize(find.byKey(hopListKey)).height,
greaterThanOrEqualTo(60),
);
final l10n = AppLocalizations.of(
tester.element(find.byType(PathMapBottomPanel)),
);
final gpsNote = find.text(l10n.pathMap_noSelfGpsFix);
await tester.ensureVisible(gpsNote);
await tester.pumpAndSettle();
expect(gpsNote.hitTestable(), findsOneWidget);
await tester.scrollUntilVisible(
find.text('Hop 3'),
60,
scrollable: find.descendant(
of: find.byKey(hopListKey),
matching: find.byType(Scrollable),
),
);
await tester.pumpAndSettle();
expect(find.text('Hop 3').hitTestable(), findsOneWidget);
}
expect(tester.takeException(), isNull);
},
);
}
}