Merge upstream/dev (86 commits) into tth
build / ci-image (push) Successful in 10s
build / build (push) Failing after 4m27s

Upstream redesigned the chat composer (bubble, round +/send button,
ChatComposerQuote for the reply preview); our terminal theme had tweaked
the old layout. Took upstream's structure and re-applied the terminal
look to the new widgets: compact panel padding, square bubble, square
button, square and one-line-low reply quote. The terminal reply padding
in channel_chat_screen now lives in ChatComposerQuote, so DMs get it too.

Also fixed for the merge:
- mesh_ui: AvatarCircle uses upstream's avatarInitials() (nullable); the
  terminal glyph falls back to the person icon like upstream does;
- chat_screen: upstream split maxMessageRetries into direct/flood limits,
  the terminal line now shows the bubble's maxSendAttempts;
- test/screens/copy_messages_test.dart: the 1x1 PNG had a bad IDAT CRC.
  Its async decode failure leaked into the next test; upstream's real
  flutter_langdetect hides that by timing, our stub (instant init) does
  not, so the DM test failed ~3 of 5 runs. Replaced with a valid PNG.

Checked in the CI image (Flutter 3.47.9): flutter analyze lib test clean;
flutter test all green except settings_reveal_test "hides Image Messages
sub-options", which fails the same way on plain upstream/dev.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
tthandClaude Opus 5.5 committed 2026-11-23 12:43:57 +01:00
commit 63907cb17d
210 files changed
+47623 -4900

No files matched your search

+3 -2
View File
@@ -7,6 +7,7 @@ import 'package:meshcore_open/connector/meshcore_connector.dart';
import 'package:meshcore_open/connector/meshcore_protocol.dart';
import 'package:meshcore_open/models/channel.dart';
import 'package:meshcore_open/models/channel_message.dart';
import 'package:meshcore_open/models/chat_compression_mode.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';
@@ -201,7 +202,7 @@ void main() {
'another slot brings its history back', () async {
await _connect(_TestRadio());
await _waitFor(() => _texts(1).contains(_queuedHikingText));
await _connector.setChannelSmazEnabled(1, true);
await _connector.setChannelCompressionMode(1, ChatCompressionMode.smaz);
await _connector.setChannel(1, 'Hiking Group', ghostPsk);
expect(_connector.channelIdForSlot(1), ghostId);
@@ -408,7 +409,7 @@ void main() {
expect(_texts(5), _texts(1));
// Settings are stored per channel, so both slots see a change.
await _connector.setChannelSmazEnabled(5, true);
await _connector.setChannelCompressionMode(5, ChatCompressionMode.smaz);
expect(_connector.isChannelSmazEnabled(1), isTrue);
await _connector.setChannelRegion(1, 'test-region');
expect(_connector.getChannelRegion(5), 'test-region');
@@ -0,0 +1,163 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/connector/meshcore_connector.dart';
import 'package:meshcore_open/models/chat_compression_mode.dart';
import 'package:meshcore_open/review_mode/review_radio.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/channel_settings_store.dart';
import 'package:meshcore_open/storage/contact_settings_store.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:shared_preferences/shared_preferences.dart';
const _contactKey =
'1111111111111111111111111111111111111111111111111111111111111111';
Future<void> _waitFor(bool Function() condition) async {
final end = DateTime.now().add(const Duration(seconds: 8));
while (!condition()) {
if (DateTime.now().isAfter(end)) fail('Timed out waiting for condition');
await Future<void>.delayed(const Duration(milliseconds: 20));
}
}
ContactSettingsStore _contactStore() =>
ContactSettingsStore()..setPublicKeyHex = ReviewRadio.selfPublicKeyHex;
ChannelSettingsStore _channelStore() =>
ChannelSettingsStore()..setPublicKeyHex = ReviewRadio.selfPublicKeyHex;
Future<(bool, bool)> _savedContactFlags() async => (
await _contactStore().loadSmazEnabled(_contactKey),
await _contactStore().loadCyr2LatEnabled(_contactKey),
);
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late MeshCoreConnector connector;
// The connector's frame streams can only be listened to once per process,
// so the tests share one connected review radio.
setUpAll(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
connector = MeshCoreConnector();
final retryService = MessageRetryService();
connector.initialize(
retryService: retryService,
pathHistoryService: PathHistoryService(StorageService()),
);
connector.reviewRadioFactoryForTest = () => ReviewRadio(
scheduledMessageInterval: const Duration(hours: 1),
ackDelay: const Duration(hours: 1),
replyDelay: const Duration(hours: 1),
);
await connector.connectReview();
await _waitFor(() => connector.channelMapConfirmed);
addTearDown(() async {
await connector.disconnect();
connector.dispose();
retryService.dispose();
});
});
test('contact modes are mutually exclusive and saved', () async {
expect(
connector.contactCompressionMode(_contactKey),
ChatCompressionMode.off,
);
await connector.setContactCompressionMode(
_contactKey,
ChatCompressionMode.smaz,
);
expect(connector.isContactSmazEnabled(_contactKey), isTrue);
expect(connector.isContactCyr2LatEnabled(_contactKey), isFalse);
expect(await _savedContactFlags(), (true, false));
await connector.setContactCompressionMode(
_contactKey,
ChatCompressionMode.cyr2lat,
);
expect(
connector.contactCompressionMode(_contactKey),
ChatCompressionMode.cyr2lat,
);
expect(connector.isContactSmazEnabled(_contactKey), isFalse);
expect(await _savedContactFlags(), (false, true));
await connector.setContactCompressionMode(
_contactKey,
ChatCompressionMode.off,
);
expect(
connector.contactCompressionMode(_contactKey),
ChatCompressionMode.off,
);
expect(await _savedContactFlags(), (false, false));
});
test('overlapping contact choices end on the last one, never both', () async {
final writes = [
connector.setContactCompressionMode(
_contactKey,
ChatCompressionMode.smaz,
),
connector.setContactCompressionMode(
_contactKey,
ChatCompressionMode.cyr2lat,
),
connector.setContactCompressionMode(
_contactKey,
ChatCompressionMode.smaz,
),
];
await Future.wait(writes);
expect(
connector.contactCompressionMode(_contactKey),
ChatCompressionMode.smaz,
);
expect(connector.isContactCyr2LatEnabled(_contactKey), isFalse);
expect(await _savedContactFlags(), (true, false));
});
test(
'channel modes are mutually exclusive and saved by channel ID',
() async {
final channelId = connector.channelIdForSlot(1)!;
await connector.setChannelCompressionMode(1, ChatCompressionMode.cyr2lat);
expect(connector.channelCompressionMode(1), ChatCompressionMode.cyr2lat);
expect(await _channelStore().loadCyr2LatEnabled(channelId), isTrue);
expect(await _channelStore().loadSmazEnabled(channelId), isFalse);
await connector.setChannelCompressionMode(1, ChatCompressionMode.smaz);
expect(connector.channelCompressionMode(1), ChatCompressionMode.smaz);
expect(connector.isChannelCyr2LatEnabled(1), isFalse);
expect(await _channelStore().loadCyr2LatEnabled(channelId), isFalse);
expect(await _channelStore().loadSmazEnabled(channelId), isTrue);
// Other channels are untouched.
expect(connector.channelCompressionMode(0), ChatCompressionMode.off);
},
);
test('a channel slot without a storage ID is refused', () async {
const emptySlot = 30;
expect(connector.channelIdForSlot(emptySlot), isNull);
await expectLater(
connector.setChannelCompressionMode(emptySlot, ChatCompressionMode.smaz),
throwsStateError,
);
expect(
connector.channelCompressionMode(emptySlot),
ChatCompressionMode.off,
);
// A refused write does not block later ones.
await connector.setChannelCompressionMode(1, ChatCompressionMode.smaz);
expect(connector.channelCompressionMode(1), ChatCompressionMode.smaz);
});
}
+152
View File
@@ -0,0 +1,152 @@
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/connector/meshcore_connector.dart';
import 'package:meshcore_open/connector/meshcore_protocol.dart';
import 'package:meshcore_open/models/contact.dart';
import 'package:meshcore_open/review_mode/review_radio.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/contact_added_at_store.dart';
import 'package:meshcore_open/storage/last_radio_store.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:meshcore_open/utils/contact_qr.dart';
import 'package:shared_preferences/shared_preferences.dart';
Future<void> _waitFor(bool Function() condition, {int seconds = 8}) async {
final end = DateTime.now().add(Duration(seconds: seconds));
while (!condition()) {
if (DateTime.now().isAfter(end)) fail('Timed out waiting for condition');
await Future<void>.delayed(const Duration(milliseconds: 25));
}
}
class _RecordingReviewRadio extends ReviewRadio {
final List<Uint8List> sent = [];
_RecordingReviewRadio()
: super(scheduledMessageInterval: const Duration(hours: 1));
@override
void handle(Uint8List frame) {
sent.add(frame);
super.handle(frame);
}
}
// [cmd][pub_key x32][type][flags][path_len][path x64][name x32][last_advert x4]
const _lastAdvertOffset = 1 + 32 + 1 + 1 + 1 + 64 + 32;
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
setUp(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
});
test(
'a card add records a local added time once, never on the radio',
() async {
final connector = MeshCoreConnector();
addTearDown(connector.dispose);
final retryService = MessageRetryService();
addTearDown(retryService.dispose);
connector.initialize(
retryService: retryService,
pathHistoryService: PathHistoryService(StorageService()),
);
final radio = _RecordingReviewRadio();
connector.reviewRadioFactoryForTest = () => radio;
await connector.connectReview();
await _waitFor(() => connector.hasLoadedContacts);
final key = Uint8List.fromList(List.generate(32, (i) => 0xA0 + (i % 16)));
final keyHex = pubKeyToHex(key);
final card = ScannedContact(publicKey: key, name: 'Card', type: 1);
final before = DateTime.now();
await connector.addContactFromCard(card);
final addedAt = connector.contactAddedAt(keyHex);
expect(addedAt, isNotNull);
expect(addedAt!.isBefore(before), isFalse);
// The radio still gets advert time 0 (its replay guard).
final addFrame = radio.sent.lastWhere(
(f) => f.first == cmdAddUpdateContact,
);
expect(
ByteData.sublistView(
addFrame,
).getUint32(_lastAdvertOffset, Endian.little),
0,
);
// Re-adding keeps the first time.
await Future<void>.delayed(const Duration(milliseconds: 5));
await connector.addContactFromCard(card);
expect(connector.contactAddedAt(keyHex), addedAt);
// Persisted per radio.
final store = ContactAddedAtStore()
..setPublicKeyHex = connector.selfPublicKeyHex;
expect(
store.load()[keyHex]?.millisecondsSinceEpoch,
addedAt.millisecondsSinceEpoch,
);
final otherRadio = ContactAddedAtStore()
..setPublicKeyHex = 'ffffffffff00';
expect(otherRadio.load(), isEmpty);
// Removing the contact forgets it, so a later add starts fresh.
await connector.removeContact(
Contact(
publicKey: key,
name: 'Card',
type: 1,
pathLength: -1,
path: Uint8List(0),
lastSeen: DateTime.fromMillisecondsSinceEpoch(0),
),
);
expect(connector.contactAddedAt(keyHex), isNull);
// So does the firmware deleting it to make room.
await connector.addContactFromCard(card);
expect(connector.contactAddedAt(keyHex), isNotNull);
connector.handleFrameForTest([pushCodeContactDeleted, ...key]);
expect(connector.contactAddedAt(keyHex), isNull);
await Future<void>.delayed(Duration.zero);
expect(store.load(), isNot(contains(keyHex)));
await connector.disconnect(manual: true);
},
);
test('a saved radio restores its added times after a restart', () async {
const radioHex =
'a0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebf';
final contactHex = 'c1' * 32;
final addedAt = DateTime.fromMillisecondsSinceEpoch(1790000000000);
await (ContactAddedAtStore()..setPublicKeyHex = radioHex).save({
contactHex: addedAt,
});
await LastRadioStore().save(
LastRadio(
publicKeyHex: radioHex,
name: 'Base',
transport: LastRadio.transportBle,
bleRemoteId: 'AA:BB:CC:DD:EE:FF',
savedAt: addedAt,
),
);
final connector = MeshCoreConnector();
addTearDown(connector.dispose);
await connector.restoreLastRadio();
expect(connector.contactAddedAt(contactHex), addedAt);
});
}
+238
View File
@@ -0,0 +1,238 @@
import 'dart:async';
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:meshcore_open/connector/meshcore_connector.dart';
import 'package:meshcore_open/connector/meshcore_protocol.dart';
import 'package:meshcore_open/models/contact.dart';
import 'package:meshcore_open/models/path_history.dart';
import 'package:meshcore_open/models/path_selection.dart';
import 'package:meshcore_open/review_mode/review_radio.dart';
import 'package:meshcore_open/services/app_settings_service.dart';
import 'package:meshcore_open/services/message_retry_service.dart';
import 'package:meshcore_open/services/path_history_service.dart';
import 'package:meshcore_open/services/storage_service.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
Contact _directContact() {
return Contact(
publicKey: Uint8List.fromList(List<int>.generate(32, (i) => i + 1)),
name: 'Hill',
type: 1,
pathLength: 1,
path: Uint8List.fromList(const [0x11]),
lastSeen: DateTime.now(),
);
}
class _ControllablePathStorage extends StorageService {
Completer<ContactPathHistory?>? loadGate;
@override
Future<ContactPathHistory?> loadPathHistory(String contactPubKeyHex) {
final gate = loadGate;
if (gate != null && !gate.isCompleted) {
return gate.future;
}
return Future<ContactPathHistory?>.value(null);
}
}
class _RecordingReviewRadio extends ReviewRadio {
final List<Uint8List> sent = [];
_RecordingReviewRadio()
: super(
scheduledMessageInterval: const Duration(hours: 1),
// Long ACK delay so retry attempts run on timeout in tests.
ackDelay: const Duration(hours: 1),
);
@override
void handle(Uint8List frame) {
sent.add(frame);
super.handle(frame);
}
}
Future<void> _waitFor(bool Function() condition, {int seconds = 8}) async {
final end = DateTime.now().add(Duration(seconds: seconds));
while (!condition()) {
if (DateTime.now().isAfter(end)) fail('Timed out waiting for condition');
await Future<void>.delayed(const Duration(milliseconds: 25));
}
}
// NotificationService is a process-wide singleton whose reply stream can be
// listened to once, so every test shares one connector and reconnects it to a
// fresh radio.
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late MeshCoreConnector connector;
late _ControllablePathStorage storage;
late PathHistoryService history;
late MessageRetryService retries;
late AppSettingsService settings;
setUpAll(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
settings = AppSettingsService();
await settings.loadSettings();
connector = MeshCoreConnector();
storage = _ControllablePathStorage();
history = PathHistoryService(storage);
retries = MessageRetryService(
sentWatchdogGrace: const Duration(milliseconds: 5),
);
connector.initialize(
retryService: retries,
pathHistoryService: history,
appSettingsService: settings,
);
});
tearDownAll(() {
connector.dispose();
history.dispose();
retries.dispose();
});
setUp(() async {
storage.loadGate = null;
await settings.resetRoutingSettingsToDefault();
});
test('flood attempts do not wait for route history', () async {
await settings.updateSettings(
settings.settings.copyWith(
autoRouteRotationEnabled: true,
directRetries: 0,
floodRetries: 1,
),
);
final flooded = await connector.preparePathForContactSend(_directContact());
expect(flooded.useFlood, isTrue);
await settings.updateSettings(
settings.settings.copyWith(directRetries: 2, floodRetries: 1),
);
final direct = await connector.preparePathForContactSend(_directContact());
expect(direct.useFlood, isFalse);
expect(direct.hopCount, 1);
expect(direct.pathBytes, [0x11]);
await settings.updateSettings(
settings.settings.copyWith(directRetries: 0, floodRetries: 0),
);
final zeroBudget = await connector.preparePathForContactSend(
_directContact(),
);
expect(zeroBudget.useFlood, isFalse);
expect(zeroBudget.hopCount, 1);
expect(zeroBudget.pathBytes, [0x11]);
});
test(
'sendMessage with directRetries 0 and floodRetries 1 floods even when route history is loading',
() async {
final gate = Completer<ContactPathHistory?>();
storage.loadGate = gate;
final radio = _RecordingReviewRadio();
connector.reviewRadioFactoryForTest = () => radio;
await connector.connectReview();
addTearDown(connector.disconnect);
await _waitFor(() => connector.contacts.isNotEmpty);
final directContact = connector.contacts.firstWhere(
(c) => c.pathLength > 0,
);
await settings.updateSettings(
settings.settings.copyWith(
autoRouteRotationEnabled: true,
directRetries: 0,
floodRetries: 1,
),
);
radio.sent.clear();
await connector.sendMessage(directContact, 'flood only');
await _waitFor(
() => radio.sent.any((frame) => frame[0] == cmdSendTxtMsg),
);
final opCodes = radio.sent
.map((frame) => frame[0])
.where(
(code) =>
code == cmdResetPath ||
code == cmdAddUpdateContact ||
code == cmdSendTxtMsg,
)
.toList();
expect(opCodes, [cmdResetPath, cmdSendTxtMsg]);
gate.complete(null);
storage.loadGate = null;
},
);
test(
'sendMessage with directRetries > 0 rotates through cached paths before flooding',
() async {
final radio = _RecordingReviewRadio();
connector.reviewRadioFactoryForTest = () => radio;
await connector.connectReview();
addTearDown(connector.disconnect);
await _waitFor(() => connector.contacts.isNotEmpty);
final directContact = connector.contacts.firstWhere(
(c) => c.pathLength > 0,
);
history.recordPathResult(
directContact.publicKeyHex,
const PathSelection(pathBytes: [0x22], hopCount: 1, useFlood: false),
success: true,
);
await pumpEventQueue();
history.recordPathResult(
directContact.publicKeyHex,
const PathSelection(pathBytes: [0x33], hopCount: 1, useFlood: false),
success: true,
);
await pumpEventQueue();
await settings.updateSettings(
settings.settings.copyWith(
autoRouteRotationEnabled: true,
directRetries: 2,
floodRetries: 1,
),
);
radio.sent.clear();
await connector.sendMessage(directContact, 'rotate then flood');
await _waitFor(
() =>
radio.sent.where((frame) => frame[0] == cmdSendTxtMsg).length == 3,
seconds: 25,
);
final pathOps = radio.sent
.where(
(frame) =>
frame[0] == cmdResetPath || frame[0] == cmdAddUpdateContact,
)
.map((frame) => frame[0])
.toList();
expect(pathOps, [cmdAddUpdateContact, cmdAddUpdateContact, cmdResetPath]);
},
timeout: const Timeout(Duration(seconds: 45)),
);
}
+82
View File
@@ -0,0 +1,82 @@
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/games/chess/chess_link.dart';
import 'package:meshcore_open/games/chess/chess_packets.dart';
import 'package:meshcore_open/games/game_packet.dart';
import 'package:meshcore_open/services/image_chunk_transport.dart';
class _Connector extends MeshCoreConnector {
final frames = StreamController<Uint8List>.broadcast(sync: true);
bool mapConfirmed = false;
@override
Stream<Uint8List> get receivedFrames => frames.stream;
@override
bool get channelMapConfirmed => mapConfirmed;
@override
String? channelIdForSlot(int slot) => slot == 2 ? 'chan-two' : null;
void confirm() {
mapConfirmed = true;
notifyListeners();
}
}
/// A RESP_CODE_CHANNEL_DATA_RECV frame for [payload] on [slot].
Uint8List _frame(int slot, int dataType, Uint8List payload) =>
Uint8List.fromList([
respCodeChannelDataRecv,
8, // SNR
0,
0,
slot,
0xFF,
dataType & 0xFF,
dataType >> 8,
payload.length,
...payload,
]);
void main() {
final payload = ChessDeclinePacket(gameId: 5, declinerName: 'Bob').encode();
test('passes chess payloads through, keyed by channel id', () async {
final connector = _Connector()..mapConfirmed = true;
final link = ConnectorChessLink(connector);
final heard = <ChessIncoming>[];
link.incoming.listen(heard.add);
connector.frames.add(_frame(2, meshcoreOpenDataType, payload));
connector.frames.add(_frame(2, 0xAE1C, payload)); // images
connector.frames.add(_frame(3, meshcoreOpenDataType, payload)); // unknown
connector.frames.add(
_frame(2, meshcoreOpenDataType, Uint8List.fromList([0x20, 0, 0, 0])),
); // another app nibble
await Future<void>.delayed(Duration.zero);
expect(heard, hasLength(1));
expect(heard.single.channelId, 'chan-two');
expect(heard.single.payload, payload);
link.dispose();
});
test('holds frames until the channel map is confirmed', () async {
final connector = _Connector();
final link = ConnectorChessLink(connector);
final heard = <ChessIncoming>[];
link.incoming.listen(heard.add);
connector.frames.add(_frame(2, meshcoreOpenDataType, payload));
expect(heard, isEmpty);
connector.confirm();
// The connector batches change notifications.
await Future<void>.delayed(const Duration(milliseconds: 300));
expect(heard, hasLength(1));
link.dispose();
});
}
+261
View File
@@ -0,0 +1,261 @@
import 'dart:math';
import 'dart:typed_data';
import 'package:chess/chess.dart' as rules;
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/games/chess/chess_game.dart';
import 'package:meshcore_open/games/chess/chess_packets.dart';
import 'package:meshcore_open/games/chess/chess_position_codec.dart';
import 'package:meshcore_open/games/game_packet.dart';
import 'package:meshcore_open/games/hash_chain.dart';
Uint8List _bytes(int n, int seed) =>
Uint8List.fromList(List.generate(n, (i) => (i * 31 + seed) & 0xFF));
/// FEN without the full-move number, which the codec does not carry.
String _withoutMoveNumber(String fen) => fen.split(' ').sublist(0, 5).join(' ');
void main() {
group('position codec', () {
test('start position packs to 26 bytes and round-trips', () {
final packed = ChessPositionCodec.encodeFen(ChessGame.startFen);
expect(packed.length, 26);
expect(
ChessPositionCodec.decodeToFen(packed, fullMoveNumber: 1),
ChessGame.startFen,
);
});
test('round-trips positions from random games', () {
final rng = Random(7);
var positions = 0;
for (var game = 0; game < 40; game++) {
final board = rules.Chess();
for (var ply = 0; ply < 120 && !board.game_over; ply++) {
final moves = board.moves({'asObjects': true}).cast<rules.Move>();
board.move(moves[rng.nextInt(moves.length)]);
final fen = board.fen;
final packed = ChessPositionCodec.encodeFen(fen);
expect(packed.length, lessThanOrEqualTo(ChessPositionCodec.maxBytes));
final decoded = ChessPositionCodec.decodeToFen(
packed,
fullMoveNumber: board.move_number,
);
expect(
_withoutMoveNumber(decoded!),
_withoutMoveNumber(fen),
reason: fen,
);
positions++;
}
}
expect(positions, greaterThan(1000));
});
test('drops castling and en passant rights the pieces rule out', () {
// Kings on e1/e8 but the h1 rook gone; an en passant file with no pawn.
const fen = 'r3k2r/8/8/8/8/8/8/R3K3 w KQkq e6 0 1';
final packed = ChessPositionCodec.encodeFen(fen);
final decoded = ChessPositionCodec.decodeToFen(packed, fullMoveNumber: 1);
expect(decoded, 'r3k2r/8/8/8/8/8/8/R3K3 w Qkq - 0 1');
// The rules engine can list moves for it without throwing.
final game = ChessGame(
channelId: 'c',
gameId: 1,
status: ChessGameStatus.active,
deadline: ChessDeadline.none,
createdAtMs: 0,
)..adoptPosition(decoded!, 0);
expect(game.legalUci(), contains('e1c1'));
expect(game.legalUci(), isNot(contains('e1g1')));
// A real en passant chance survives.
const ep =
'rnbqkbnr/ppp1p1pp/8/3pPp2/8/8/PPPP1PPP/RNBQKBNR w KQkq f6 0 3';
expect(
ChessPositionCodec.decodeToFen(
ChessPositionCodec.encodeFen(ep),
fullMoveNumber: 3,
),
ep,
);
});
test('rejects a length that does not match the occupancy', () {
final packed = ChessPositionCodec.encodeFen(ChessGame.startFen);
expect(
ChessPositionCodec.decodeToFen(
Uint8List.fromList(packed.sublist(0, 20)),
fullMoveNumber: 1,
),
isNull,
);
});
});
group('hash chain', () {
final chain = HashChain(_bytes(16, 3));
test('each value hashes to the previous one', () {
expect(hashChainStep(chain.valueAt(1)), chain.valueAt(0));
expect(hashChainStep(chain.valueAt(10)), chain.valueAt(9));
});
test('distance counts skipped values and flags duplicates', () {
expect(hashChainDistance(chain.valueAt(1), chain.commitment), 1);
expect(hashChainDistance(chain.valueAt(5), chain.valueAt(2)), 3);
expect(hashChainDistance(chain.valueAt(2), chain.valueAt(2)), 0);
});
test('rejects older values and other chains', () {
expect(hashChainDistance(chain.valueAt(2), chain.valueAt(5)), isNull);
final other = HashChain(_bytes(16, 9));
expect(hashChainDistance(other.valueAt(1), chain.commitment), isNull);
});
test('player values count once and only in order', () {
final player = ChessPlayer(name: 'A', commitment: chain.commitment);
expect(player.freshIndex(chain.valueAt(1)), 1);
player.use(1);
expect(player.freshIndex(chain.valueAt(1)), isNull);
expect(player.freshIndex(chain.valueAt(4)), 4);
player.use(4);
// Index 3 was never used, but anyone can compute it from value 4.
expect(player.freshIndex(chain.valueAt(3)), isNull);
expect(player.lastIndex, 4);
});
test('the inviter chain keeps value 1 for the game info', () {
final inviter = ChessPlayer.inviter(
name: 'A',
commitment: chain.commitment,
);
expect(inviter.freshIndex(chain.valueAt(1)), isNull);
expect(inviter.freshIndex(chain.valueAt(2)), 2);
});
});
group('packets', () {
final commitment = _bytes(16, 1);
final value = _bytes(16, 2);
final longName = 'N' * 40;
test('move packet fits one 64-byte encrypted block run', () {
final packet = ChessMovePacket(
gameId: 0xBEEF,
ply: 300,
moveIndex: 17,
chainValue: value,
position: ChessPositionCodec.encodeFen(ChessGame.startFen),
);
final bytes = packet.encode();
expect(bytes.length, 48);
expect(encryptedGamePayloadSize(bytes.length), 64);
final decoded = ChessPacket.decode(bytes) as ChessMovePacket;
expect(decoded.gameId, 0xBEEF);
expect(decoded.ply, 300);
expect(decoded.moveIndex, 17);
expect(decoded.chainValue, value);
expect(decoded.position, packet.position);
});
test('invite sizes and names are capped', () {
final open = ChessInvitePacket(
gameId: 1,
deadline: ChessDeadline.hour1,
colour: ChessColourPreference.black,
commitment: commitment,
inviterName: longName,
).encode();
expect(open.length, 55);
expect(encryptedGamePayloadSize(open.length), 64);
final direct = ChessInvitePacket(
gameId: 1,
deadline: ChessDeadline.days3,
colour: ChessColourPreference.random,
commitment: commitment,
inviterName: longName,
targetName: longName,
);
final bytes = direct.encode();
expect(bytes.length, 87);
final decoded = ChessPacket.decode(bytes) as ChessInvitePacket;
expect(decoded.inviterName, 'N' * maxGameNameBytes);
expect(decoded.targetName, 'N' * maxGameNameBytes);
expect(decoded.deadline, ChessDeadline.days3);
expect(decoded.isDirect, isTrue);
final accept = ChessAcceptPacket(
gameId: 1,
commitment: commitment,
accepterName: longName,
).encode();
expect(accept.length, 53);
final decline = ChessDeclinePacket(
gameId: 1,
declinerName: longName,
).encode();
expect(decline.length, 37);
});
test('names are cut on a character boundary', () {
final name = '${'a' * 29}é'; // 29 + 2 bytes = 31: fits.
expect(truncateUtf8(name, 31).length, 31);
expect(truncateUtf8('${'a' * 30}é', 31).length, 30);
});
test('actions, info and requests round-trip', () {
final action = ChessActionPacket(
kind: ChessPacketKind.resign,
gameId: 9,
ply: 4,
chainValue: value,
).encode();
expect(action.length, 21);
expect(encryptedGamePayloadSize(action.length), 32);
expect(
(ChessPacket.decode(action) as ChessActionPacket).kind,
ChessPacketKind.resign,
);
final info = ChessInfoPacket(
gameId: 9,
ply: 4,
startedAtUnix: 1700000000,
deadline: ChessDeadline.hour1,
whiteCommitment: commitment,
blackCommitment: value,
inviterValue: value,
whiteName: longName,
blackName: longName,
).encode();
expect(info.length, 122);
expect(info.length, lessThanOrEqualTo(maxGamePayloadBytes));
final decodedInfo = ChessPacket.decode(info) as ChessInfoPacket;
expect(decodedInfo.startedAtUnix, 1700000000);
expect(decodedInfo.blackCommitment, value);
expect(decodedInfo.inviterValue, value);
final request = ChessRequestPacket(
gameId: 9,
ply: 4,
wantsInfo: true,
wantsLatestMove: true,
).encode();
expect(request.length, 6);
final decodedRequest = ChessPacket.decode(request) as ChessRequestPacket;
expect(decodedRequest.wantsInfo, isTrue);
expect(decodedRequest.wantsLatestMove, isTrue);
});
test('rejects other apps and truncated packets', () {
final bytes = ChessAcceptPacket(
gameId: 2,
commitment: commitment,
accepterName: 'Bob',
).encode();
expect(ChessPacket.decode(bytes.sublist(0, 10)), isNull);
final otherApp = Uint8List.fromList(bytes)..[0] = 0x21;
expect(ChessPacket.decode(otherApp), isNull);
});
});
}
+959
View File
@@ -0,0 +1,959 @@
import 'dart:async';
import 'dart:math';
import 'dart:typed_data';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/games/chess/chess_game.dart';
import 'package:meshcore_open/games/chess/chess_link.dart';
import 'package:meshcore_open/games/chess/chess_packets.dart';
import 'package:meshcore_open/games/chess/chess_service.dart';
import 'package:meshcore_open/games/chess/chess_store.dart';
import 'package:meshcore_open/games/hash_chain.dart';
import 'package:meshcore_open/l10n/app_localizations.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:shared_preferences/shared_preferences.dart';
const _channel = 'abcdef0123456789';
/// A shared channel: whatever one link sends, every other link hears.
class _Mesh {
final List<_FakeLink> links = [];
/// Return false to drop a packet before it reaches [to].
bool Function(_FakeLink from, _FakeLink to, Uint8List payload)? filter;
void deliver(_FakeLink from, Uint8List payload) {
for (final to in links) {
if (identical(to, from)) continue;
if (filter != null && !filter!(from, to, payload)) continue;
to.controller.add(ChessIncoming(_channel, payload));
}
}
}
class _FakeLink extends ChangeNotifier implements ChessLink {
final _Mesh mesh;
@override
final String selfName;
@override
final String storageScope;
final StreamController<ChessIncoming> controller = StreamController.broadcast(
sync: true,
);
final List<Uint8List> sent = [];
final List<String> notifications = [];
bool connected = true;
/// The radio does not confirm the next send; [deliverFailed] says whether
/// the packet went out anyway.
bool failNext = false;
bool deliverFailed = false;
/// Lets other timers run while our send is in flight.
bool slow = false;
_FakeLink(this.mesh, this.selfName, this.storageScope) {
mesh.links.add(this);
}
@override
Stream<ChessIncoming> get incoming => controller.stream;
@override
Future<bool> send(String channelId, Uint8List payload) async {
if (!connected) return false;
if (failNext) {
failNext = false;
if (deliverFailed) mesh.deliver(this, payload);
return false;
}
sent.add(payload);
mesh.deliver(this, payload);
if (slow) await Future<void>.delayed(Duration.zero);
return true;
}
@override
bool get canSend => connected;
@override
void notify(String channelId, String text) => notifications.add(text);
@override
AppLocalizations get l10n => lookupAppLocalizations(const Locale('en'));
}
class _Player {
final _FakeLink link;
final ChessService service;
_Player(this.link, this.service);
ChessGame? get game => service.gamesForChannel(_channel).firstOrNull;
}
void main() {
late _Mesh mesh;
late DateTime now;
final created = <_Player>[];
setUp(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
mesh = _Mesh();
now = DateTime(2026, 11, 21, 12);
});
tearDown(() {
for (final p in created) {
p.service.dispose();
}
created.clear();
});
var nextSeed = 100;
_Player player(String name, {int? seed, bool Function()? isForeground}) {
final link = _FakeLink(
mesh,
name,
'${name.toLowerCase()}000000000'.substring(0, 10),
);
final service = ChessService(
link: link,
store: ChessStore(),
clock: () => now,
random: Random(seed ?? nextSeed++),
answerDelayMin: Duration.zero,
answerDelayMax: Duration.zero,
startHousekeeping: false,
isForeground: isForeground,
);
final p = _Player(link, service);
created.add(p);
return p;
}
/// Lets zero-delay answer timers fire.
Future<void> settle() => Future<void>.delayed(Duration.zero);
Future<(_Player white, _Player black)> startGame(
_Player alice,
_Player bob, {
ChessColourPreference colour = ChessColourPreference.white,
}) async {
final invite = await alice.service.createInvite(
channelId: _channel,
colour: colour,
);
expect(invite, isNotNull);
expect(await bob.service.accept(bob.game!), isTrue);
await settle(); // Alice's confirmation (game info).
expect(alice.game!.status, ChessGameStatus.active);
expect(bob.game!.status, ChessGameStatus.active);
final aliceWhite = alice.game!.mySide == ChessSide.white;
return aliceWhite ? (alice, bob) : (bob, alice);
}
test(
'open invite, accept, and Scholar\'s mate seen by a spectator',
() async {
final alice = player('Alice', seed: 1);
final bob = player('Bob', seed: 2);
final carol = player('Carol', seed: 3);
final (white, black) = await startGame(alice, bob);
expect(white, same(alice));
expect(carol.game!.status, ChessGameStatus.active);
expect(carol.game!.isPlayer, isFalse);
expect(carol.game!.hasPlayers, isTrue);
expect(bob.link.notifications, isEmpty);
const moves = ['e2e4', 'e7e5', 'f1c4', 'b8c6', 'd1h5', 'g8f6', 'h5f7'];
for (var i = 0; i < moves.length; i++) {
final mover = i.isEven ? white : black;
expect(
await mover.service.makeMove(mover.game!, moves[i]),
isTrue,
reason: moves[i],
);
}
for (final p in [alice, bob, carol]) {
final g = p.game!;
expect(g.status, ChessGameStatus.finished);
expect(g.endReason, ChessEndReason.checkmate);
expect(g.winner, ChessSide.white);
expect(g.sanMoves.last, 'Qxf7#');
}
expect(bob.link.notifications.last, contains('Alice'));
},
);
test('random colour gives both sides the same answer', () async {
final alice = player('Alice', seed: 4);
final bob = player('Bob', seed: 5);
await startGame(alice, bob, colour: ChessColourPreference.random);
expect(alice.game!.mySide, isNotNull);
expect(bob.game!.mySide, alice.game!.mySide!.other);
});
test('direct challenge notifies only the target, who can decline', () async {
final alice = player('Alice');
final bob = player('Bob');
final carol = player('Carol');
await alice.service.createInvite(channelId: _channel, targetName: 'bob');
expect(bob.link.notifications.single, contains('Alice'));
expect(carol.link.notifications, isEmpty);
expect(await bob.service.decline(bob.game!), isTrue);
expect(alice.game!.status, ChessGameStatus.finished);
expect(alice.game!.endReason, ChessEndReason.declined);
});
test('only the first confirmed accept gets the game', () async {
final alice = player('Alice');
final bob = player('Bob');
final carol = player('Carol');
await alice.service.createInvite(
channelId: _channel,
colour: ChessColourPreference.white,
);
// Carol does not hear Bob's accept, and accepts too.
mesh.filter = (from, to, _) => !(from == bob.link && to == carol.link);
await bob.service.accept(bob.game!);
mesh.filter = null;
await carol.service.accept(carol.game!);
await settle();
expect(alice.game!.nameOf(ChessSide.black), 'Bob');
expect(bob.game!.mySide, ChessSide.black);
expect(carol.game!.isPlayer, isFalse);
expect(carol.game!.status, ChessGameStatus.active);
});
test(
'a spectator that missed moves takes the position from the next one',
() async {
final alice = player('Alice');
final bob = player('Bob');
final (white, black) = await startGame(alice, bob);
await white.service.makeMove(white.game!, 'd2d4');
await black.service.makeMove(black.game!, 'd7d5');
final dave = player('Dave');
await white.service.makeMove(white.game!, 'c2c4');
final g = dave.game!;
expect(g.ply, 3);
expect(g.fen, white.game!.fen);
expect(g.sanMoves, [null, null, null]);
expect(g.hasPlayers, isFalse);
// Asking for an update fetches the players.
await dave.service.requestUpdate(g);
await settle();
expect(dave.game!.hasPlayers, isTrue);
await black.service.makeMove(black.game!, 'e7e6');
expect(dave.game!.ply, 4);
expect(dave.game!.sanMoves.last, 'e6');
},
);
test('a player who missed a move gets it back by asking', () async {
final alice = player('Alice');
final bob = player('Bob');
final (white, black) = await startGame(alice, bob);
mesh.filter = (from, to, _) => !(from == white.link && to == black.link);
await white.service.makeMove(white.game!, 'e2e4');
mesh.filter = null;
expect(black.game!.ply, 0);
expect(black.game!.isMyTurn, isFalse);
await black.service.requestUpdate(black.game!);
await settle();
expect(black.game!.ply, 1);
expect(black.game!.isMyTurn, isTrue);
});
test('forged moves and conflicting duplicates are rejected', () async {
final alice = player('Alice');
final bob = player('Bob');
final carol = player('Carol');
final (white, black) = await startGame(alice, bob);
await white.service.makeMove(white.game!, 'e2e4');
final real = ChessPacket.decode(white.link.sent.last) as ChessMovePacket;
// Mallory replays White's chain value with a different move as Black's.
final forged = ChessMovePacket(
gameId: real.gameId,
ply: 2,
moveIndex: 0,
chainValue: real.chainValue,
position: real.position,
);
carol.service.handleIncoming(ChessIncoming(_channel, forged.encode()));
expect(carol.game!.ply, 1);
// And a made-up chain value.
final random = ChessMovePacket(
gameId: real.gameId,
ply: 2,
moveIndex: 0,
chainValue: Uint8List(16),
position: real.position,
);
carol.service.handleIncoming(ChessIncoming(_channel, random.encode()));
black.service.handleIncoming(ChessIncoming(_channel, random.encode()));
expect(carol.game!.ply, 1);
expect(black.game!.ply, 1);
});
test('resign, draw and timeout claims', () async {
final alice = player('Alice');
final bob = player('Bob');
var (white, black) = await startGame(alice, bob);
await white.service.offerDraw(white.game!);
expect(black.game!.drawOfferedBy, ChessSide.white);
await black.service.acceptDraw(black.game!);
expect(white.game!.endReason, ChessEndReason.drawAgreed);
final carol = player('Carol', seed: 8);
final dan = player('Dan', seed: 9);
(white, black) = await startGame(carol, dan);
await black.service.resign(black.game!);
expect(white.game!.winner, ChessSide.white);
expect(white.game!.endReason, ChessEndReason.resignation);
final erin = player('Erin', seed: 10);
final finn = player('Finn', seed: 11);
(white, black) = await startGame(erin, finn);
await white.service.makeMove(white.game!, 'e2e4');
expect(white.service.canClaimTimeout(white.game!), isFalse);
now = now.add(const Duration(hours: 1, minutes: 11));
expect(white.service.canClaimTimeout(white.game!), isTrue);
expect(await white.service.claimTimeout(white.game!), isTrue);
expect(black.game!.endReason, ChessEndReason.timeout);
expect(black.game!.winner, ChessSide.white);
});
test('games persist per radio scope', () async {
final alice = player('Alice');
final bob = player('Bob');
final (white, _) = await startGame(alice, bob);
await white.service.makeMove(white.game!, 'g1f3');
await alice.service.store.flush();
final reloaded = ChessStore().load(alice.link.storageScope).single;
expect(reloaded.ply, 1);
expect(reloaded.mySide, alice.game!.mySide);
expect(reloaded.mySeedHex, isNotNull);
expect(ChessStore().load('other00000'), isEmpty);
});
test('invites expire after a day', () async {
final alice = player('Alice');
final bob = player('Bob');
await alice.service.createInvite(channelId: _channel);
now = now.add(const Duration(hours: 25));
bob.service.housekeeping();
expect(bob.game!.endReason, ChessEndReason.expired);
});
/// The packets [p] sent of type [T].
List<T> sentOf<T extends ChessPacket>(_Player p) =>
p.link.sent.map(ChessPacket.decode).whereType<T>().toList();
void feed(_Player p, ChessPacket packet) =>
p.service.handleIncoming(ChessIncoming(_channel, packet.encode()));
/// A legal move on [game]'s board as the next half-move, carrying [value].
ChessMovePacket craftMove(ChessGame game, String uci, Uint8List value) {
final probe = ChessGame.fromJson(game.toJson())!;
final index = probe.legalUci().indexOf(uci);
probe.applyUci(uci);
return ChessMovePacket(
gameId: game.gameId,
ply: probe.ply,
moveIndex: index,
chainValue: value,
position: probe.packedPosition(),
);
}
group('review regressions', () {
test('a replayed chain value cannot carry a later move', () async {
final alice = player('Alice');
final bob = player('Bob');
final carol = player('Carol');
final (white, black) = await startGame(alice, bob);
await white.service.makeMove(white.game!, 'e2e4');
final first = sentOf<ChessMovePacket>(white).last;
await black.service.makeMove(black.game!, 'e7e5');
// White's ply-1 value with a legal ply-3 move.
final replay = craftMove(black.game!, 'd1h5', first.chainValue);
feed(black, replay);
feed(carol, replay);
expect(black.game!.ply, 2);
expect(carol.game!.ply, 2);
// A spectator two moves behind does not adopt it either.
final dave = player('Dave');
feed(dave, sentOf<ChessMovePacket>(black).last);
final ahead = ChessMovePacket(
gameId: first.gameId,
ply: 5,
moveIndex: 0,
chainValue: first.chainValue,
position: first.position,
);
feed(carol, ahead);
expect(carol.game!.ply, 2);
// The real move is accepted, and a different move with the same value
// heard afterwards is not: the first one heard wins.
await white.service.makeMove(white.game!, 'g1f3');
final real = sentOf<ChessMovePacket>(white).last;
final copy = craftMove(
ChessGame.fromJson(carol.game!.toJson())!
..adoptPosition(black.game!.fen, 2),
'd2d4',
real.chainValue,
);
feed(carol, copy);
expect(carol.game!.ply, 3);
expect(carol.game!.sanMoves.last, 'Nf3');
});
test('a forged game info is ignored', () async {
final alice = player('Alice');
final bob = player('Bob');
final carol = player('Carol');
final mallory = HashChain(Uint8List(16)..[0] = 66);
// Nobody hears Alice's confirmation.
mesh.filter = (from, to, payload) =>
!(from == alice.link &&
ChessPacket.decode(payload) is ChessInfoPacket);
await alice.service.createInvite(
channelId: _channel,
colour: ChessColourPreference.white,
);
await bob.service.accept(bob.game!);
await settle();
final real = sentOf<ChessInfoPacket>(alice).single;
final inviter = alice.game!.inviter!.commitment;
// Without the inviter's value: lists Mallory and swaps colours.
ChessInfoPacket info({
required Uint8List white,
required Uint8List black,
required Uint8List value,
}) => ChessInfoPacket(
gameId: real.gameId,
ply: 0,
startedAtUnix: 0,
deadline: ChessDeadline.days3,
whiteCommitment: white,
blackCommitment: black,
inviterValue: value,
whiteName: 'Alice',
blackName: 'Mallory',
);
final noValue = info(
white: inviter,
black: mallory.commitment,
value: Uint8List(16),
);
feed(bob, noValue);
feed(carol, noValue);
expect(bob.game!.status, ChessGameStatus.starting);
expect(bob.game!.mySeedHex, isNotNull);
expect(carol.game!.status, ChessGameStatus.invite);
// The real value, but colours the invite does not allow.
final swapped = info(
white: real.blackCommitment,
black: inviter,
value: real.inviterValue,
);
feed(bob, swapped);
feed(carol, swapped);
expect(bob.game!.status, ChessGameStatus.starting);
expect(carol.game!.status, ChessGameStatus.invite);
// A copied value listing Mallory: Bob watches but keeps his chain, and
// asking again gets him the real game.
final copied = info(
white: inviter,
black: mallory.commitment,
value: real.inviterValue,
);
feed(bob, copied);
expect(bob.game!.isPlayer, isFalse);
expect(bob.game!.mySeedHex, isNotNull);
mesh.filter = null;
await bob.service.requestUpdate(bob.game!);
await settle();
expect(bob.game!.mySide, ChessSide.black);
expect(bob.game!.nameOf(ChessSide.white), 'Alice');
// A late joiner can't tie the info to an invite: not confirmed.
final dave = player('Dave');
feed(dave, real);
expect(dave.game!.hasPlayers, isTrue);
expect(dave.game!.playersConfirmed, isFalse);
expect(carol.game!.playersConfirmed, isTrue);
});
test('a forged move never starts an invite', () async {
final alice = player('Alice');
final bob = player('Bob');
final carol = player('Carol');
await alice.service.createInvite(
channelId: _channel,
colour: ChessColourPreference.white,
);
final forged = craftMove(alice.game!, 'e2e4', Uint8List(16));
feed(alice, forged);
feed(carol, forged);
expect(alice.game!.status, ChessGameStatus.invite);
expect(carol.game!.status, ChessGameStatus.invite);
// A real accept still starts the game, and a repeat is answered.
await bob.service.accept(bob.game!);
await settle();
expect(alice.game!.mySide, ChessSide.white);
feed(alice, sentOf<ChessAcceptPacket>(bob).single);
await settle();
expect(alice.game!.status, ChessGameStatus.active);
// A spectator who missed the start follows the inviter's first move.
final dave = player('Dave');
feed(dave, sentOf<ChessInvitePacket>(alice).single);
await alice.service.makeMove(alice.game!, 'e2e4');
expect(dave.game!.status, ChessGameStatus.active);
expect(dave.game!.ply, 1);
expect(dave.game!.white, same(dave.game!.inviter));
});
test('a confirmation heard while our accept is sending counts', () async {
final alice = player('Alice');
final bob = player('Bob');
await alice.service.createInvite(channelId: _channel);
bob.link.slow = true;
await bob.service.accept(bob.game!);
expect(bob.game!.status, ChessGameStatus.active);
expect(bob.game!.isPlayer, isTrue);
});
test('a losing accepter who missed the info learns it by asking', () async {
final alice = player('Alice');
final bob = player('Bob');
final carol = player('Carol');
await alice.service.createInvite(channelId: _channel);
mesh.filter = (from, to, _) => to != carol.link;
await bob.service.accept(bob.game!);
await settle();
mesh.filter = (from, to, payload) =>
!(to == carol.link && ChessPacket.decode(payload) is ChessInfoPacket);
await carol.service.accept(carol.game!);
await settle();
expect(carol.game!.status, ChessGameStatus.starting);
// Alice answered (unheard); she answers again after a minute.
mesh.filter = null;
now = now.add(ChessService.requestAnswerInterval);
await carol.service.requestUpdate(carol.game!);
await settle();
expect(carol.game!.status, ChessGameStatus.active);
expect(carol.game!.isPlayer, isFalse);
expect(carol.game!.hasPlayers, isTrue);
});
test('repeated accepts are answered at most once a minute', () async {
final alice = player('Alice');
final bob = player('Bob');
await startGame(alice, bob);
final before = sentOf<ChessInfoPacket>(alice).length;
final accept = sentOf<ChessAcceptPacket>(bob).single;
for (var i = 0; i < 5; i++) {
feed(alice, accept);
await settle();
}
expect(sentOf<ChessInfoPacket>(alice).length, before + 1);
});
test('a lost move followed by a draw offer still gets through', () async {
final alice = player('Alice');
final bob = player('Bob');
final (white, black) = await startGame(alice, bob);
mesh.filter = (from, to, payload) =>
!(to == black.link && ChessPacket.decode(payload) is ChessMovePacket);
await white.service.makeMove(white.game!, 'e2e4');
mesh.filter = null;
await white.service.offerDraw(white.game!);
expect(black.game!.ply, 0);
// The offer was for a position Black has not seen.
expect(black.game!.drawOfferedBy, isNull);
await black.service.requestUpdate(black.game!);
await settle();
expect(black.game!.ply, 1);
expect(black.game!.isMyTurn, isTrue);
await black.service.makeMove(black.game!, 'e7e5');
expect(white.game!.ply, 2);
});
test('a move the radio did not confirm is kept and sent again', () async {
final alice = player('Alice');
final bob = player('Bob');
final (white, black) = await startGame(alice, bob);
final next = white.game!.myNextChainIndex;
white.link.failNext = true;
expect(await white.service.makeMove(white.game!, 'e2e4'), isFalse);
// Applied, with its chain value used up.
expect(white.game!.ply, 1);
expect(white.game!.moveUnconfirmed, isTrue);
expect(white.game!.myNextChainIndex, next + 1);
expect(black.game!.ply, 0);
await white.service.requestUpdate(white.game!);
expect(black.game!.ply, 1);
expect(white.game!.moveUnconfirmed, isFalse);
// A failed action does not give its chain value back either.
black.link.failNext = true;
final before = black.game!.myNextChainIndex;
expect(await black.service.offerDraw(black.game!), isFalse);
expect(black.game!.myNextChainIndex, before + 1);
expect(await black.service.makeMove(black.game!, 'e7e5'), isTrue);
expect(white.game!.ply, 2);
});
test(
'a move that went out despite a failed send is not replaced',
() async {
final alice = player('Alice');
final bob = player('Bob');
final (white, black) = await startGame(alice, bob);
white.link
..failNext = true
..deliverFailed = true;
await white.service.makeMove(white.game!, 'e2e4');
expect(black.game!.ply, 1);
expect(white.game!.isMyTurn, isFalse);
expect(await white.service.makeMove(white.game!, 'd2d4'), isFalse);
expect(white.game!.fen, black.game!.fen);
},
);
test('draw accepts and timeout claims need their preconditions', () async {
final alice = player('Alice');
final bob = player('Bob');
final carol = player('Carol');
final (white, black) = await startGame(alice, bob);
final whiteChain = white.game!.myChain!;
var next = white.game!.myNextChainIndex;
ChessActionPacket action(ChessPacketKind kind) => ChessActionPacket(
kind: kind,
gameId: white.game!.gameId,
ply: white.game!.ply,
chainValue: whiteChain.valueAt(next++),
);
// No draw offer pending.
final accept = action(ChessPacketKind.drawAccept);
feed(black, accept);
feed(carol, accept);
expect(black.game!.status, ChessGameStatus.active);
expect(carol.game!.status, ChessGameStatus.active);
// Black to move, but the hour is not up yet.
white.game!.myNextChainIndex = next;
await white.service.makeMove(white.game!, 'e2e4');
next = white.game!.myNextChainIndex;
now = now.add(const Duration(minutes: 30));
feed(black, action(ChessPacketKind.timeoutClaim));
expect(black.game!.status, ChessGameStatus.active);
// Past the deadline it counts.
now = now.add(const Duration(minutes: 31));
feed(black, action(ChessPacketKind.timeoutClaim));
expect(black.game!.endReason, ChessEndReason.timeout);
// No deadline at all: never.
final erin = player('Erin');
final finn = player('Finn');
final invite = await erin.service.createInvite(
channelId: _channel,
deadline: ChessDeadline.none,
colour: ChessColourPreference.white,
);
await finn.service.accept(finn.service.game(_channel, invite!.gameId)!);
await settle();
final e = erin.service.game(_channel, invite.gameId)!;
await erin.service.makeMove(e, 'e2e4');
now = now.add(const Duration(days: 30));
final claim = ChessActionPacket(
kind: ChessPacketKind.timeoutClaim,
gameId: e.gameId,
ply: e.ply,
chainValue: e.myChain!.valueAt(e.myNextChainIndex),
);
feed(finn, claim);
expect(
finn.service.game(_channel, invite.gameId)!.status,
ChessGameStatus.active,
);
});
test('notifications for the open game resume in the background', () async {
var foreground = true;
final alice = player('Alice');
final bob = player('Bob', isForeground: () => foreground);
final (white, black) = await startGame(alice, bob);
expect(black, same(bob));
bob.service.viewing = bob.game;
await white.service.makeMove(white.game!, 'e2e4');
expect(bob.link.notifications, isEmpty);
await black.service.makeMove(black.game!, 'e7e5');
foreground = false;
await white.service.makeMove(white.game!, 'd2d4');
expect(bob.link.notifications, hasLength(1));
});
test('the game cap keeps our own invites and accepts', () async {
final alice = player('Alice');
final bob = player('Bob');
final mine = await alice.service.createInvite(channelId: _channel);
final theirs = await bob.service.createInvite(channelId: _channel);
await alice.service.accept(alice.service.game(_channel, theirs!.gameId)!);
now = now.add(const Duration(minutes: 1));
for (var i = 0; i < ChessService.maxStoredGames + 5; i++) {
feed(
alice,
ChessInvitePacket(
gameId: 1000 + i,
deadline: ChessDeadline.hour1,
colour: ChessColourPreference.random,
commitment: Uint8List(16)..[0] = i,
inviterName: 'Spam $i',
),
);
}
alice.service.housekeeping();
expect(alice.service.game(_channel, mine!.gameId), isNotNull);
expect(alice.service.game(_channel, theirs.gameId), isNotNull);
});
test('only the inviter acts on a decline', () async {
final alice = player('Alice');
final bob = player('Bob');
final carol = player('Carol');
await alice.service.createInvite(channelId: _channel, targetName: 'Bob');
feed(
carol,
ChessDeclinePacket(gameId: alice.game!.gameId, declinerName: 'Bob'),
);
expect(carol.game!.status, ChessGameStatus.invite);
expect(bob.game!.status, ChessGameStatus.invite);
// The challenge to Bob is neither listed nor counted for Carol.
expect(carol.service.isListed(carol.game!), isFalse);
expect(carol.service.openCountForChannel(_channel), 0);
expect(bob.service.openCountForChannel(_channel), 1);
});
test('a late joiner keeps the full ply and takes the deadline from the '
'game info', () async {
final alice = player('Alice');
final bob = player('Bob');
final (white, _) = await startGame(alice, bob);
final g = white.game!;
final move = ChessMovePacket(
gameId: g.gameId,
ply: 301,
moveIndex: 0,
chainValue: Uint8List(16),
position: g.packedPosition(),
);
final dave = player('Dave');
feed(dave, move);
expect(dave.game!.ply, 301);
expect(dave.game!.deadline, ChessDeadline.none);
feed(dave, sentOf<ChessInfoPacket>(alice).single);
expect(dave.game!.hasPlayers, isTrue);
expect(dave.game!.deadline, ChessDeadline.hour1);
});
test('a spectator who hears the game info mid-game takes the board from '
'the latest move', () async {
final alice = player('Alice');
final bob = player('Bob');
final (white, black) = await startGame(alice, bob);
await white.service.makeMove(white.game!, 'e2e4');
await black.service.makeMove(black.game!, 'e7e5');
final dave = player('Dave');
await dave.service.requestUpdate(
ChessGame(
channelId: _channel,
gameId: alice.game!.gameId,
status: ChessGameStatus.active,
deadline: ChessDeadline.none,
hasPosition: false,
createdAtMs: 0,
),
);
await settle();
expect(dave.game!.hasPlayers, isTrue);
expect(dave.game!.ply, 2);
expect(dave.game!.hasPosition, isTrue);
expect(dave.game!.fen, alice.game!.fen);
});
test(
'a lost checkmate reaches the opponent who sends their move again',
() async {
final alice = player('Alice');
final bob = player('Bob');
final (white, black) = await startGame(alice, bob);
const moves = ['e2e4', 'e7e5', 'f1c4', 'b8c6', 'd1h5', 'g8f6'];
for (var i = 0; i < moves.length; i++) {
final mover = i.isEven ? white : black;
await mover.service.makeMove(mover.game!, moves[i]);
}
mesh.filter = (from, to, _) =>
!(from == white.link && to == black.link);
await white.service.makeMove(white.game!, 'h5f7');
mesh.filter = null;
expect(white.game!.endReason, ChessEndReason.checkmate);
expect(black.game!.status, ChessGameStatus.active);
// Black's Ask for update re-sends g8f6; White answers with the mate.
await black.service.requestUpdate(black.game!);
await settle();
expect(black.game!.status, ChessGameStatus.finished);
expect(black.game!.endReason, ChessEndReason.checkmate);
expect(black.game!.winner, ChessSide.white);
// Rate-limited like other answers.
final sent = white.link.sent.length;
feed(white, sentOf<ChessMovePacket>(black).last);
await settle();
expect(white.link.sent.length, sent);
},
);
test('a lost resignation is sent again with recovery answers', () async {
final alice = player('Alice');
final bob = player('Bob');
final carol = player('Carol');
final (white, black) = await startGame(alice, bob);
await white.service.makeMove(white.game!, 'e2e4');
await black.service.makeMove(black.game!, 'e7e5');
mesh.filter = (from, to, payload) =>
!(from == white.link &&
ChessPacket.decode(payload) is ChessActionPacket);
expect(await white.service.resign(white.game!), isTrue);
expect(white.game!.finalActionPacket, isNotNull);
expect(black.game!.status, ChessGameStatus.active);
expect(carol.game!.status, ChessGameStatus.active);
// Kept across a restart.
await white.service.store.flush();
final reloaded = ChessStore().load(white.link.storageScope).single;
expect(reloaded.finalActionPacket, white.game!.finalActionPacket);
// Black re-sends its move; White answers with the resignation. Carol
// still misses it.
mesh.filter = (from, to, payload) =>
!(to == carol.link &&
ChessPacket.decode(payload) is ChessActionPacket);
await black.service.requestUpdate(black.game!);
await settle();
expect(black.game!.endReason, ChessEndReason.resignation);
expect(black.game!.winner, black.game!.mySide);
expect(carol.game!.status, ChessGameStatus.active);
// Carol asks; a player answers with the resignation.
mesh.filter = null;
now = now.add(ChessService.requestAnswerInterval);
await carol.service.requestUpdate(carol.game!);
await settle();
expect(carol.game!.endReason, ChessEndReason.resignation);
expect(carol.game!.winner, ChessSide.black);
// Hearing it again changes nothing.
final resign = sentOf<ChessActionPacket>(white).first;
final index = carol.game!.white!.lastIndex;
feed(carol, resign);
expect(carol.game!.white!.lastIndex, index);
expect(carol.game!.endReason, ChessEndReason.resignation);
});
test('a draw accept or timeout claim that crosses a move does not '
'apply', () async {
final alice = player('Alice');
final bob = player('Bob');
final (white, black) = await startGame(alice, bob);
await white.service.makeMove(white.game!, 'e2e4');
now = now.add(const Duration(hours: 1, minutes: 11));
expect(white.service.canClaimTimeout(white.game!), isTrue);
// White's claim and Black's move cross on air.
Uint8List? claim;
mesh.filter = (from, to, payload) {
if (from == white.link &&
ChessPacket.decode(payload) is ChessActionPacket) {
claim = payload;
return false;
}
return true;
};
white.link.slow = true;
Timer.run(() => black.service.makeMove(black.game!, 'e7e5'));
expect(await white.service.claimTimeout(white.game!), isFalse);
await settle();
black.service.handleIncoming(ChessIncoming(_channel, claim!));
for (final p in [white, black]) {
expect(p.game!.status, ChessGameStatus.active);
expect(p.game!.ply, 2);
}
// The claim's value is used up on both sides.
final claimIndex = white.game!.myNextChainIndex - 1;
expect(white.game!.playerOf(white.game!.mySide!)!.lastIndex, claimIndex);
expect(black.game!.playerOf(ChessSide.white)!.lastIndex, claimIndex);
// Same for a draw accept crossing a move.
claim = null;
await white.service.makeMove(white.game!, 'g1f3');
await black.service.offerDraw(black.game!);
expect(white.game!.drawOfferedBy, ChessSide.black);
// Black then moves after all, while White accepts.
Timer.run(() => black.service.makeMove(black.game!, 'b8c6'));
expect(await white.service.acceptDraw(white.game!), isFalse);
await settle();
black.service.handleIncoming(ChessIncoming(_channel, claim!));
for (final p in [white, black]) {
expect(p.game!.status, ChessGameStatus.active);
expect(p.game!.ply, 4);
}
mesh.filter = null;
white.link.slow = false;
expect(await white.service.makeMove(white.game!, 'f1c4'), isTrue);
expect(black.game!.ply, 5);
});
test('a malformed position never throws out of the listener', () {
final carol = player('Carol');
final packet = Uint8List.fromList(
ChessMovePacket(
gameId: 5,
ply: 1,
moveIndex: 0,
chainValue: Uint8List(16),
position: Uint8List(10),
).encode(),
);
expect(
() => carol.service.handleIncoming(ChessIncoming(_channel, packet)),
returnsNormally,
);
});
});
}
+177
View File
@@ -0,0 +1,177 @@
import 'dart:async';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/connector/meshcore_connector.dart';
import 'package:meshcore_open/games/chess/chess_game.dart';
import 'package:meshcore_open/games/chess/chess_link.dart';
import 'package:meshcore_open/games/chess/chess_packets.dart';
import 'package:meshcore_open/games/chess/chess_service.dart';
import 'package:meshcore_open/games/chess/ui/chess_board.dart';
import 'package:meshcore_open/games/chess/ui/chess_game_screen.dart';
import 'package:meshcore_open/l10n/app_localizations.dart';
import 'package:meshcore_open/models/channel.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:meshcore_open/theme/mesh_theme.dart';
import 'package:meshcore_open/games/chess/ui/chess_games_sheet.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
final _l10n = lookupAppLocalizations(const Locale('en'));
class _ConnectedConnector extends MeshCoreConnector {
@override
bool get isConnected => true;
}
class _Link extends ChangeNotifier implements ChessLink {
final controller = StreamController<ChessIncoming>.broadcast(sync: true);
final sent = <Uint8List>[];
@override
Stream<ChessIncoming> get incoming => controller.stream;
@override
Future<bool> send(String channelId, Uint8List payload) async {
sent.add(payload);
return true;
}
@override
String get selfName => 'Me';
@override
String get storageScope => 'ui00000000';
@override
bool get canSend => true;
@override
void notify(String channelId, String text) {}
@override
AppLocalizations get l10n => _l10n;
}
void main() {
late Channel channel;
late String channelId;
late _Link link;
late ChessService service;
late ChessGame myGame;
setUp(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
channel = Channel(index: 0, name: 'Public', psk: Uint8List(16)..[0] = 9);
channelId = channel.storageId!;
link = _Link();
service = ChessService(link: link, startHousekeeping: false);
// Our own invite, accepted by Bob, so we play white.
myGame = (await service.createInvite(
channelId: channelId,
colour: ChessColourPreference.white,
))!;
link.controller.add(
ChessIncoming(
channelId,
ChessAcceptPacket(
gameId: myGame.gameId,
commitment: Uint8List(16)..[3] = 7,
accepterName: 'Bob',
).encode(),
),
);
link.controller.add(
ChessIncoming(
channelId,
ChessInvitePacket(
gameId: 4242,
deadline: ChessDeadline.day1,
colour: ChessColourPreference.random,
commitment: Uint8List(16)..[1] = 1,
inviterName: 'Carol',
).encode(),
),
);
});
tearDown(() => service.dispose());
Widget app(Widget home) => MultiProvider(
providers: [
ChangeNotifierProvider<MeshCoreConnector>.value(
value: _ConnectedConnector(),
),
ChangeNotifierProvider.value(value: service),
],
child: MaterialApp(
theme: MeshTheme.light(),
locale: const Locale('en'),
localizationsDelegates: const [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: AppLocalizations.supportedLocales,
home: home,
),
);
testWidgets('sheet lists our game and the open invite', (tester) async {
// A cancelled invite of ours, listed under Finished.
final cancelled = await tester.runAsync(
() => service.createInvite(channelId: channelId),
);
await tester.runAsync(() => service.cancelInvite(cancelled!));
tester.view.physicalSize = const Size(400, 2000);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
await tester.pumpWidget(
app(
Builder(
builder: (context) => Scaffold(
body: TextButton(
onPressed: () => showChessGamesSheet(context, channel),
child: const Text('open'),
),
),
),
),
);
await tester.tap(find.text('open'));
await tester.pumpAndSettle();
expect(find.text(_l10n.chess_sectionYourGames.toUpperCase()), findsOne);
expect(find.text(_l10n.chess_vs('Me', 'Bob')), findsOne);
expect(find.text(_l10n.chess_rowOpenInvite('Carol')), findsOne);
expect(find.text(_l10n.chess_accept), findsOne);
expect(find.text(_l10n.chess_rowYourOpenInvite), findsOne);
expect(find.text(_l10n.chess_endCancelled), findsOne);
expect(find.text(_l10n.chess_vs('Unknown', 'Unknown')), findsNothing);
});
testWidgets('tapping a piece and a target sends the move', (tester) async {
tester.view.physicalSize = const Size(400, 1600);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
await tester.pumpWidget(
app(ChessGameScreen(channelId: channelId, gameId: myGame.gameId)),
);
await tester.pump();
expect(find.byType(ChessBoardView), findsOne);
expect(find.text(_l10n.chess_statusYourMove), findsWidgets);
await tester.tap(
find.bySemanticsLabel(
_l10n.chess_squareWhitePiece('e2', _l10n.chess_piecePawn),
),
);
await tester.pump();
await tester.tap(find.bySemanticsLabel('e4'));
await tester.pumpAndSettle();
final move = ChessPacket.decode(link.sent.last);
expect(move, isA<ChessMovePacket>());
expect(myGame.sanMoves, ['e4']);
expect(find.text(_l10n.chess_statusWaiting('Bob')), findsOne);
});
}
+92
View File
@@ -0,0 +1,92 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/helpers/chat_scroll_anchor.dart';
/// A reversed chat list of rows with uneven heights. [add] appends newer
/// rows, which land at index 0 below everything else.
class _Harness {
final controller = ScrollController();
final anchor = ChatScrollAnchor();
var items = List.generate(100, (i) => 'm$i');
late StateSetter _setState;
Widget build() => MaterialApp(
home: Scaffold(
body: StatefulBuilder(
builder: (context, setState) {
_setState = setState;
final rows = items.reversed.toList();
return AnchoredChatListView.builder(
scrollAnchor: anchor,
reverse: true,
controller: controller,
padding: const EdgeInsets.all(16),
itemCount: rows.length,
itemBuilder: (context, i) => SizedBox(
height: 40.0 + (int.parse(rows[i].substring(1)) % 5) * 20,
child: Text(rows[i]),
),
);
},
),
),
);
void add(int count, {bool anchored = true}) {
_setState(() {
final start = items.length;
items = [...items, for (var i = 0; i < count; i++) 'n${start + i}'];
if (anchored) anchor.rowsInsertedBelow(count);
});
}
}
void main() {
for (final count in [1, 3, 30, 300]) {
testWidgets('$count rows added below keep the visible rows in place', (
tester,
) async {
final harness = _Harness();
addTearDown(harness.controller.dispose);
await tester.pumpWidget(harness.build());
harness.controller.jumpTo(2000);
await tester.pump();
final row = find.text('m72');
expect(row, findsOneWidget);
final before = tester.getTopLeft(row).dy;
harness.add(count);
await tester.pump();
expect(row, findsOneWidget);
expect(tester.getTopLeft(row).dy, moreOrLessEquals(before));
expect(harness.controller.position.pixels, greaterThan(2000));
});
}
testWidgets('without the anchor the rows on screen move', (tester) async {
final harness = _Harness();
addTearDown(harness.controller.dispose);
await tester.pumpWidget(harness.build());
harness.controller.jumpTo(2000);
await tester.pump();
final before = tester.getTopLeft(find.text('m72')).dy;
harness.add(3, anchored: false);
await tester.pump();
expect(tester.getTopLeft(find.text('m72')).dy, isNot(before));
});
testWidgets('a list at the bottom is left at the bottom', (tester) async {
final harness = _Harness();
addTearDown(harness.controller.dispose);
await tester.pumpWidget(harness.build());
harness.add(3, anchored: false);
await tester.pump();
expect(harness.controller.position.pixels, 0);
expect(find.text('n102'), findsOneWidget);
});
}
+219
View File
@@ -0,0 +1,219 @@
import 'package:flutter/foundation.dart';
import 'package:flutter_linkify/flutter_linkify.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/helpers/coordinate_parser.dart';
void main() {
group('CoordinateParser.parse', () {
test('parses positive and negative decimal pairs', () {
const inputs = [
('37.7749,-122.4194', 37.7749, -122.4194),
('38.722,-9.139', 38.722, -9.139),
('-33.86882, 151.20929', -33.86882, 151.20929),
('51.5074, -0.1278', 51.5074, -0.1278),
('0.0, 0.0', 0.0, 0.0),
('45.515232, -122.678385', 45.515232, -122.678385),
('37.77491234, -122.41945678', 37.77491234, -122.41945678),
];
for (final (text, expectedLat, expectedLon) in inputs) {
final parsed = CoordinateParser.parse(text);
expect(parsed, hasLength(1), reason: 'Failed for "$text"');
expect(parsed.first.latitude, closeTo(expectedLat, 1e-12));
expect(parsed.first.longitude, closeTo(expectedLon, 1e-12));
expect(parsed.first.rawText, text);
expect(parsed.first.start, 0);
expect(parsed.first.end, text.length);
}
});
test('parses explicit + signs and optional whitespace after comma', () {
final parsed = CoordinateParser.parse(
'Meet at +37.7749,+122.4194 or +45.5152,\t-122.6784',
);
expect(parsed, hasLength(2));
expect(parsed[0].rawText, '+37.7749,+122.4194');
expect(parsed[0].latitude, 37.7749);
expect(parsed[0].longitude, 122.4194);
expect(parsed[1].rawText, '+45.5152,\t-122.6784');
expect(parsed[1].latitude, 45.5152);
expect(parsed[1].longitude, -122.6784);
});
test('accepts WGS84 boundary coordinates and rejects out-of-range', () {
final validBounds = CoordinateParser.parse(
'90.0, 180.0 and -90.0, -180.0',
);
expect(validBounds, hasLength(2));
expect(validBounds[0].latitude, 90.0);
expect(validBounds[0].longitude, 180.0);
expect(validBounds[1].latitude, -90.0);
expect(validBounds[1].longitude, -180.0);
const invalidBounds = [
'90.0001, 0.0',
'-90.1, 0.0',
'0.0, 180.0001',
'0.0, -180.1',
'990.0, -180.0',
'123.45, 67.89',
];
for (final text in invalidBounds) {
expect(
CoordinateParser.parse(text),
isEmpty,
reason: 'Should reject "$text"',
);
}
});
test('rejects plain integer pairs and mixed integer/decimal pairs', () {
const invalid = [
'1,2',
'10, 20',
'-45, 122',
'37,-122.4194',
'37.7749,-122',
];
for (final text in invalid) {
expect(
CoordinateParser.parse(text),
isEmpty,
reason: 'Should reject "$text"',
);
}
});
test('rejects version numbers and digits inside words or identifiers', () {
const invalid = [
'1.2.3,4.5',
'1.2,3.4.5',
'1.2, 3.4.5',
'1.2.3, 4.5.6',
'v1.2,3.4',
'foo37.7749,-122.4194',
'37.7749,-122.4194bar',
'id_37.7749,-122.4194',
'37.7749,-122.4194_end',
'--37.7749,-122.4194',
'+-37.7749,-122.4194',
'1.2,3.4-5',
];
for (final text in invalid) {
expect(
CoordinateParser.parse(text),
isEmpty,
reason: 'Should reject "$text"',
);
}
});
test('handles punctuation boundaries around coordinates', () {
const text =
'Camp (37.7749, -122.4194), ridge [45.5152,-122.6784], end 38.722,-9.139.';
final parsed = CoordinateParser.parse(text);
expect(parsed, hasLength(3));
expect(parsed[0].rawText, '37.7749, -122.4194');
expect(text.substring(parsed[0].start, parsed[0].end), parsed[0].rawText);
expect(parsed[1].rawText, '45.5152,-122.6784');
expect(text.substring(parsed[1].start, parsed[1].end), parsed[1].rawText);
expect(parsed[2].rawText, '38.722,-9.139');
expect(text.substring(parsed[2].start, parsed[2].end), parsed[2].rawText);
});
test('parses multiple coordinates and #wardriving messages', () {
const wardriving =
'#wardriving 37.7749,-122.4194 SNR: 8.5dB -> (37.7812, -122.4111) '
'and 38.722,-9.139, 51.5074, -0.1278';
final parsed = CoordinateParser.parse(wardriving);
expect(parsed, hasLength(4));
expect(parsed.map((c) => c.rawText).toList(), [
'37.7749,-122.4194',
'37.7812, -122.4111',
'38.722,-9.139',
'51.5074, -0.1278',
]);
});
test('does not misparse coordinates inside URLs or emails', () {
const urlOnly = [
'https://maps.google.com/?q=37.7749,-122.4194',
'https://www.openstreetmap.org/?mlat=37.7749&mlon=-122.4194#map=16/37.7749/-122.4194',
'https://example.com/@37.7749,-122.4194,15z',
'geo:37.7749,-122.4194',
'maps.google.com/?q=37.7749,-122.4194',
];
for (final text in urlOnly) {
expect(
CoordinateParser.parse(text),
isEmpty,
reason: 'Should not parse coordinate inside "$text"',
);
}
const mixed =
'Route https://maps.google.com/?q=10.0,20.0 meet at 37.7749, -122.4194';
final parsed = CoordinateParser.parse(mixed);
expect(parsed, hasLength(1));
expect(parsed.first.rawText, '37.7749, -122.4194');
final elements = CoordinateParser.linkifyWithCoordinates(mixed);
expect(elements.whereType<UrlElement>(), hasLength(1));
expect(elements.whereType<CoordinateElement>(), hasLength(1));
});
});
group('buildExternalMapUri', () {
test('builds platform-appropriate map URIs', () {
expect(
buildExternalMapUri(
37.7749,
-122.4194,
platform: TargetPlatform.android,
isWeb: false,
).toString(),
'geo:37.7749,-122.4194?q=37.7749,-122.4194',
);
expect(
buildExternalMapUri(
37.7749,
-122.4194,
platform: TargetPlatform.iOS,
isWeb: false,
).toString(),
'https://maps.apple.com/?ll=37.7749,-122.4194&q=37.7749,-122.4194',
);
expect(
buildExternalMapUri(
37.7749,
-122.4194,
platform: TargetPlatform.macOS,
isWeb: false,
).toString(),
'https://maps.apple.com/?ll=37.7749,-122.4194&q=37.7749,-122.4194',
);
expect(
buildExternalMapUri(
37.7749,
-122.4194,
platform: TargetPlatform.linux,
isWeb: false,
).toString(),
'https://www.openstreetmap.org/?mlat=37.7749&mlon=-122.4194#map=16/37.7749/-122.4194',
);
expect(
buildExternalMapUri(
37.7749,
-122.4194,
platform: TargetPlatform.windows,
isWeb: false,
).toString(),
'https://www.openstreetmap.org/?mlat=37.7749&mlon=-122.4194#map=16/37.7749/-122.4194',
);
expect(
buildExternalMapUri(-0.0, -0.0, isWeb: true).toString(),
'https://www.openstreetmap.org/?mlat=0.0&mlon=0.0#map=16/0.0/0.0',
);
});
});
}
+336 -1
View File
@@ -8,13 +8,16 @@ import 'package:meshcore_open/models/contact.dart';
Contact _contact({
required int prefix,
int? secondByte,
required String name,
required double latitude,
required double longitude,
DateTime? lastSeen,
}) {
final key = Uint8List(32)..first = prefix;
if (secondByte != null) key[1] = secondByte;
return Contact(
publicKey: Uint8List(32)..first = prefix,
publicKey: key,
name: name,
type: advTypeRepeater,
pathLength: 0,
@@ -91,4 +94,336 @@ void main() {
expect(resolved.single?.name, 'Newer');
});
test(
'rejects single candidate impossibly far and preserves previousPosition',
() {
// Arizona self/local repeaters vs East Coast collision (~3700 km away).
const selfArizona = LatLng(33.4484, -112.0740);
final azHop1 = _contact(
prefix: 0x48,
name: 'AZ Repeater 1',
latitude: 33.60097,
longitude: -112.02457,
);
final eastCoastBogus = _contact(
prefix: 0x9C,
name: 'East Coast 9C',
latitude: 42.3601,
longitude: -71.0589,
);
final azHop3 = _contact(
prefix: 0x53,
name: 'AZ Repeater 2',
latitude: 33.46300,
longitude: -111.65000,
);
final resolved = PathHopResolver.resolve(
pathBytes: const [0x53, 0x9C, 0x48],
contacts: [azHop1, eastCoastBogus, azHop3],
endpoint: selfArizona,
resolveFromEnd: true,
);
expect(resolved.map((c) => c?.name), [
'AZ Repeater 2',
null,
'AZ Repeater 1',
]);
},
);
test('rejects multiple candidates when all are impossibly far', () {
const selfArizona = LatLng(33.4484, -112.0740);
final eastCoast = _contact(
prefix: 0x9C,
name: 'East Coast 9C',
latitude: 42.3601,
longitude: -71.0589,
lastSeen: DateTime.utc(2026, 2),
);
final europe = _contact(
prefix: 0x9C,
name: 'Europe 9C',
latitude: 48.8566,
longitude: 2.3522,
lastSeen: DateTime.utc(2026, 1),
);
final resolved = PathHopResolver.resolve(
pathBytes: const [0x9C],
contacts: [eastCoast, europe],
endpoint: selfArizona,
);
expect(resolved, [null]);
});
test(
'picks plausible candidate when another candidate is impossibly far',
() {
const selfArizona = LatLng(33.4484, -112.0740);
final eastCoastNewer = _contact(
prefix: 0x9C,
name: 'East Coast 9C',
latitude: 42.3601,
longitude: -71.0589,
lastSeen: DateTime.utc(2026, 5),
);
final localOlder = _contact(
prefix: 0x9C,
name: 'Local AZ 9C',
latitude: 33.50,
longitude: -111.90,
lastSeen: DateTime.utc(2026, 1),
);
final resolved = PathHopResolver.resolve(
pathBytes: const [0x9C],
contacts: [eastCoastNewer, localOlder],
endpoint: selfArizona,
);
expect(resolved.single?.name, 'Local AZ 9C');
},
);
test('consecutive unresolved hops widen distance budget proportionally', () {
// At equator, 1 degree longitude is ~111.32 km.
// With 2 unresolved intermediate hops (hopGap = 3), budget is 3 * 250 km = 750 km.
// 6.0 degrees (~667.9 km) is beyond 1-hop (250 km) and 2-hop (500 km),
// but within 3-hop (750 km).
const endpoint = LatLng(0, 0);
final distantValid = _contact(
prefix: 0xCC,
name: 'Valid 3-hop target',
latitude: 0,
longitude: 6.0,
);
final resolvedWithTwoUnknowns = PathHopResolver.resolve(
pathBytes: const [0xAA, 0xBB, 0xCC],
contacts: [distantValid],
endpoint: endpoint,
);
expect(resolvedWithTwoUnknowns, [null, null, distantValid]);
// With only 1 hop (hopGap = 1, budget = 250 km), 6.0 degrees is rejected.
final resolvedDirect = PathHopResolver.resolve(
pathBytes: const [0xCC],
contacts: [distantValid],
endpoint: endpoint,
);
expect(resolvedDirect, [null]);
});
test(
'endpoint == null rejects a leading distant outlier and keeps local cluster',
() {
final bogusFirst = _contact(
prefix: 0x9C,
name: 'East Coast Outlier',
latitude: 42.3601,
longitude: -71.0589,
lastSeen: DateTime.utc(2026, 6),
);
final local1 = _contact(
prefix: 0x48,
name: 'Local 1',
latitude: 33.60097,
longitude: -112.02457,
);
final local2 = _contact(
prefix: 0x53,
name: 'Local 2',
latitude: 33.46300,
longitude: -111.65000,
);
final local3 = _contact(
prefix: 0x6C,
name: 'Local 3',
latitude: 33.42,
longitude: -111.80,
);
final resolved = PathHopResolver.resolve(
pathBytes: const [0x9C, 0x48, 0x53, 0x6C],
contacts: [bogusFirst, local1, local2, local3],
endpoint: null,
);
expect(resolved.map((c) => c?.name), [
null,
'Local 1',
'Local 2',
'Local 3',
]);
},
);
test(
'endpoint != null rejects first-hop outlier and resolves subsequent local hops',
() {
const selfArizona = LatLng(33.4484, -112.0740);
final bogusFirst = _contact(
prefix: 0xEA,
name: 'East Coast First Hop',
latitude: 42.3601,
longitude: -71.0589,
);
final local2 = _contact(
prefix: 0x48,
name: 'Local 2',
latitude: 33.60097,
longitude: -112.02457,
);
final local3 = _contact(
prefix: 0x53,
name: 'Local 3',
latitude: 33.46300,
longitude: -111.65000,
);
final resolved = PathHopResolver.resolve(
pathBytes: const [0xEA, 0x48, 0x53],
contacts: [bogusFirst, local2, local3],
endpoint: selfArizona,
);
expect(resolved.map((c) => c?.name), [null, 'Local 2', 'Local 3']);
},
);
test('legitimate long-range line-of-sight LoRa hops still resolve', () {
// ~200 km mountain-to-mountain hop (within 250 km single-hop budget).
const self = LatLng(33.4484, -112.0740);
final mountainPeak = _contact(
prefix: 0xAA,
name: 'Mountain Peak',
latitude: 35.1983,
longitude: -111.6513, // Flagstaff (~198 km from Phoenix)
);
final secondPeak = _contact(
prefix: 0xBB,
name: 'North Rim',
latitude: 36.2100,
longitude: -112.0600, // ~118 km from Flagstaff
);
final resolved = PathHopResolver.resolve(
pathBytes: const [0xAA, 0xBB],
contacts: [mountainPeak, secondPeak],
endpoint: self,
);
expect(resolved.map((c) => c?.name), ['Mountain Peak', 'North Rim']);
});
test('multi-byte path hash width rejects impossible hop', () {
const self = LatLng(33.4484, -112.0740);
final local = _contact(
prefix: 0x48,
secondByte: 0x01,
name: 'Local 2-byte',
latitude: 33.60,
longitude: -112.02,
);
final bogus = _contact(
prefix: 0x9C,
secondByte: 0x02,
name: 'Bogus 2-byte',
latitude: 40.7128,
longitude: -74.0060,
);
final resolved = PathHopResolver.resolve(
pathBytes: const [0x48, 0x01, 0x9C, 0x02],
contacts: [local, bogus],
endpoint: self,
pathHashByteWidth: 2,
);
expect(resolved.map((c) => c?.name), ['Local 2-byte', null]);
});
test(
'preferredContacts overrides nearer general contact with same prefix when plausible',
() {
const self = LatLng(33.4484, -112.0740);
final nearerGeneral = _contact(
prefix: 0x48,
secondByte: 0x01,
name: 'Nearer General 48',
latitude: 33.4600,
longitude: -112.0700,
lastSeen: DateTime.utc(2026, 6),
);
final selectedPreferred = _contact(
prefix: 0x48,
secondByte: 0x02,
name: 'Selected Preferred 48',
latitude: 33.9000,
longitude: -111.7000,
lastSeen: DateTime.utc(2026, 1),
);
final secondHopGeneral = _contact(
prefix: 0x53,
name: 'Second Hop 53',
latitude: 33.9500,
longitude: -111.6500,
);
final resolvedWithEndpoint = PathHopResolver.resolve(
pathBytes: const [0x48, 0x53],
contacts: [nearerGeneral, selectedPreferred, secondHopGeneral],
preferredContacts: [selectedPreferred],
endpoint: self,
);
expect(resolvedWithEndpoint.map((c) => c?.name), [
'Selected Preferred 48',
'Second Hop 53',
]);
final resolvedWithoutEndpoint = PathHopResolver.resolve(
pathBytes: const [0x48, 0x53],
contacts: [nearerGeneral, selectedPreferred, secondHopGeneral],
preferredContacts: [selectedPreferred],
endpoint: null,
);
expect(resolvedWithoutEndpoint.map((c) => c?.name), [
'Selected Preferred 48',
'Second Hop 53',
]);
},
);
test(
'impossibly far preferredContact is rejected and falls back to plausible general contact',
() {
const self = LatLng(33.4484, -112.0740);
final bogusPreferred = _contact(
prefix: 0x9C,
secondByte: 0x01,
name: 'East Coast Preferred 9C',
latitude: 42.3601,
longitude: -71.0589,
);
final localGeneral = _contact(
prefix: 0x9C,
secondByte: 0x02,
name: 'Local General 9C',
latitude: 33.60097,
longitude: -112.02457,
);
final resolved = PathHopResolver.resolve(
pathBytes: const [0x9C],
contacts: [bogusPreferred, localGeneral],
preferredContacts: [bogusPreferred],
endpoint: self,
);
expect(resolved.map((c) => c?.name), ['Local General 9C']);
},
);
}
@@ -1,4 +1,5 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/models/bookmarked_message.dart';
import 'package:meshcore_open/models/channel_message.dart';
void main() {
@@ -25,5 +26,52 @@ void main() {
test('outgoing message without reply has no reply target', () {
final message = ChannelMessage.outgoing('hello', 'Me', 0);
expect(message.replyToMessageId, isNull);
expect(message.fullText, 'hello');
});
test('fullText restores @[username] prefix for stored replies', () {
final storedReply = ChannelMessage(
senderName: 'Me',
text: 'answer',
timestamp: DateTime(2026, 1, 1, 12),
isOutgoing: true,
replyToMessageId: 'msg-1',
replyToSenderName: 'Alice',
replyToText: 'question',
);
expect(storedReply.fullText, '@[Alice] answer');
final bookmark = BookmarkedMessage.fromChannel(
message: storedReply,
channelId: 'ch-0',
channelName: 'Public',
senderName: 'Me',
);
expect(bookmark.text, '@[Alice] answer');
});
test('fullText preserves nested mention and special payloads in replies', () {
final nestedReply = ChannelMessage(
senderName: 'Bob',
text: '@[Alice] nested',
timestamp: DateTime(2026, 1, 1, 12),
isOutgoing: false,
replyToMessageId: 'msg-1',
replyToSenderName: 'Alice',
replyToText: 'original',
);
expect(nestedReply.fullText, '@[Alice] @[Alice] nested');
final gifReply = ChannelMessage(
senderName: 'Bob',
text: 'g:abc123',
timestamp: DateTime(2026, 1, 1, 12),
isOutgoing: false,
replyToMessageId: 'msg-1',
replyToSenderName: 'Alice',
replyToText: 'original',
);
expect(gifReply.fullText, '@[Alice] g:abc123');
});
}
+349
View File
@@ -0,0 +1,349 @@
import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/connector/meshcore_connector.dart';
import 'package:meshcore_open/connector/meshcore_protocol.dart';
import 'package:meshcore_open/helpers/smaz.dart';
import 'package:meshcore_open/models/app_settings.dart';
import 'package:meshcore_open/models/channel_message.dart';
import 'package:meshcore_open/models/chat_compression_mode.dart';
import 'package:meshcore_open/models/message.dart';
import 'package:meshcore_open/review_mode/review_frames.dart';
import 'package:meshcore_open/review_mode/review_radio.dart';
import 'package:meshcore_open/services/app_settings_service.dart';
import 'package:meshcore_open/services/message_retry_service.dart';
import 'package:meshcore_open/services/path_history_service.dart';
import 'package:meshcore_open/services/storage_service.dart';
import 'package:meshcore_open/storage/channel_message_store.dart';
import 'package:meshcore_open/storage/history_store.dart';
import 'package:meshcore_open/storage/message_store.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:shared_preferences/shared_preferences.dart';
const _deviceScope = 'abcdef012345';
const _contactHex =
'1111111111111111111111111111111111111111111111111111111111111111';
const _channelId = '0123456789abcdef';
const _compressibleText =
'This is a long enough English sentence that SMAZ compresses smaller.';
Uint8List _legacyDmFrame(Uint8List senderPubKey, String text, int timestamp) {
final writer = BufferWriter();
writer.writeByte(respCodeContactMsgRecv);
writer.writeBytes(senderPubKey);
writer.writeInt32LE(timestamp);
writer.writeByte(txtTypePlain << 2);
writer.writeString(text);
writer.writeByte(0);
return writer.toBytes();
}
Future<void> _waitFor(bool Function() condition) async {
final end = DateTime.now().add(const Duration(seconds: 8));
while (!condition()) {
if (DateTime.now().isAfter(end)) fail('Timed out waiting for condition');
await Future<void>.delayed(const Duration(milliseconds: 20));
}
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('AppSettings.showCompressionIndicator', () {
test('defaults to false, including for stored JSON without the key', () {
expect(AppSettings().showCompressionIndicator, isFalse);
final legacy = AppSettings().toJson()
..remove('show_compression_indicator');
expect(AppSettings.fromJson(legacy).showCompressionIndicator, isFalse);
});
test(
'round-trips through JSON, copyWith, and AppSettingsService',
() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
final enabled = AppSettings().copyWith(showCompressionIndicator: true);
expect(
AppSettings.fromJson(enabled.toJson()).showCompressionIndicator,
isTrue,
);
expect(
enabled.copyWith(enableMessageTracing: true).showCompressionIndicator,
isTrue,
);
final service = AppSettingsService();
await service.loadSettings();
expect(service.settings.showCompressionIndicator, isFalse);
await service.setShowCompressionIndicator(true);
expect(service.settings.showCompressionIndicator, isTrue);
final reloaded = AppSettingsService();
await reloaded.loadSettings();
expect(reloaded.settings.showCompressionIndicator, isTrue);
},
);
});
group('Message & MessageStore SMAZ flag', () {
setUp(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
HistoryStore.reset();
MessageStore().forgetArchive();
});
test('Message.fromFrame decodes SMAZ and sets isSmazCompressed', () {
final sender = Uint8List.fromList(List.generate(32, (i) => i + 1));
final encoded = Smaz.encodeIfSmaller(_compressibleText);
expect(encoded, startsWith('s:'));
final compressedMsg = Message.fromFrame(
_legacyDmFrame(sender, encoded, 1700000000),
Uint8List(32),
)!;
expect(compressedMsg.text, _compressibleText);
expect(compressedMsg.isSmazCompressed, isTrue);
expect(compressedMsg.copyWith(retryCount: 1).isSmazCompressed, isTrue);
final plainMsg = Message.fromFrame(
_legacyDmFrame(sender, 'plain hello', 1700000001),
Uint8List(32),
)!;
expect(plainMsg.text, 'plain hello');
expect(plainMsg.isSmazCompressed, isFalse);
});
test(
'MessageStore persists flag and defaults legacy rows to false',
() async {
final store = MessageStore()..setPublicKeyHex = _deviceScope;
final key = Uint8List.fromList(List.generate(32, (i) => i + 2));
final compressed = Message.outgoing(
key,
_compressibleText,
isSmazCompressed: true,
);
final plain = Message.outgoing(key, 'hi', isSmazCompressed: false);
await store.saveMessages(_contactHex, [compressed, plain]);
final loaded = await store.loadMessages(_contactHex);
expect(loaded, hasLength(2));
expect(loaded[0].isSmazCompressed, isTrue);
expect(loaded[1].isSmazCompressed, isFalse);
// Legacy persisted message without `isSmazCompressed` key defaults to false.
await HistoryStore.instance.setString(
'${store.keyFor}$_contactHex',
jsonEncode([
{
'senderKey': base64Encode(key),
'text': 'legacy plain',
'timestamp': 1700000002000,
'receivedAt': 1700000002000,
'isOutgoing': false,
'status': MessageStatus.delivered.index,
'plainText': true,
},
]),
);
final legacyLoaded = await store.loadMessages(_contactHex);
expect(legacyLoaded, hasLength(1));
expect(legacyLoaded.first.isSmazCompressed, isFalse);
},
);
});
group('ChannelMessage & ChannelMessageStore SMAZ flag', () {
setUp(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
HistoryStore.reset();
ChannelMessageStore().forgetArchive();
});
test('ChannelMessage.fromFrame decodes SMAZ and sets isSmazCompressed', () {
final encoded = Smaz.encodeIfSmaller(_compressibleText);
expect(encoded, startsWith('s:'));
final compressed = ChannelMessage.fromFrame(
ReviewFrames.channelMessage(
channelIndex: 0,
sender: 'Maya',
message: encoded,
timestampSecs: 1700000000,
),
)!;
expect(compressed.text, _compressibleText);
expect(compressed.isSmazCompressed, isTrue);
expect(compressed.copyWith(repeatCount: 2).isSmazCompressed, isTrue);
final plain = ChannelMessage.fromFrame(
ReviewFrames.channelMessage(
channelIndex: 0,
sender: 'Maya',
message: 'hello camp',
timestampSecs: 1700000001,
),
)!;
expect(plain.text, 'hello camp');
expect(plain.isSmazCompressed, isFalse);
});
test(
'ChannelMessageStore persists flag and defaults legacy rows to false',
() async {
final store = ChannelMessageStore()..setPublicKeyHex = _deviceScope;
final compressed = ChannelMessage.outgoing(
_compressibleText,
'Me',
0,
isSmazCompressed: true,
);
final plain = ChannelMessage.outgoing(
'short',
'Me',
0,
isSmazCompressed: false,
);
await store.saveChannelMessages(_channelId, [compressed, plain]);
final loaded = await store.loadChannelMessages(_channelId);
expect(loaded, hasLength(2));
expect(loaded[0].isSmazCompressed, isTrue);
expect(loaded[1].isSmazCompressed, isFalse);
await HistoryStore.instance.setString(
'${store.keyFor}_$_channelId',
jsonEncode([
{
'senderName': 'Maya',
'text': 'legacy channel msg',
'timestamp': 1700000002000,
'receivedAt': 1700000002000,
'isOutgoing': false,
'status': ChannelMessageStatus.sent.index,
'channelIndex': 0,
'plainText': true,
},
]),
);
final legacyLoaded = await store.loadChannelMessages(_channelId);
expect(legacyLoaded, hasLength(1));
expect(legacyLoaded.first.isSmazCompressed, isFalse);
},
);
});
group('MeshCoreConnector SMAZ tracking', () {
late MeshCoreConnector connector;
late MessageRetryService retryService;
late ReviewRadio radio;
setUpAll(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
HistoryStore.reset();
connector = MeshCoreConnector();
retryService = MessageRetryService();
connector.initialize(
retryService: retryService,
pathHistoryService: PathHistoryService(StorageService()),
);
connector.reviewRadioFactoryForTest = () {
radio = ReviewRadio(
scheduledMessageInterval: const Duration(hours: 1),
ackDelay: const Duration(hours: 1),
replyDelay: const Duration(hours: 1),
);
return radio;
};
await connector.connectReview();
await _waitFor(
() =>
connector.channelMapConfirmed &&
connector.contacts.isNotEmpty &&
connector.channels.isNotEmpty,
);
addTearDown(() async {
await connector.disconnect();
connector.dispose();
retryService.dispose();
});
});
test(
'records isSmazCompressed on outgoing DM and channel messages',
() async {
final contact = connector.contacts.first;
final channel = connector.channels.first;
// Mode off: not SMAZ compressed.
await connector.setContactCompressionMode(
contact.publicKeyHex,
ChatCompressionMode.off,
);
await connector.sendMessage(contact, _compressibleText);
// Mode SMAZ: compressible text sets flag, tiny uncompressible text does not.
await connector.setContactCompressionMode(
contact.publicKeyHex,
ChatCompressionMode.smaz,
);
await connector.sendMessage(contact, _compressibleText);
await connector.sendMessage(contact, 'ok');
// Mode Cyr2Lat: not SMAZ compressed.
await connector.setContactCompressionMode(
contact.publicKeyHex,
ChatCompressionMode.cyr2lat,
);
await connector.sendMessage(contact, 'Привет мир');
final dmMessages = connector.getMessages(contact);
final recentDms = dmMessages.sublist(dmMessages.length - 4);
expect(recentDms[0].isSmazCompressed, isFalse);
expect(recentDms[1].isSmazCompressed, isTrue);
expect(recentDms[2].isSmazCompressed, isFalse);
expect(recentDms[3].isSmazCompressed, isFalse);
// Channel outgoing messages.
await connector.setChannelCompressionMode(
channel.index,
ChatCompressionMode.off,
);
await connector.sendChannelMessage(channel, _compressibleText);
await connector.setChannelCompressionMode(
channel.index,
ChatCompressionMode.smaz,
);
await connector.sendChannelMessage(channel, _compressibleText);
await connector.sendChannelMessage(channel, 'ok');
await connector.setChannelCompressionMode(
channel.index,
ChatCompressionMode.cyr2lat,
);
await connector.sendChannelMessage(channel, 'Привет мир');
final chMessages = connector.getChannelMessages(channel);
final recentCh = chMessages.sublist(chMessages.length - 4);
expect(recentCh[0].isSmazCompressed, isFalse);
expect(recentCh[1].isSmazCompressed, isTrue);
expect(recentCh[2].isSmazCompressed, isFalse);
expect(recentCh[3].isSmazCompressed, isFalse);
// Ensure radio reference stays live without lint warnings.
expect(radio, isNotNull);
},
);
});
}
+22 -10
View File
@@ -404,7 +404,9 @@ void main() {
expect(settings.initialRouteWeight, equals(3.0));
expect(settings.routeWeightSuccessIncrement, equals(0.5));
expect(settings.routeWeightFailureDecrement, equals(0.2));
expect(settings.maxMessageRetries, equals(5));
expect(settings.directRetries, equals(4));
expect(settings.floodRetries, equals(1));
expect(settings.loginAttempts, equals(5));
expect(settings.evictDiscoveredContactsEnabled, isTrue);
});
@@ -415,13 +417,17 @@ void main() {
expect(json.containsKey('initial_route_weight'), isTrue);
expect(json.containsKey('route_weight_success_increment'), isTrue);
expect(json.containsKey('route_weight_failure_decrement'), isTrue);
expect(json.containsKey('max_message_retries'), isTrue);
expect(json.containsKey('max_direct_retries'), isTrue);
expect(json.containsKey('max_flood_retries'), isTrue);
expect(json.containsKey('login_attempts'), isTrue);
expect(json.containsKey('evict_discovered_contacts_enabled'), isTrue);
expect(json['max_route_weight'], equals(5.0));
expect(json['initial_route_weight'], equals(3.0));
expect(json['route_weight_success_increment'], equals(0.5));
expect(json['route_weight_failure_decrement'], equals(0.2));
expect(json['max_message_retries'], equals(5));
expect(json['max_direct_retries'], equals(4));
expect(json['max_flood_retries'], equals(1));
expect(json['login_attempts'], equals(5));
expect(json['evict_discovered_contacts_enabled'], isTrue);
});
@@ -431,7 +437,9 @@ void main() {
'initial_route_weight': 2.0,
'route_weight_success_increment': 1.0,
'route_weight_failure_decrement': 1.5,
'max_message_retries': 8,
'max_direct_retries': 8,
'max_flood_retries': 3,
'login_attempts': 7,
'evict_discovered_contacts_enabled': false,
};
final settings = AppSettings.fromJson(json);
@@ -439,7 +447,9 @@ void main() {
expect(settings.initialRouteWeight, equals(2.0));
expect(settings.routeWeightSuccessIncrement, equals(1.0));
expect(settings.routeWeightFailureDecrement, equals(1.5));
expect(settings.maxMessageRetries, equals(8));
expect(settings.directRetries, equals(8));
expect(settings.floodRetries, equals(3));
expect(settings.loginAttempts, equals(7));
expect(settings.evictDiscoveredContactsEnabled, isFalse);
});
@@ -503,7 +513,9 @@ void main() {
expect(settings.initialRouteWeight, equals(3.0));
expect(settings.routeWeightSuccessIncrement, equals(0.5));
expect(settings.routeWeightFailureDecrement, equals(0.2));
expect(settings.maxMessageRetries, equals(5));
expect(settings.directRetries, equals(4));
expect(settings.floodRetries, equals(1));
expect(settings.loginAttempts, equals(5));
},
);
@@ -513,7 +525,7 @@ void main() {
expect(updated.maxRouteWeight, equals(8.0));
// Other fields should be unchanged
expect(updated.initialRouteWeight, equals(settings.initialRouteWeight));
expect(updated.maxMessageRetries, equals(settings.maxMessageRetries));
expect(updated.directRetries, equals(settings.directRetries));
});
test('copyWith works for initialRouteWeight', () {
@@ -543,10 +555,10 @@ void main() {
);
});
test('copyWith works for maxMessageRetries', () {
test('copyWith works for directRetries', () {
final settings = AppSettings();
final updated = settings.copyWith(maxMessageRetries: 10);
expect(updated.maxMessageRetries, equals(10));
final updated = settings.copyWith(directRetries: 10);
expect(updated.directRetries, equals(10));
expect(updated.maxRouteWeight, equals(settings.maxRouteWeight));
});
});
+176
View File
@@ -0,0 +1,176 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:meshcore_open/models/app_settings.dart';
import 'package:meshcore_open/models/send_attempt_plan.dart';
import 'package:meshcore_open/services/app_settings_service.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
void main() {
group('SendAttemptPlan', () {
const rotating = SendAttemptPlan(
directRetries: 4,
floodRetries: 1,
rotateRoutes: true,
);
const fixed = SendAttemptPlan(
directRetries: 4,
floodRetries: 2,
rotateRoutes: false,
);
test('rotation spends direct attempts then flood attempts', () {
expect(rotating.attemptLimit(floodPath: false), 5);
expect(rotating.attemptLimit(floodPath: true), 5);
expect(rotating.floodFromAttempt, 4);
});
test('a fixed path uses only that path kind', () {
expect(fixed.attemptLimit(floodPath: false), 4);
expect(fixed.attemptLimit(floodPath: true), 2);
expect(fixed.floodFromAttempt, isNull);
});
test('both limits at zero still send once and do not switch to flood', () {
const plan = SendAttemptPlan(
directRetries: 0,
floodRetries: 0,
rotateRoutes: true,
);
expect(plan.attemptLimit(floodPath: false), 1);
expect(plan.floodFromAttempt, isNull);
});
test('direct zero with rotation floods from the first attempt', () {
const plan = SendAttemptPlan(
directRetries: 0,
floodRetries: 3,
rotateRoutes: true,
);
expect(plan.attemptLimit(floodPath: false), 3);
expect(plan.floodFromAttempt, 0);
});
test('flood zero with rotation never switches to flood', () {
const plan = SendAttemptPlan(
directRetries: 6,
floodRetries: 0,
rotateRoutes: true,
);
expect(plan.attemptLimit(floodPath: true), 6);
expect(plan.floodFromAttempt, isNull);
});
});
group('AppSettings retry migration', () {
test('a saved single retry limit becomes direct plus one flood', () {
final settings = AppSettings.fromJson({'max_message_retries': 5});
expect(settings.directRetries, 4);
expect(settings.floodRetries, 1);
expect(settings.toJson().containsKey('max_message_retries'), isFalse);
});
test('the old maximum of 10 keeps nine direct attempts and one flood', () {
final settings = AppSettings.fromJson({'max_message_retries': 10});
expect(settings.directRetries, 9);
expect(settings.floodRetries, 1);
});
test('new keys win over a leftover single limit and are clamped', () {
final settings = AppSettings.fromJson({
'max_message_retries': 5,
'max_direct_retries': 40,
'max_flood_retries': -2,
'login_attempts': 0,
});
expect(settings.directRetries, SendAttemptPlan.maxDirectRetries);
expect(settings.floodRetries, SendAttemptPlan.minFloodRetries);
expect(settings.loginAttempts, SendAttemptPlan.minLoginAttempts);
});
test('round trip keeps the split limits', () {
final saved = AppSettings(
directRetries: 12,
floodRetries: 7,
loginAttempts: 3,
clearPathOnMaxRetry: true,
autoRouteRotationEnabled: false,
channelMinHopsEnabled: true,
).toJson();
final restored = AppSettings.fromJson(saved);
expect(restored.directRetries, 12);
expect(restored.floodRetries, 7);
expect(restored.loginAttempts, 3);
expect(restored.clearPathOnMaxRetry, isTrue);
expect(restored.autoRouteRotationEnabled, isFalse);
expect(restored.channelMinHopsEnabled, isTrue);
});
});
test('reset routing settings restores the moved controls', () async {
SharedPreferences.setMockInitialValues({});
await PrefsManager.initialize();
final service = AppSettingsService();
await service.loadSettings();
await service.updateSettings(
service.settings.copyWith(
clearPathOnMaxRetry: true,
autoRouteRotationEnabled: false,
directRetries: 15,
floodRetries: 10,
loginAttempts: 9,
channelMinHopsEnabled: true,
channelMinHops: 6,
channelMinHopsRetries: 4,
channelMinHopsCountRepeaters: true,
maxRouteWeight: 9,
),
);
await service.resetRoutingSettingsToDefault();
final settings = service.settings;
expect(settings.clearPathOnMaxRetry, isFalse);
expect(settings.autoRouteRotationEnabled, isTrue);
expect(settings.directRetries, SendAttemptPlan.defaultDirectRetries);
expect(settings.floodRetries, SendAttemptPlan.defaultFloodRetries);
expect(settings.loginAttempts, 9);
expect(settings.channelMinHopsEnabled, isFalse);
expect(settings.channelMinHops, 2);
expect(settings.channelMinHopsRetries, 1);
expect(settings.channelMinHopsCountRepeaters, isFalse);
expect(settings.maxRouteWeight, AppSettings.defaultMaxRouteWeight);
final reloaded = AppSettingsService();
await reloaded.loadSettings();
expect(
reloaded.settings.directRetries,
SendAttemptPlan.defaultDirectRetries,
);
expect(reloaded.settings.floodRetries, SendAttemptPlan.defaultFloodRetries);
expect(reloaded.settings.loginAttempts, 9);
});
test('reset repeater and room settings restores that section', () async {
SharedPreferences.setMockInitialValues({});
await PrefsManager.initialize();
final service = AppSettingsService();
await service.loadSettings();
await service.updateSettings(
service.settings.copyWith(
clockSyncAfterLogin: true,
loginPasswordAutofocus: true,
autoFetchRepeaterSettings: true,
loginAttempts: 8,
directRetries: 12,
),
);
await service.resetRepeaterRoomSettingsToDefault();
final settings = service.settings;
expect(settings.clockSyncAfterLogin, isFalse);
expect(settings.loginPasswordAutofocus, isFalse);
expect(settings.autoFetchRepeaterSettings, isFalse);
expect(settings.loginAttempts, SendAttemptPlan.defaultLoginAttempts);
expect(settings.directRetries, 12);
});
}
+546
View File
@@ -0,0 +1,546 @@
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:meshcore_open/connector/meshcore_connector.dart';
import 'package:meshcore_open/connector/meshcore_protocol.dart';
import 'package:meshcore_open/l10n/app_localizations.dart';
import 'package:meshcore_open/l10n/app_localizations_en.dart';
import 'package:meshcore_open/review_mode/review_radio.dart';
import 'package:meshcore_open/screens/add_contact_screen.dart';
import 'package:meshcore_open/screens/contacts_screen.dart';
import 'package:meshcore_open/screens/discovery_screen.dart';
import 'package:meshcore_open/services/app_debug_log_service.dart';
import 'package:meshcore_open/services/app_settings_service.dart';
import 'package:meshcore_open/services/ble_debug_log_service.dart';
import 'package:meshcore_open/services/chat_text_scale_service.dart';
import 'package:meshcore_open/services/image_codec_service.dart';
import 'package:meshcore_open/services/map_tile_cache_service.dart';
import 'package:meshcore_open/services/message_retry_service.dart';
import 'package:meshcore_open/services/network_map/network_map_upload_service.dart';
import 'package:meshcore_open/services/path_history_service.dart';
import 'package:meshcore_open/services/received_image_store.dart';
import 'package:meshcore_open/services/storage_service.dart';
import 'package:meshcore_open/services/timeout_prediction_service.dart';
import 'package:meshcore_open/services/translation_service.dart';
import 'package:meshcore_open/services/ui_view_state_service.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:meshcore_open/theme/mesh_theme.dart';
final _l10n = AppLocalizationsEn();
MeshCoreConnector? _sharedConnector;
Future<MeshCoreConnector> _connectedConnector(WidgetTester tester) async {
if (_sharedConnector != null) {
return _sharedConnector!;
}
final storage = StorageService();
final connector = MeshCoreConnector();
final retry = MessageRetryService();
final settings = AppSettingsService();
final translation = TranslationService(settings);
await tester.runAsync(() async {
await settings.loadSettings();
connector.initialize(
retryService: retry,
pathHistoryService: PathHistoryService(storage),
appSettingsService: settings,
translationService: translation,
);
connector.reviewRadioFactoryForTest = () => ReviewRadio(
scheduledMessageInterval: const Duration(hours: 1),
ackDelay: const Duration(milliseconds: 50),
replyDelay: const Duration(hours: 1),
);
await connector.connectReview();
final end = DateTime.now().add(const Duration(seconds: 8));
while (!connector.hasLoadedContacts && DateTime.now().isBefore(end)) {
await Future<void>.delayed(const Duration(milliseconds: 25));
}
});
_sharedConnector = connector;
return connector;
}
Widget _wrapApp({
required MeshCoreConnector connector,
required Widget home,
ThemeData? theme,
Locale locale = const Locale('en'),
double textScale = 1.0,
}) {
final storage = StorageService();
final settings = AppSettingsService();
return MultiProvider(
providers: [
ChangeNotifierProvider.value(value: connector),
ChangeNotifierProvider(create: (_) => MessageRetryService()),
ChangeNotifierProvider(create: (_) => PathHistoryService(storage)),
ChangeNotifierProvider.value(value: settings),
ChangeNotifierProvider(create: (_) => BleDebugLogService()),
ChangeNotifierProvider(create: (_) => AppDebugLogService()),
ChangeNotifierProvider(create: (_) => ChatTextScaleService()),
ChangeNotifierProvider(create: (_) => TranslationService(settings)),
ChangeNotifierProvider(create: (_) => UiViewStateService()),
Provider.value(value: storage),
ChangeNotifierProvider(
create: (_) => MapTileCacheService(appSettingsService: settings),
),
ChangeNotifierProvider(create: (_) => TimeoutPredictionService(storage)),
ChangeNotifierProvider(create: (_) => ImageCodecService(settings)),
ChangeNotifierProvider(create: (_) => ReceivedImageStore()),
ChangeNotifierProvider(
create: (_) =>
NetworkMapUploadService(connector: connector, settings: settings),
),
],
child: MaterialApp(
theme: theme ?? MeshTheme.dark(),
locale: locale,
localizationsDelegates: const [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: AppLocalizations.supportedLocales,
builder: (context, child) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(textScaler: TextScaler.linear(textScale)),
child: child!,
),
home: home,
),
);
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final tempDir = Directory.systemTemp.createTempSync('add_contact_test');
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(
const MethodChannel('plugins.flutter.io/path_provider'),
(call) async => tempDir.path,
);
setUp(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
});
tearDownAll(() {
_sharedConnector?.dispose();
_sharedConnector = null;
if (tempDir.existsSync()) {
tempDir.deleteSync(recursive: true);
}
});
testWidgets('validates empty fields and invalid public key', (tester) async {
final connector = await _connectedConnector(tester);
await tester.pumpWidget(
_wrapApp(connector: connector, home: const AddContactScreen()),
);
await tester.pumpAndSettle();
expect(find.text(_l10n.addContact_title), findsOneWidget);
expect(find.text(_l10n.addContact_infoBanner), findsOneWidget);
expect(find.text(_l10n.contacts_addContactFromClipboard), findsOneWidget);
expect(find.text(_l10n.addContact_fromDiscovered), findsOneWidget);
expect(find.text(_l10n.contacts_scanQrCode), findsOneWidget);
await tester.tap(find.byIcon(Icons.check));
await tester.pumpAndSettle();
expect(find.text(_l10n.addContact_nameRequired), findsOneWidget);
expect(find.text(_l10n.addContact_publicKeyRequired), findsOneWidget);
await tester.enterText(find.byType(TextFormField).first, 'Repeater One');
await tester.enterText(find.byType(TextFormField).last, 'abcd');
await tester.tap(find.byIcon(Icons.check));
await tester.pumpAndSettle();
expect(find.text(_l10n.addContact_publicKeyInvalid), findsOneWidget);
await tester.pumpWidget(const SizedBox());
});
testWidgets('selects contact type and submits manual contact', (
tester,
) async {
final connector = await _connectedConnector(tester);
final keyHex = List.generate(
32,
(i) => (i + 1).toRadixString(16).padLeft(2, '0'),
).join();
await tester.pumpWidget(
_wrapApp(
connector: connector,
home: Builder(
builder: (context) => Scaffold(
body: Center(
child: FilledButton(
onPressed: () => Navigator.push(
context,
MaterialPageRoute(builder: (_) => const AddContactScreen()),
),
child: const Text('Open'),
),
),
),
),
),
);
await tester.pumpAndSettle();
await tester.tap(find.text('Open'));
await tester.pumpAndSettle();
// Change Contact Type from Chat to Repeater.
expect(find.text(_l10n.contact_typeChat), findsOneWidget);
await tester.tap(find.text(_l10n.contact_typeChat));
await tester.pumpAndSettle();
expect(find.text(_l10n.contact_typeRepeater), findsOneWidget);
expect(find.text(_l10n.contact_typeRoom), findsOneWidget);
expect(find.text(_l10n.contact_typeSensor), findsOneWidget);
await tester.tap(find.text(_l10n.contact_typeRepeater));
await tester.pumpAndSettle();
expect(find.text(_l10n.contact_typeRepeater), findsOneWidget);
await tester.enterText(find.byType(TextFormField).first, ' North Ridge ');
await tester.enterText(
find.byType(TextFormField).last,
' 0x${keyHex.toUpperCase()} ',
);
await tester.runAsync(() async {
await tester.tap(find.byIcon(Icons.check));
final end = DateTime.now().add(const Duration(seconds: 5));
while (!connector.contacts.any((c) => c.publicKeyHex == keyHex) &&
DateTime.now().isBefore(end)) {
await Future<void>.delayed(const Duration(milliseconds: 25));
}
});
await tester.pumpAndSettle();
final added = connector.contacts.firstWhere(
(c) => c.publicKeyHex == keyHex,
);
expect(added.name, 'North Ridge');
expect(added.type, advTypeRepeater);
expect(find.byType(AddContactScreen), findsNothing);
expect(find.text(_l10n.discoveredContacts_contactAdded), findsOneWidget);
await tester.pumpWidget(const SizedBox());
});
testWidgets('bare hex key in clipboard fills Public Key and focuses Name', (
tester,
) async {
final connector = await _connectedConnector(tester);
final keyHex = 'ab' * 32;
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(SystemChannels.platform, (call) async {
if (call.method == 'Clipboard.getData') {
return <String, dynamic>{'text': ' 0x${keyHex.toUpperCase()} \n'};
}
return null;
});
addTearDown(
() => TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(SystemChannels.platform, null),
);
await tester.pumpWidget(
_wrapApp(connector: connector, home: const AddContactScreen()),
);
await tester.pumpAndSettle();
// Trigger empty validation error first, then ensure pasting a bare key clears it.
await tester.tap(find.byIcon(Icons.check));
await tester.pumpAndSettle();
expect(find.text(_l10n.addContact_publicKeyRequired), findsOneWidget);
await tester.tap(find.text(_l10n.contacts_addContactFromClipboard));
await tester.pumpAndSettle();
final nameField = tester.widget<TextField>(find.byType(TextField).first);
final keyField = tester.widget<TextField>(find.byType(TextField).last);
expect(keyField.controller!.text, keyHex);
expect(nameField.focusNode!.hasFocus, isTrue);
expect(find.text(_l10n.addContact_publicKeyRequired), findsNothing);
expect(find.text(_l10n.addContact_clipboardKeyLoaded), findsOneWidget);
await tester.pumpWidget(const SizedBox());
});
testWidgets('empty and invalid clipboard show feedback snackbars', (
tester,
) async {
final connector = await _connectedConnector(tester);
String? clipboardText;
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(SystemChannels.platform, (call) async {
if (call.method == 'Clipboard.getData') {
return clipboardText == null
? null
: <String, dynamic>{'text': clipboardText};
}
return null;
});
addTearDown(
() => TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(SystemChannels.platform, null),
);
await tester.pumpWidget(
_wrapApp(connector: connector, home: const AddContactScreen()),
);
await tester.pumpAndSettle();
await tester.tap(find.text(_l10n.contacts_addContactFromClipboard));
await tester.pumpAndSettle();
expect(find.text(_l10n.contacts_clipboardEmpty), findsOneWidget);
clipboardText = 'not-a-valid-key-or-uri';
await tester.tap(find.text(_l10n.contacts_addContactFromClipboard));
await tester.pumpAndSettle();
expect(find.text(_l10n.contacts_invalidAdvertFormat), findsOneWidget);
await tester.pumpWidget(const SizedBox());
});
testWidgets('rejects adding own public key manually', (tester) async {
final connector = await _connectedConnector(tester);
await tester.pumpWidget(
_wrapApp(connector: connector, home: const AddContactScreen()),
);
await tester.pumpAndSettle();
await tester.enterText(find.byType(TextFormField).first, 'Self');
await tester.enterText(
find.byType(TextFormField).last,
connector.selfPublicKeyHex,
);
await tester.tap(find.byIcon(Icons.check));
await tester.pumpAndSettle();
expect(find.text(_l10n.contactShare_isYou), findsOneWidget);
expect(find.byType(AddContactScreen), findsOneWidget);
await tester.pumpWidget(const SizedBox());
});
testWidgets('meshcore:// contact URI in clipboard imports contact', (
tester,
) async {
final connector = await _connectedConnector(tester);
final keyHex = 'cd' * 32;
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(SystemChannels.platform, (call) async {
if (call.method == 'Clipboard.getData') {
return <String, dynamic>{
'text': 'meshcore://contact/add?name=UriPeer&public_key=$keyHex',
};
}
return null;
});
addTearDown(
() => TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(SystemChannels.platform, null),
);
await tester.pumpWidget(
_wrapApp(
connector: connector,
home: Builder(
builder: (context) => Scaffold(
body: Center(
child: FilledButton(
onPressed: () => Navigator.push(
context,
MaterialPageRoute(builder: (_) => const AddContactScreen()),
),
child: const Text('Open'),
),
),
),
),
),
);
await tester.pumpAndSettle();
await tester.tap(find.text('Open'));
await tester.pumpAndSettle();
await tester.runAsync(() async {
await tester.tap(find.text(_l10n.contacts_addContactFromClipboard));
final end = DateTime.now().add(const Duration(seconds: 5));
while (!connector.contacts.any((c) => c.publicKeyHex == keyHex) &&
DateTime.now().isBefore(end)) {
await Future<void>.delayed(const Duration(milliseconds: 25));
}
});
await tester.pumpAndSettle();
expect(connector.contacts.any((c) => c.name == 'UriPeer'), isTrue);
expect(find.byType(AddContactScreen), findsNothing);
await tester.pumpWidget(const SizedBox());
});
testWidgets('Contacts FAB and menu item both open AddContactScreen', (
tester,
) async {
final connector = await _connectedConnector(tester);
await tester.pumpWidget(
_wrapApp(connector: connector, home: const ContactsScreen()),
);
await tester.pumpAndSettle();
// Entry point 1: Contacts FAB.
await tester.tap(find.byType(FloatingActionButton));
await tester.pumpAndSettle();
expect(find.byType(AddContactScreen), findsOneWidget);
await tester.pageBack();
await tester.pumpAndSettle();
expect(find.byType(AddContactScreen), findsNothing);
// Entry point 2: Overflow menu item.
await tester.tap(find.byIcon(Icons.more_vert));
await tester.pumpAndSettle();
await tester.tap(find.text(_l10n.addContact_title));
await tester.pumpAndSettle();
expect(find.byType(AddContactScreen), findsOneWidget);
await tester.pumpWidget(const SizedBox());
});
testWidgets('navigates to Discovered Contacts and adds a discovered node', (
tester,
) async {
final connector = await _connectedConnector(tester);
final discoveredKey = Uint8List.fromList(List<int>.filled(32, 0x5E));
final discoveredKeyHex = pubKeyToHex(discoveredKey);
const name = 'Discovered Node';
final frameData = ByteData(1 + 32 + 3 + 64 + 32 + 4 + 12);
final frame = frameData.buffer.asUint8List();
frame[0] = pushCodeNewAdvert;
frame.setRange(1, 33, discoveredKey);
frame[33] = advTypeChat;
frame[35] = 0xFF;
frame.setRange(100, 100 + name.length, name.codeUnits);
frameData.setUint32(132, 1700000000, Endian.little);
connector.handleFrameForTest(frame);
await tester.pumpWidget(
_wrapApp(connector: connector, home: const AddContactScreen()),
);
await tester.pumpAndSettle();
await tester.tap(find.text(_l10n.addContact_fromDiscovered));
await tester.pumpAndSettle();
expect(find.byType(DiscoveryScreen), findsOneWidget);
expect(find.text(name), findsOneWidget);
await tester.runAsync(() async {
await tester.tap(find.byIcon(Icons.person_add_alt_1));
final end = DateTime.now().add(const Duration(seconds: 5));
while (!connector.contacts.any(
(c) => c.publicKeyHex == discoveredKeyHex,
) &&
DateTime.now().isBefore(end)) {
await Future<void>.delayed(const Duration(milliseconds: 25));
}
});
await tester.pumpAndSettle();
expect(
connector.contacts.any((c) => c.publicKeyHex == discoveredKeyHex),
isTrue,
);
expect(find.text(_l10n.discoveredContacts_contactAdded), findsOneWidget);
await tester.pumpWidget(const SizedBox());
});
testWidgets('disconnected manual submit shows offline error snackbar', (
tester,
) async {
final connector = MeshCoreConnector();
addTearDown(connector.dispose);
final keyHex = 'ef' * 32;
await tester.pumpWidget(
_wrapApp(connector: connector, home: const AddContactScreen()),
);
await tester.pumpAndSettle();
await tester.enterText(find.byType(TextFormField).first, 'Offline Node');
await tester.enterText(find.byType(TextFormField).last, keyHex);
await tester.tap(find.byIcon(Icons.check));
await tester.pumpAndSettle();
expect(find.text(_l10n.settings_notConnectedError), findsOneWidget);
expect(find.byType(AddContactScreen), findsOneWidget);
await tester.pumpWidget(const SizedBox());
});
for (final (label, theme, locale) in [
('light en', MeshTheme.light(), const Locale('en')),
('dark en', MeshTheme.dark(), const Locale('en')),
('dark de', MeshTheme.dark(), const Locale('de')),
]) {
for (final scale in [1.3, 2.0]) {
testWidgets('fits 320dp width at ${scale}x in $label', (tester) async {
tester.view.physicalSize = const Size(320, 568);
tester.view.devicePixelRatio = 1.0;
addTearDown(tester.view.reset);
final connector = await _connectedConnector(tester);
final overflows = <String>[];
final previous = FlutterError.onError;
FlutterError.onError = (details) {
final text = details.exceptionAsString();
if (text.contains('overflowed')) {
overflows.add(text.split('\n').first);
} else {
previous?.call(details);
}
};
addTearDown(() => FlutterError.onError = previous);
await tester.pumpWidget(
_wrapApp(
connector: connector,
home: const AddContactScreen(),
theme: theme,
locale: locale,
textScale: scale,
),
);
await tester.pumpAndSettle();
FlutterError.onError = previous;
expect(overflows, isEmpty, reason: overflows.join('\n'));
await tester.pumpWidget(const SizedBox());
});
}
}
}
@@ -0,0 +1,331 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:provider/provider.dart';
import 'package:provider/single_child_widget.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:meshcore_open/connector/meshcore_connector.dart';
import 'package:meshcore_open/helpers/chat_scroll_controller.dart';
import 'package:meshcore_open/l10n/app_localizations.dart';
import 'package:meshcore_open/review_mode/review_frames.dart';
import 'package:meshcore_open/review_mode/review_radio.dart';
import 'package:meshcore_open/screens/channel_chat_screen.dart';
import 'package:meshcore_open/services/app_debug_log_service.dart';
import 'package:meshcore_open/services/app_settings_service.dart';
import 'package:meshcore_open/services/ble_debug_log_service.dart';
import 'package:meshcore_open/services/chat_text_scale_service.dart';
import 'package:meshcore_open/services/image_codec_service.dart';
import 'package:meshcore_open/services/map_tile_cache_service.dart';
import 'package:meshcore_open/services/message_retry_service.dart';
import 'package:meshcore_open/services/path_history_service.dart';
import 'package:meshcore_open/services/received_image_store.dart';
import 'package:meshcore_open/services/storage_service.dart';
import 'package:meshcore_open/services/timeout_prediction_service.dart';
import 'package:meshcore_open/services/translation_service.dart';
import 'package:meshcore_open/services/ui_view_state_service.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:meshcore_open/theme/mesh_theme.dart';
/// Selecting messages must not move the transcript: picking, selecting all
/// and clearing are not new messages, and the composer getting its focus back
/// when the action sheet closes is not the user opening the keyboard.
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final tempDir = Directory.systemTemp.createTempSync('selection_scroll_test');
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(
const MethodChannel('plugins.flutter.io/path_provider'),
(call) async => tempDir.path,
);
setUpAll(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
});
testWidgets('selecting from far up the history keeps the scroll offset', (
tester,
) async {
_useSmallView(tester);
await _pumpChannelChat(tester);
// The composer has focus (keyboard open) while the user reads back.
await tester.tap(find.byType(TextField).last);
await _settle(tester);
await _scrollTo(tester, 600);
await _startSelection(tester);
expect(find.text('1 selected'), findsOneWidget);
expect(_position(tester).pixels, 600);
// Select a few more.
for (var i = 0; i < 2; i++) {
await _tapVisibleUnselected(tester);
expect(_position(tester).pixels, 600);
}
expect(find.text('3 selected'), findsOneWidget);
// Select all from the selection app bar's menu.
await tester.tap(find.byIcon(Icons.more_vert));
await _settle(tester);
await tester.tap(find.text('Select all'));
await _settle(tester);
expect(find.byIcon(Icons.radio_button_unchecked), findsNothing);
expect(_position(tester).pixels, 600);
// End selection.
await tester.tap(find.byTooltip('Clear selection'));
await _settle(tester);
expect(find.byTooltip('Clear selection'), findsNothing);
expect(_position(tester).pixels, 600);
// Losing focus with nothing on top, then tapping the composer, still jumps
// to the newest message.
FocusManager.instance.primaryFocus?.unfocus();
await _settle(tester);
await tester.tap(find.byType(TextField).last);
await _settle(tester);
expect(_position(tester).pixels, 0);
await _tearDown(tester);
});
testWidgets('selection near the bottom does not snap to the newest message', (
tester,
) async {
_useSmallView(tester);
await _pumpChannelChat(tester);
await _scrollTo(tester, 600);
await _startSelection(tester);
// Inside the "at bottom" threshold, where a new message would snap.
await _scrollTo(tester, 60);
await _tapVisibleUnselected(tester);
expect(find.text('2 selected'), findsOneWidget);
expect(_position(tester).pixels, 60);
await tester.tap(find.byTooltip('Clear selection'));
await _settle(tester);
expect(_position(tester).pixels, 60);
await _tearDown(tester);
});
testWidgets('incoming messages during selection behave as before', (
tester,
) async {
_useSmallView(tester);
final connector = await _pumpChannelChat(tester);
final channelIndex = connector.channels[0].index;
await _scrollTo(tester, 600);
await _startSelection(tester);
// Reading back: a new message must not pull the view down.
_receive(connector, channelIndex, 'Arrives while reading back');
await _settle(tester);
expect(find.text('1 selected'), findsOneWidget);
expect(_position(tester).pixels, greaterThanOrEqualTo(600));
// Near the bottom: a new message still scrolls into view.
await _scrollTo(tester, 60);
_receive(connector, channelIndex, 'Arrives while at the bottom');
await _settle(tester);
expect(find.text('1 selected'), findsOneWidget);
expect(_position(tester).pixels, 0);
await _tearDown(tester);
});
}
void _useSmallView(WidgetTester tester) {
tester.view.physicalSize = const Size(400, 700);
tester.view.devicePixelRatio = 1.0;
addTearDown(tester.view.reset);
}
ScrollPosition _position(WidgetTester tester) => tester
.widget<ListView>(
find.byWidgetPredicate(
(w) => w is ListView && w.controller is ChatScrollController,
),
)
.controller!
.position;
/// Jumps to [pixels] from the bottom. Jumps twice: the first lays out
/// messages whose heights were only estimated, which can correct the offset.
Future<void> _scrollTo(WidgetTester tester, double pixels) async {
for (var i = 0; i < 2; i++) {
_position(tester).jumpTo(pixels);
await _settle(tester);
}
expect(_position(tester).pixels, pixels);
}
/// Long-presses a message in the middle of the screen and picks "Select
/// messages" from its action sheet. The long-press callback is invoked
/// directly: in tests a real long press on the bubble text starts text
/// selection instead.
Future<void> _startSelection(WidgetTester tester) async {
final detector = find
.byWidgetPredicate((w) => w is GestureDetector && w.onLongPress != null)
.evaluate()
.firstWhere((e) {
final box = e.renderObject! as RenderBox;
final y = box.localToGlobal(box.size.center(Offset.zero)).dy;
return y > 150 && y < 450;
});
(detector.widget as GestureDetector).onLongPress!();
await _settle(tester);
await tester.ensureVisible(find.text('Select messages'));
await tester.pump();
await tester.tap(find.text('Select messages'));
await _settle(tester);
}
/// Taps the selection circle of an unselected message on screen.
Future<void> _tapVisibleUnselected(WidgetTester tester) async {
final list = tester.getRect(
find.byWidgetPredicate(
(w) => w is ListView && w.controller is ChatScrollController,
),
);
final circle = find
.byIcon(Icons.radio_button_unchecked)
.evaluate()
.firstWhere((e) {
final box = e.renderObject! as RenderBox;
return list.contains(box.localToGlobal(box.size.center(Offset.zero)));
});
await tester.tap(find.byWidget(circle.widget));
await _settle(tester);
}
var _received = 0;
void _receive(MeshCoreConnector connector, int channelIndex, String text) {
connector.handleFrameForTest(
ReviewFrames.channelMessage(
channelIndex: channelIndex,
sender: 'Alice',
message: text,
timestampSecs:
DateTime.now().millisecondsSinceEpoch ~/ 1000 + 60 * ++_received,
),
);
}
Future<void> _settle(WidgetTester tester) async {
for (var i = 0; i < 10; i++) {
await tester.pump(const Duration(milliseconds: 100));
}
}
Future<void> _tearDown(WidgetTester tester) async {
await tester.pumpWidget(const SizedBox());
await tester.pump(const Duration(minutes: 1));
}
/// One review-radio connection shared by the tests: reconnecting it in the
/// same run does not resend the channel list.
(MeshCoreConnector, List<SingleChildWidget>)? _shared;
/// Connects the review radio (once), seeds a long history and shows the
/// first channel's chat.
Future<MeshCoreConnector> _pumpChannelChat(WidgetTester tester) async {
final firstRun = _shared == null;
final (connector, providers) = _shared ??= await _connect(tester);
if (firstRun) {
final base = DateTime.now().millisecondsSinceEpoch ~/ 1000 - 10000;
for (var i = 0; i < 40; i++) {
connector.handleFrameForTest(
ReviewFrames.channelMessage(
channelIndex: connector.channels[0].index,
sender: 'Alice',
message: 'History message $i with enough words to wrap a line',
timestampSecs: base + i * 60,
),
);
}
}
await tester.pumpWidget(
MultiProvider(
providers: providers,
child: MaterialApp(
theme: MeshTheme.light(),
locale: const Locale('en'),
localizationsDelegates: const [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: AppLocalizations.supportedLocales,
home: ChannelChatScreen(channel: connector.channels[0]),
),
),
);
await _settle(tester);
return connector;
}
Future<(MeshCoreConnector, List<SingleChildWidget>)> _connect(
WidgetTester tester,
) async {
final storage = StorageService();
final connector = MeshCoreConnector();
final retry = MessageRetryService();
final settings = AppSettingsService();
final translation = TranslationService(settings);
await tester.runAsync(() async {
await settings.loadSettings();
connector.initialize(
retryService: retry,
pathHistoryService: PathHistoryService(storage),
appSettingsService: settings,
translationService: translation,
);
connector.reviewRadioFactoryForTest = () => ReviewRadio(
scheduledMessageInterval: const Duration(hours: 1),
ackDelay: const Duration(hours: 1),
replyDelay: const Duration(hours: 1),
);
await connector.connectReview();
final end = DateTime.now().add(const Duration(seconds: 8));
while ((connector.contacts.isEmpty || connector.channels.length < 2) &&
DateTime.now().isBefore(end)) {
await Future<void>.delayed(const Duration(milliseconds: 25));
}
});
expect(connector.channels.length, greaterThanOrEqualTo(2));
return (
connector,
<SingleChildWidget>[
ChangeNotifierProvider.value(value: connector),
ChangeNotifierProvider.value(value: retry),
ChangeNotifierProvider.value(value: PathHistoryService(storage)),
ChangeNotifierProvider.value(value: settings),
ChangeNotifierProvider.value(value: BleDebugLogService()),
ChangeNotifierProvider.value(value: AppDebugLogService()),
ChangeNotifierProvider.value(value: ChatTextScaleService()),
ChangeNotifierProvider.value(value: translation),
ChangeNotifierProvider.value(value: UiViewStateService()),
Provider.value(value: storage),
ChangeNotifierProvider.value(
value: MapTileCacheService(appSettingsService: settings),
),
ChangeNotifierProvider.value(value: TimeoutPredictionService(storage)),
ChangeNotifierProvider.value(value: ImageCodecService(settings)),
ChangeNotifierProvider.value(value: ReceivedImageStore()),
],
);
}
@@ -0,0 +1,84 @@
import 'dart:typed_data';
import 'package:flutter/material.dart';
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/l10n/app_localizations.dart';
import 'package:meshcore_open/models/channel_message.dart';
import 'package:meshcore_open/models/contact.dart';
import 'package:meshcore_open/screens/channel_message_path_screen.dart';
import 'package:meshcore_open/widgets/mesh_ui.dart';
import 'package:provider/provider.dart';
class _FakeConnector extends MeshCoreConnector {
_FakeConnector(this.hopContacts);
final List<Contact> hopContacts;
@override
List<Contact> get allContacts => hopContacts;
@override
double? get selfLatitude => null;
@override
double? get selfLongitude => null;
}
void main() {
testWidgets('hop avatars use the repeater name or the hex prefix', (
tester,
) async {
final connector = _FakeConnector([
Contact(
publicKey: Uint8List(32)..first = 0xAA,
name: '(Base) Hilltop',
type: advTypeRepeater,
pathLength: 0,
path: Uint8List(0),
lastSeen: DateTime.utc(2026),
),
]);
final message = ChannelMessage(
senderName: 'Alice',
text: 'hello',
timestamp: DateTime.utc(2026),
isOutgoing: false,
pathBytes: Uint8List.fromList([0xAA, 0xBC]),
channelIndex: 0,
);
await tester.pumpWidget(
ChangeNotifierProvider<MeshCoreConnector>.value(
value: connector,
child: MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: ChannelMessagePathScreen(
message: message,
channelMessage: true,
),
),
),
);
await tester.pumpAndSettle();
final avatarNames = tester
.widgetList<AvatarCircle>(find.byType(AvatarCircle))
.map((avatar) => avatar.name)
.toList();
expect(avatarNames, containsAll(['(Base) Hilltop', 'BC']));
expect(
find.descendant(of: find.byType(AvatarCircle), matching: find.text('BH')),
findsOneWidget,
);
expect(
find.descendant(
of: find.byType(AvatarCircle),
matching: find.textContaining('('),
),
findsNothing,
);
});
}
@@ -0,0 +1,292 @@
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
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/l10n/app_localizations.dart';
import 'package:meshcore_open/models/channel_message.dart';
import 'package:meshcore_open/models/contact.dart';
import 'package:meshcore_open/screens/channel_message_path_screen.dart';
import 'package:meshcore_open/services/app_settings_service.dart';
import 'package:meshcore_open/services/map_tile_cache_service.dart';
import 'package:provider/provider.dart';
class _FakeConnector extends MeshCoreConnector {
_FakeConnector(this._contacts, {this.lat = 33.4484, this.lon = -112.0740});
final List<Contact> _contacts;
final double? lat;
final double? lon;
@override
List<Contact> get allContacts => _contacts;
@override
double? get selfLatitude => lat;
@override
double? get selfLongitude => lon;
}
Contact _repeater({
required int prefix,
required String name,
required double latitude,
required double longitude,
}) {
return Contact(
publicKey: Uint8List(32)..first = prefix,
name: name,
type: advTypeRepeater,
pathLength: 0,
path: Uint8List(0),
latitude: latitude,
longitude: longitude,
lastSeen: DateTime.utc(2026),
);
}
Widget _wrapWithProviders(MeshCoreConnector connector, Widget child) {
final settings = AppSettingsService();
return MultiProvider(
providers: [
ChangeNotifierProvider<MeshCoreConnector>.value(value: connector),
ChangeNotifierProvider<AppSettingsService>.value(value: settings),
ChangeNotifierProvider<MapTileCacheService>(
create: (_) => MapTileCacheService(appSettingsService: settings),
),
],
child: MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: child,
),
);
}
void main() {
testWidgets(
'ChannelMessagePathMapScreen ignores impossible distant hop in polylines, markers, bounds, distance, and hop list',
(tester) async {
final localHop3 = _repeater(
prefix: 0x53,
name: "Rod's Repeater",
latitude: 33.46300,
longitude: -111.65000,
);
final localHop4 = _repeater(
prefix: 0x48,
name: 'Twain - Clearview',
latitude: 33.60097,
longitude: -112.02457,
);
final bogusEastCoastHop5 = _repeater(
prefix: 0x9C,
name: 'Beacon Hill 1W Repeater',
latitude: 42.3601,
longitude: -71.0589,
);
final connector = _FakeConnector([
localHop3,
localHop4,
bogusEastCoastHop5,
]);
final message = ChannelMessage(
senderName: 'Alice',
text: 'test',
timestamp: DateTime.utc(2026),
isOutgoing: false,
pathBytes: Uint8List.fromList([
0x6C,
0x84,
0x53,
0x48,
0x9C,
0x21,
0xC9,
0xEA,
]),
channelIndex: 0,
);
await tester.pumpWidget(
_wrapWithProviders(
connector,
ChannelMessagePathMapScreen(message: message, channelMessage: true),
),
);
await tester.pumpAndSettle();
// East Coast repeater must not appear as a resolved repeater or in markers.
expect(find.textContaining('Beacon Hill 1W Repeater'), findsNothing);
expect(find.textContaining('42.36010'), findsNothing);
// Expand the hop list panel so all 8 hops in the ListView are built.
await tester.tap(find.byIcon(Icons.open_in_full));
await tester.pumpAndSettle();
expect(find.text('(9C) Unknown Repeater'), findsOneWidget);
// Local repeaters should still be listed and plotted.
expect(find.text("(53) Rod's Repeater"), findsOneWidget);
expect(find.text('(48) Twain - Clearview'), findsOneWidget);
// Collapse back so map assertions (PolylineLayer, MarkerLayer, header distance) are visible.
await tester.tap(find.byIcon(Icons.close_fullscreen));
await tester.pumpAndSettle();
// Polyline points and markers must stay in Arizona (no East Coast jump).
final polylineLayer = tester.widget<PolylineLayer>(
find.byType(PolylineLayer),
);
final allPolylinePoints = polylineLayer.polylines
.expand((p) => p.points)
.toList();
expect(allPolylinePoints, isNotEmpty);
for (final point in allPolylinePoints) {
expect(point.latitude, inInclusiveRange(33.0, 34.0));
expect(point.longitude, inInclusiveRange(-113.0, -111.0));
}
// Segment across unresolved/ignored hops (4 -> You) must be dashed while
// adjacent local hops (3 -> 4) remain solid.
expect(
polylineLayer.polylines.any((p) => p.pattern != StrokePattern.solid()),
isTrue,
);
final markerLayer = tester.widget<MarkerLayer>(
find.byType(MarkerLayer).first,
);
for (final marker in markerLayer.markers) {
expect(marker.point.latitude, inInclusiveRange(33.0, 34.0));
expect(marker.point.longitude, inInclusiveRange(-113.0, -111.0));
}
// Camera bounds must stay local, not continental.
final flutterMap = tester.widget<FlutterMap>(find.byType(FlutterMap));
final fit = flutterMap.options.initialCameraFit as FitBounds;
expect(fit.bounds.north, lessThan(34.0));
expect(fit.bounds.east, lessThan(-111.0));
// Reported path distance must be local (~50-65 km), not thousands of km.
final distanceFinder = find.textContaining(' km)');
expect(distanceFinder, findsOneWidget);
final distanceText = tester.widget<Text>(distanceFinder).data!;
final kmMatch = RegExp(r'\((\d+\.\d+) km\)').firstMatch(distanceText);
expect(kmMatch, isNotNull);
final kmValue = double.parse(kmMatch!.group(1)!);
expect(kmValue, lessThan(200.0));
expect(kmValue, greaterThan(10.0));
},
);
testWidgets(
'ChannelMessagePathMapScreen without self GPS rejects leading outlier and keeps local cluster',
(tester) async {
final bogusEastCoast = _repeater(
prefix: 0x9C,
name: 'Beacon Hill 1W Repeater',
latitude: 42.3601,
longitude: -71.0589,
);
final localHop1 = _repeater(
prefix: 0x48,
name: 'Twain - Clearview',
latitude: 33.60097,
longitude: -112.02457,
);
final localHop2 = _repeater(
prefix: 0x53,
name: "Rod's Repeater",
latitude: 33.46300,
longitude: -111.65000,
);
final connector = _FakeConnector(
[bogusEastCoast, localHop1, localHop2],
lat: null,
lon: null,
);
final message = ChannelMessage(
senderName: 'Alice',
text: 'test',
timestamp: DateTime.utc(2026),
isOutgoing: false,
pathBytes: Uint8List.fromList([0x53, 0x48, 0x9C]),
channelIndex: 0,
);
await tester.pumpWidget(
_wrapWithProviders(
connector,
ChannelMessagePathMapScreen(message: message, channelMessage: true),
),
);
await tester.pumpAndSettle();
await tester.tap(find.byIcon(Icons.open_in_full));
await tester.pumpAndSettle();
expect(find.textContaining('Beacon Hill 1W Repeater'), findsNothing);
expect(find.text('(9C) Unknown Repeater'), findsOneWidget);
expect(find.text('(48) Twain - Clearview'), findsOneWidget);
expect(find.text("(53) Rod's Repeater"), findsOneWidget);
final polylineLayer = tester.widget<PolylineLayer>(
find.byType(PolylineLayer),
);
final allPoints = polylineLayer.polylines
.expand((p) => p.points)
.toList();
expect(allPoints.length, 2);
for (final point in allPoints) {
expect(point.latitude, inInclusiveRange(33.0, 34.0));
expect(point.longitude, inInclusiveRange(-113.0, -111.0));
}
},
);
testWidgets(
'ChannelMessagePathScreen timeline treats impossible distant hop as unknown',
(tester) async {
final localHop = _repeater(
prefix: 0x48,
name: 'Twain - Clearview',
latitude: 33.60097,
longitude: -112.02457,
);
final bogusHop = _repeater(
prefix: 0x9C,
name: 'Beacon Hill 1W Repeater',
latitude: 42.3601,
longitude: -71.0589,
);
final connector = _FakeConnector([localHop, bogusHop]);
final message = ChannelMessage(
senderName: 'Alice',
text: 'test',
timestamp: DateTime.utc(2026),
isOutgoing: false,
pathBytes: Uint8List.fromList([0x48, 0x9C]),
channelIndex: 0,
);
await tester.pumpWidget(
_wrapWithProviders(
connector,
ChannelMessagePathScreen(message: message, channelMessage: true),
),
);
await tester.pumpAndSettle();
expect(find.text('(48) Twain - Clearview'), findsOneWidget);
expect(find.text('(9C) Unknown Repeater'), findsOneWidget);
expect(find.textContaining('Beacon Hill 1W Repeater'), findsNothing);
},
);
}
@@ -0,0 +1,399 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:provider/provider.dart';
import 'package:provider/single_child_widget.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:meshcore_open/connector/meshcore_connector.dart';
import 'package:meshcore_open/connector/meshcore_protocol.dart';
import 'package:meshcore_open/l10n/app_localizations.dart';
import 'package:meshcore_open/review_mode/review_frames.dart';
import 'package:meshcore_open/review_mode/review_radio.dart';
import 'package:meshcore_open/screens/channel_chat_screen.dart';
import 'package:meshcore_open/screens/chat_screen.dart';
import 'package:meshcore_open/services/app_debug_log_service.dart';
import 'package:meshcore_open/services/app_settings_service.dart';
import 'package:meshcore_open/services/ble_debug_log_service.dart';
import 'package:meshcore_open/services/chat_text_scale_service.dart';
import 'package:meshcore_open/services/image_codec_service.dart';
import 'package:meshcore_open/services/map_tile_cache_service.dart';
import 'package:meshcore_open/services/message_retry_service.dart';
import 'package:meshcore_open/services/path_history_service.dart';
import 'package:meshcore_open/services/received_image_store.dart';
import 'package:meshcore_open/services/storage_service.dart';
import 'package:meshcore_open/services/timeout_prediction_service.dart';
import 'package:meshcore_open/services/translation_service.dart';
import 'package:meshcore_open/services/ui_view_state_service.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:meshcore_open/theme/mesh_theme.dart';
import 'package:meshcore_open/widgets/chat_composer.dart';
const _screen = Size(400, 800);
const _keyboard = 300.0;
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final tempDir = Directory.systemTemp.createTempSync('app_switch_kb_test');
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(
const MethodChannel('plugins.flutter.io/path_provider'),
(call) async => tempDir.path,
);
setUpAll(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
});
// Android/iOS keep focus on the composer across an app switch; the OS may
// or may not bring the keyboard back. Layout must follow the reported
// inset, and the draft, focus and reading position must survive.
for (final keyboardBack in [true, false]) {
for (final atBottom in [false, true]) {
final keyboard = keyboardBack ? 'keyboard back' : 'OS closed keyboard';
final reading = atBottom ? 'at the bottom' : 'reading history';
testWidgets('mobile app switch: $keyboard, $reading', (tester) async {
tester.view.physicalSize = _screen;
tester.view.devicePixelRatio = 1.0;
addTearDown(tester.view.reset);
await _pumpChannelChat(tester);
await tester.tap(_composerField);
tester.view.viewInsets = const FakeViewPadding(bottom: _keyboard);
await _settle(tester);
await tester.enterText(_composerField, 'half written');
await _settle(tester);
if (!atBottom) {
await tester.drag(find.byType(ListView).first, const Offset(0, 300));
await _settle(tester);
}
final offsetBefore = _list(tester).position.pixels;
expect(offsetBefore, atBottom ? 0 : greaterThan(100));
expect(_composerBottom(tester), closeTo(_screen.height - _keyboard, 1));
// Switch away; the OS hides the keyboard while the app is hidden.
_goBackground(tester);
tester.view.viewInsets = FakeViewPadding.zero;
await tester.pump();
_goForeground(tester);
if (keyboardBack) {
tester.view.viewInsets = const FakeViewPadding(bottom: _keyboard);
}
await _settle(tester);
final inset = keyboardBack ? _keyboard : 0.0;
expect(_composerBottom(tester), closeTo(_screen.height - inset, 1));
expect(_composer(tester).focusNode.hasFocus, isTrue);
expect(_composer(tester).controller.text, 'half written');
expect(_list(tester).position.pixels, closeTo(offsetBefore, 1));
// Tapping the field opens the keyboard again above the composer.
await tester.tap(_composerField);
tester.view.viewInsets = const FakeViewPadding(bottom: _keyboard);
await _settle(tester);
expect(_composerBottom(tester), closeTo(_screen.height - _keyboard, 1));
expect(_composer(tester).controller.text, 'half written');
await _tearDown(tester);
});
}
}
// Desktop and web take focus away when the window goes inactive and restore
// it on resume. That restore used to count as "keyboard opened" and jumped
// the transcript to the newest message.
testWidgets('desktop app switch keeps the reading position', (tester) async {
tester.view.physicalSize = _screen;
tester.view.devicePixelRatio = 1.0;
addTearDown(tester.view.reset);
await _pumpChannelChat(tester);
await tester.tap(_composerField);
await _settle(tester);
await tester.enterText(_composerField, 'half written');
// Mouse-wheel up through the history; the composer keeps focus.
_list(tester).jumpTo(300);
await _settle(tester);
_goBackground(tester);
await tester.pump();
expect(_composer(tester).focusNode.hasFocus, isFalse);
_goForeground(tester);
await _settle(tester);
expect(_composer(tester).focusNode.hasFocus, isTrue);
expect(_composer(tester).controller.text, 'half written');
expect(_list(tester).position.pixels, closeTo(300, 1));
// A real click on the composer still jumps to the newest message.
_composer(tester).focusNode.unfocus();
await _settle(tester);
await tester.tap(_composerField);
await _settle(tester);
expect(_list(tester).position.pixels, 0);
await _tearDown(tester);
}, variant: TargetPlatformVariant.only(TargetPlatform.linux));
testWidgets(
'desktop app switch when focus is not restored does not swallow the next tap',
(tester) async {
tester.view.physicalSize = _screen;
tester.view.devicePixelRatio = 1.0;
addTearDown(tester.view.reset);
await _pumpChannelChat(tester);
await tester.tap(_composerField);
await _settle(tester);
_list(tester).jumpTo(300);
await _settle(tester);
_goBackground(tester);
await tester.pump();
expect(_composer(tester).focusNode.hasFocus, isFalse);
// User returns and interacts elsewhere (e.g. opens search) so focus is
// not restored to the composer on resume.
await tester.tap(find.byIcon(Icons.search));
await tester.pump();
_goForeground(tester);
await _settle(tester);
await tester.tap(find.byIcon(Icons.arrow_back));
await _settle(tester);
expect(_composer(tester).focusNode.hasFocus, isFalse);
expect(_list(tester).position.pixels, closeTo(300, 1));
await tester.tap(_composerField);
await _settle(tester);
expect(_composer(tester).focusNode.hasFocus, isTrue);
expect(_list(tester).position.pixels, 0);
await _tearDown(tester);
},
variant: TargetPlatformVariant.only(TargetPlatform.linux),
);
testWidgets(
'DM chat: desktop app switch and dialog close keep reading position',
(tester) async {
tester.view.physicalSize = _screen;
tester.view.devicePixelRatio = 1.0;
addTearDown(tester.view.reset);
await _pumpDirectChat(tester);
await tester.tap(_composerField);
await _settle(tester);
_list(tester).jumpTo(300);
await _settle(tester);
// App switch away and back restores focus without jumping to bottom.
_goBackground(tester);
await tester.pump();
expect(_composer(tester).focusNode.hasFocus, isFalse);
_goForeground(tester);
await _settle(tester);
expect(_composer(tester).focusNode.hasFocus, isTrue);
expect(_list(tester).position.pixels, closeTo(300, 1));
// Opening and closing a dialog over the chat returns focus without jumping.
await tester.tap(find.byIcon(Icons.more_vert));
await _settle(tester);
await tester.tap(find.byIcon(Icons.info_outline));
await _settle(tester);
expect(find.byType(AlertDialog), findsOneWidget);
Navigator.of(tester.element(find.byType(AlertDialog))).pop();
await _settle(tester);
expect(_list(tester).position.pixels, closeTo(300, 1));
// Losing focus in the foreground and tapping again still jumps to bottom.
_composer(tester).focusNode.unfocus();
await _settle(tester);
await tester.tap(_composerField);
await _settle(tester);
expect(_list(tester).position.pixels, 0);
await _tearDown(tester);
},
variant: TargetPlatformVariant.only(TargetPlatform.linux),
);
}
final _composerField = find.descendant(
of: find.byType(ChatComposer),
matching: find.byType(EditableText),
);
EditableText _composer(WidgetTester tester) =>
tester.widget<EditableText>(_composerField);
void _goBackground(WidgetTester tester) {
for (final state in const [
AppLifecycleState.inactive,
AppLifecycleState.hidden,
AppLifecycleState.paused,
]) {
tester.binding.handleAppLifecycleStateChanged(state);
}
}
void _goForeground(WidgetTester tester) {
for (final state in const [
AppLifecycleState.hidden,
AppLifecycleState.inactive,
AppLifecycleState.resumed,
]) {
tester.binding.handleAppLifecycleStateChanged(state);
}
}
ScrollController _list(WidgetTester tester) => tester
.widget<ListView>(find.byWidgetPredicate((w) => w is ListView).first)
.controller!;
double _composerBottom(WidgetTester tester) =>
tester.getBottomLeft(find.byType(ChatComposer)).dy;
Future<void> _settle(WidgetTester tester) async {
for (var i = 0; i < 10; i++) {
await tester.pump(const Duration(milliseconds: 100));
}
}
Future<void> _tearDown(WidgetTester tester) async {
await tester.pumpWidget(const SizedBox());
await tester.pump(const Duration(minutes: 1));
}
(MeshCoreConnector, List<SingleChildWidget>)? _shared;
Future<MeshCoreConnector> _pumpChannelChat(WidgetTester tester) async {
final (connector, providers) = _shared ??= await _connect(tester);
await _pumpScreen(
tester,
providers,
ChannelChatScreen(channel: connector.channels[0]),
);
return connector;
}
Future<MeshCoreConnector> _pumpDirectChat(WidgetTester tester) async {
final (connector, providers) = _shared ??= await _connect(tester);
final contact = connector.contacts.firstWhere((c) => c.type == advTypeChat);
if (connector.getMessages(contact).length < 40) {
final now = DateTime.now().millisecondsSinceEpoch ~/ 1000;
for (var i = 0; i < 40; i++) {
connector.handleFrameForTest(
ReviewFrames.contactMessage(
senderPublicKey: contact.publicKey,
text: 'Direct history line $i about the weather on the hill',
timestampSecs: now - 4000 + i,
),
);
}
}
await _pumpScreen(tester, providers, ChatScreen(contact: contact));
return connector;
}
Future<void> _pumpScreen(
WidgetTester tester,
List<SingleChildWidget> providers,
Widget screen,
) async {
await tester.pumpWidget(
MultiProvider(
providers: providers,
child: MaterialApp(
theme: MeshTheme.light(),
locale: const Locale('en'),
localizationsDelegates: const [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: AppLocalizations.supportedLocales,
home: screen,
),
),
);
await _settle(tester);
}
Future<(MeshCoreConnector, List<SingleChildWidget>)> _connect(
WidgetTester tester,
) async {
final storage = StorageService();
final connector = MeshCoreConnector();
final retry = MessageRetryService();
final settings = AppSettingsService();
final translation = TranslationService(settings);
await tester.runAsync(() async {
await settings.loadSettings();
connector.initialize(
retryService: retry,
pathHistoryService: PathHistoryService(storage),
appSettingsService: settings,
translationService: translation,
);
connector.reviewRadioFactoryForTest = () => ReviewRadio(
scheduledMessageInterval: const Duration(hours: 1),
ackDelay: const Duration(hours: 1),
replyDelay: const Duration(hours: 1),
);
await connector.connectReview();
final end = DateTime.now().add(const Duration(seconds: 8));
while (connector.channels.isEmpty && DateTime.now().isBefore(end)) {
await Future<void>.delayed(const Duration(milliseconds: 25));
}
// Enough history that the transcript scrolls with or without a keyboard.
final now = DateTime.now().millisecondsSinceEpoch ~/ 1000;
for (var i = 0; i < 40; i++) {
connector.handleFrameForTest(
ReviewFrames.channelMessage(
channelIndex: 0,
sender: 'Tester',
message: 'History line number $i about the weather on the hill',
timestampSecs: now - 4000 + i,
),
);
}
while (connector.getChannelMessages(connector.channels[0]).length < 40 &&
DateTime.now().isBefore(end)) {
await Future<void>.delayed(const Duration(milliseconds: 25));
}
});
expect(connector.channels, isNotEmpty);
return (
connector,
<SingleChildWidget>[
ChangeNotifierProvider.value(value: connector),
ChangeNotifierProvider.value(value: retry),
ChangeNotifierProvider.value(value: PathHistoryService(storage)),
ChangeNotifierProvider.value(value: settings),
ChangeNotifierProvider.value(value: BleDebugLogService()),
ChangeNotifierProvider.value(value: AppDebugLogService()),
ChangeNotifierProvider.value(value: ChatTextScaleService()),
ChangeNotifierProvider.value(value: translation),
ChangeNotifierProvider.value(value: UiViewStateService()),
Provider.value(value: storage),
ChangeNotifierProvider.value(
value: MapTileCacheService(appSettingsService: settings),
),
ChangeNotifierProvider.value(value: TimeoutPredictionService(storage)),
ChangeNotifierProvider.value(value: ImageCodecService(settings)),
ChangeNotifierProvider.value(value: ReceivedImageStore()),
],
);
}
+419
View File
@@ -0,0 +1,419 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:meshcore_open/connector/meshcore_connector.dart';
import 'package:meshcore_open/connector/meshcore_protocol.dart';
import 'package:meshcore_open/l10n/app_localizations.dart';
import 'package:meshcore_open/models/channel.dart';
import 'package:meshcore_open/models/channel_message.dart';
import 'package:meshcore_open/models/contact.dart';
import 'package:meshcore_open/models/message.dart';
import 'package:meshcore_open/screens/channel_chat_screen.dart';
import 'package:meshcore_open/screens/chat_screen.dart';
import 'package:meshcore_open/services/app_debug_log_service.dart';
import 'package:meshcore_open/services/app_settings_service.dart';
import 'package:meshcore_open/services/ble_debug_log_service.dart';
import 'package:meshcore_open/services/chat_text_scale_service.dart';
import 'package:meshcore_open/services/image_codec_service.dart';
import 'package:meshcore_open/services/map_tile_cache_service.dart';
import 'package:meshcore_open/services/message_retry_service.dart';
import 'package:meshcore_open/services/network_map/network_map_upload_service.dart';
import 'package:meshcore_open/services/path_history_service.dart';
import 'package:meshcore_open/services/received_image_store.dart';
import 'package:meshcore_open/services/storage_service.dart';
import 'package:meshcore_open/services/timeout_prediction_service.dart';
import 'package:meshcore_open/services/translation_service.dart';
import 'package:meshcore_open/services/ui_view_state_service.dart';
import 'package:meshcore_open/storage/channel_message_store.dart';
import 'package:meshcore_open/storage/channel_store.dart';
import 'package:meshcore_open/storage/contact_store.dart';
import 'package:meshcore_open/storage/last_radio_store.dart';
import 'package:meshcore_open/storage/message_store.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:meshcore_open/theme/mesh_theme.dart';
import 'package:meshcore_open/utils/platform_info.dart';
import 'package:meshcore_open/widgets/message_bubble_frame.dart';
final _radioKey = Uint8List.fromList(List<int>.generate(32, (i) => 0xA0 + i));
final _radioHex = pubKeyToHex(_radioKey);
final _aliceKey = Uint8List.fromList(List<int>.generate(32, (i) => 0x10 + i));
final _psk = Uint8List.fromList(List<int>.generate(16, (i) => 0x40 + i));
const _long =
'The ridge trail is washed out past the second bridge, so take the '
'lower path along the river and meet us at the old ranger station.';
/// Shows the saved radio as connected or offline without a transport, so
/// both states render exactly the same stored transcript.
class _ToggleConnector extends MeshCoreConnector {
bool connected = false;
@override
bool get isConnected => connected;
}
// Two-digit local hour (10:13 PM / 22:13) so narrow 2.0x text checks the wide
// timestamp layout regardless of host timezone.
DateTime _at(int seconds) => DateTime(2023, 11, 14, 22, 13, seconds);
Future<void> _seedRadio({
bool smazCompressed = false,
int repeatCount = 0,
}) async {
final alice = Contact(
publicKey: _aliceKey,
name: 'Alice',
type: advTypeChat,
pathLength: 1,
path: Uint8List.fromList([0x22]),
lastSeen: _at(0),
);
await (ContactStore()..setPublicKeyHex = _radioHex).saveContacts([alice]);
final channel = Channel(index: 0, name: 'Base Camp', psk: _psk);
final channelStore = ChannelStore()..setPublicKeyHex = _radioHex;
await channelStore.saveChannels([channel]);
await channelStore.saveSlotChannelIds({0: channel.storageId!});
ChannelMessage channelMessage(
int second,
String text, {
required bool outgoing,
String? translated,
}) => ChannelMessage(
senderName: outgoing ? 'Base' : 'Bob',
text: text,
translatedText: translated,
timestamp: _at(second),
isOutgoing: outgoing,
isSmazCompressed: smazCompressed,
repeatCount: repeatCount,
status: ChannelMessageStatus.sent,
channelIndex: 0,
);
await (ChannelMessageStore()..setPublicKeyHex = _radioHex)
.saveChannelMessages(channel.storageId!, [
channelMessage(1, 'ok', outgoing: false),
channelMessage(2, _long, outgoing: false),
channelMessage(3, 'on my way', outgoing: true),
channelMessage(4, _long, outgoing: true),
channelMessage(
5,
'Der Weg ist frei',
outgoing: false,
translated: 'The path is clear',
),
]);
Message directMessage(
int second,
String text, {
required bool outgoing,
String? translated,
}) => Message(
senderKey: _aliceKey,
text: text,
translatedText: translated,
timestamp: _at(second),
isOutgoing: outgoing,
isSmazCompressed: smazCompressed,
status: MessageStatus.delivered,
);
await (MessageStore()..setPublicKeyHex = _radioHex)
.saveMessages(alice.publicKeyHex, [
directMessage(1, 'hi', outgoing: false),
directMessage(2, _long, outgoing: false),
directMessage(3, 'see you', outgoing: true),
directMessage(4, _long, outgoing: true),
directMessage(
5,
'Der Weg ist frei',
outgoing: false,
translated: 'The path is clear',
),
]);
await LastRadioStore().save(
LastRadio(
publicKeyHex: _radioHex,
name: 'Base',
transport: LastRadio.transportBle,
bleRemoteId: 'AA:BB:CC:DD:EE:FF',
savedAt: _at(0),
),
);
}
Future<Widget> _app(
WidgetTester tester,
MeshCoreConnector connector,
Widget home, {
bool showCompressionIndicator = false,
bool enableMessageTracing = false,
}) async {
final storage = StorageService();
final settings = AppSettingsService();
await tester.runAsync(() async {
await settings.loadSettings();
if (showCompressionIndicator) {
await settings.setShowCompressionIndicator(true);
}
if (enableMessageTracing) {
await settings.setEnableMessageTracing(true);
}
});
final translation = TranslationService(settings);
return MultiProvider(
providers: [
ChangeNotifierProvider.value(value: connector),
ChangeNotifierProvider.value(value: MessageRetryService()),
ChangeNotifierProvider.value(value: PathHistoryService(storage)),
ChangeNotifierProvider.value(value: settings),
ChangeNotifierProvider.value(value: BleDebugLogService()),
ChangeNotifierProvider.value(value: AppDebugLogService()),
ChangeNotifierProvider.value(value: ChatTextScaleService()),
ChangeNotifierProvider.value(value: translation),
ChangeNotifierProvider.value(value: UiViewStateService()),
Provider.value(value: storage),
ChangeNotifierProvider.value(
value: MapTileCacheService(appSettingsService: settings),
),
ChangeNotifierProvider.value(value: TimeoutPredictionService(storage)),
ChangeNotifierProvider.value(value: ImageCodecService(settings)),
ChangeNotifierProvider.value(value: ReceivedImageStore()),
ChangeNotifierProvider.value(
value: NetworkMapUploadService(
connector: connector,
settings: settings,
),
),
],
child: MaterialApp(
theme: MeshTheme.light(),
locale: const Locale('en'),
localizationsDelegates: const [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: AppLocalizations.supportedLocales,
home: home,
),
);
}
Future<void> _settle(WidgetTester tester) async {
for (var i = 0; i < 10; i++) {
await tester.pump(const Duration(milliseconds: 100));
}
}
/// Horizontal extent of every rendered bubble, in transcript order.
List<String> _bubbleExtents(WidgetTester tester) {
final frames = find.byType(MessageBubbleFrame);
expect(frames, findsWidgets);
return [
for (final element in frames.evaluate())
() {
final rect = tester.getRect(find.byWidget(element.widget));
return '${rect.left.toStringAsFixed(1)}..'
'${rect.right.toStringAsFixed(1)}';
}(),
];
}
Future<List<String>> _render(
WidgetTester tester,
_ToggleConnector connector,
Widget Function() screen, {
required bool connected,
bool showCompressionIndicator = false,
bool enableMessageTracing = false,
bool expectCompressionIndicator = false,
}) async {
connector.connected = connected;
await tester.pumpWidget(
await _app(
tester,
connector,
screen(),
showCompressionIndicator: showCompressionIndicator,
enableMessageTracing: enableMessageTracing,
),
);
await _settle(tester);
if (expectCompressionIndicator) {
expect(find.byType(CompressionIndicator), findsNWidgets(5));
}
final extents = _bubbleExtents(tester);
await tester.pumpWidget(const SizedBox());
await tester.pump(const Duration(seconds: 1));
return extents;
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final tempDir = Directory.systemTemp.createTempSync('bubble_width_test');
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(
const MethodChannel('plugins.flutter.io/path_provider'),
(call) async => tempDir.path,
);
setUp(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
ChannelMessageStore().forgetArchive();
MessageStore().forgetArchive();
await _seedRadio();
ChannelMessageStore().forgetArchive();
MessageStore().forgetArchive();
});
// On phones, incoming channel bubbles are swipeable (reply) only while
// connected; that must not change their size or position. Day separators
// and bubbles must also fit 320dp at large text sizes.
for (final desktop in [false, true]) {
for (final scale in [1.0, 1.3, 2.0]) {
final label = '${desktop ? 'desktop' : 'phone'}, 320dp, ${scale}x text';
testWidgets('channel bubbles match connected vs offline ($label)', (
tester,
) async {
PlatformInfo.debugIsDesktopOverride = desktop;
addTearDown(() => PlatformInfo.debugIsDesktopOverride = null);
tester.view.physicalSize = const Size(320, 4000);
tester.view.devicePixelRatio = 1;
tester.platformDispatcher.textScaleFactorTestValue = scale;
addTearDown(tester.view.reset);
addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
final connector = _ToggleConnector();
addTearDown(connector.dispose);
await tester.runAsync(connector.restoreLastRadio);
final channel = connector.channels.single;
final offline = await _render(
tester,
connector,
() => ChannelChatScreen(channel: channel),
connected: false,
);
final connected = await _render(
tester,
connector,
() => ChannelChatScreen(channel: channel),
connected: true,
);
expect(offline, hasLength(5));
expect(connected, offline);
});
testWidgets('DM bubbles match connected vs offline ($label)', (
tester,
) async {
PlatformInfo.debugIsDesktopOverride = desktop;
addTearDown(() => PlatformInfo.debugIsDesktopOverride = null);
tester.view.physicalSize = const Size(320, 4000);
tester.view.devicePixelRatio = 1;
tester.platformDispatcher.textScaleFactorTestValue = scale;
addTearDown(tester.view.reset);
addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
final connector = _ToggleConnector();
addTearDown(connector.dispose);
await tester.runAsync(connector.restoreLastRadio);
final alice = connector.contacts.single;
final offline = await _render(
tester,
connector,
() => ChatScreen(contact: alice),
connected: false,
);
final connected = await _render(
tester,
connector,
() => ChatScreen(contact: alice),
connected: true,
);
expect(offline, hasLength(5));
expect(connected, offline);
});
}
}
testWidgets(
'channel and DM bubbles with SMAZ compression indicator fit 320dp, 2.0x text',
(tester) async {
ChannelMessageStore().forgetArchive();
MessageStore().forgetArchive();
await _seedRadio(smazCompressed: true, repeatCount: 2);
ChannelMessageStore().forgetArchive();
MessageStore().forgetArchive();
PlatformInfo.debugIsDesktopOverride = false;
addTearDown(() => PlatformInfo.debugIsDesktopOverride = null);
tester.view.physicalSize = const Size(320, 4000);
tester.view.devicePixelRatio = 1;
tester.platformDispatcher.textScaleFactorTestValue = 2.0;
addTearDown(tester.view.reset);
addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
final connector = _ToggleConnector();
addTearDown(connector.dispose);
await tester.runAsync(connector.restoreLastRadio);
final channel = connector.channels.single;
final alice = connector.contacts.single;
final channelOffline = await _render(
tester,
connector,
() => ChannelChatScreen(channel: channel),
connected: false,
showCompressionIndicator: true,
enableMessageTracing: true,
expectCompressionIndicator: true,
);
final channelConnected = await _render(
tester,
connector,
() => ChannelChatScreen(channel: channel),
connected: true,
showCompressionIndicator: true,
enableMessageTracing: true,
expectCompressionIndicator: true,
);
expect(channelOffline, hasLength(5));
expect(channelConnected, channelOffline);
final dmOffline = await _render(
tester,
connector,
() => ChatScreen(contact: alice),
connected: false,
showCompressionIndicator: true,
enableMessageTracing: true,
expectCompressionIndicator: true,
);
final dmConnected = await _render(
tester,
connector,
() => ChatScreen(contact: alice),
connected: true,
showCompressionIndicator: true,
enableMessageTracing: true,
expectCompressionIndicator: true,
);
expect(dmOffline, hasLength(5));
expect(dmConnected, dmOffline);
},
);
}
@@ -0,0 +1,206 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:provider/provider.dart';
import 'package:provider/single_child_widget.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:meshcore_open/connector/meshcore_connector.dart';
import 'package:meshcore_open/connector/meshcore_protocol.dart';
import 'package:meshcore_open/l10n/app_localizations.dart';
import 'package:meshcore_open/review_mode/review_radio.dart';
import 'package:meshcore_open/screens/channel_chat_screen.dart';
import 'package:meshcore_open/screens/chat_screen.dart';
import 'package:meshcore_open/services/app_debug_log_service.dart';
import 'package:meshcore_open/services/app_settings_service.dart';
import 'package:meshcore_open/services/ble_debug_log_service.dart';
import 'package:meshcore_open/services/chat_text_scale_service.dart';
import 'package:meshcore_open/services/image_codec_service.dart';
import 'package:meshcore_open/services/map_tile_cache_service.dart';
import 'package:meshcore_open/services/message_retry_service.dart';
import 'package:meshcore_open/services/path_history_service.dart';
import 'package:meshcore_open/services/received_image_store.dart';
import 'package:meshcore_open/services/storage_service.dart';
import 'package:meshcore_open/services/timeout_prediction_service.dart';
import 'package:meshcore_open/services/translation_service.dart';
import 'package:meshcore_open/services/ui_view_state_service.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:meshcore_open/theme/mesh_theme.dart';
import 'package:meshcore_open/widgets/chat_background.dart';
import 'package:meshcore_open/widgets/chat_composer.dart';
import 'package:meshcore_open/widgets/message_bubble_frame.dart';
final _l10n = lookupAppLocalizations(const Locale('en'));
/// Both chat screens show the same composer, as the footer of the chat
/// background, and the channel reply preview sits inside its bubble.
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final tempDir = Directory.systemTemp.createTempSync('chat_composer_test');
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(
const MethodChannel('plugins.flutter.io/path_provider'),
(call) async => tempDir.path,
);
setUpAll(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
});
Finder composerIn(Type screen) => find.descendant(
of: find.descendant(
of: find.byType(screen),
matching: find.byType(ChatBackdrop),
),
matching: find.byType(ChatComposer),
);
testWidgets('DM chat shows the redesigned composer', (tester) async {
final (connector, providers) = _shared ??= await _connect(tester);
final contact = connector.contacts.firstWhere((c) => c.type == advTypeChat);
await _pump(tester, providers, ChatScreen(contact: contact));
expect(composerIn(ChatScreen), findsOneWidget);
expect(find.byTooltip(_l10n.chat_selectSendAction), findsOneWidget);
expect(find.byIcon(Icons.add_circle_outline), findsNothing);
await tester.enterText(find.byType(TextField), 'hello');
await _settle(tester);
expect(find.byTooltip(_l10n.chat_selectSendAction), findsNothing);
expect(find.byTooltip(_l10n.chat_sendMessageTo(contact.name)), findsOne);
await _tearDown(tester);
});
testWidgets('channel chat shows the same composer with the reply preview '
'inside the bubble', (tester) async {
final (connector, providers) = _shared ??= await _connect(tester);
final channel = connector.channels[0];
await _pump(tester, providers, ChannelChatScreen(channel: channel));
expect(composerIn(ChannelChatScreen), findsOneWidget);
expect(find.byTooltip(_l10n.chat_selectSendAction), findsOneWidget);
expect(find.byType(ChatComposerQuote), findsNothing);
final incoming = connector
.getChannelMessages(channel)
.lastWhere((m) => !m.isOutgoing);
final bubble = find.ancestor(
of: find.textContaining(incoming.text, findRichText: true),
matching: find.byType(MessageBubbleFrame),
);
await tester.longPressAt(tester.getTopLeft(bubble) + const Offset(4, 4));
await _settle(tester);
await tester.tap(find.text(_l10n.chat_reply));
await _settle(tester);
final quote = find.byType(ChatComposerQuote);
expect(
find.descendant(of: find.byKey(ChatComposer.bubbleKey), matching: quote),
findsOneWidget,
);
expect(find.text(_l10n.chat_replyingTo(incoming.senderName)), findsOne);
await tester.tap(find.byTooltip(_l10n.chat_cancelReply));
await _settle(tester);
expect(quote, findsNothing);
await _tearDown(tester);
});
}
Future<void> _pump(
WidgetTester tester,
List<SingleChildWidget> providers,
Widget home,
) async {
await tester.pumpWidget(
MultiProvider(
providers: providers,
child: MaterialApp(
theme: MeshTheme.light(),
locale: const Locale('en'),
localizationsDelegates: const [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: AppLocalizations.supportedLocales,
home: home,
),
),
);
await _settle(tester);
}
Future<void> _settle(WidgetTester tester) async {
for (var i = 0; i < 10; i++) {
await tester.pump(const Duration(milliseconds: 100));
}
}
Future<void> _tearDown(WidgetTester tester) async {
await tester.pumpWidget(const SizedBox());
await tester.pump(const Duration(minutes: 1));
}
/// One review-radio connection shared by the tests.
(MeshCoreConnector, List<SingleChildWidget>)? _shared;
Future<(MeshCoreConnector, List<SingleChildWidget>)> _connect(
WidgetTester tester,
) async {
final storage = StorageService();
final connector = MeshCoreConnector();
final retry = MessageRetryService();
final settings = AppSettingsService();
final translation = TranslationService(settings);
await tester.runAsync(() async {
await settings.loadSettings();
connector.initialize(
retryService: retry,
pathHistoryService: PathHistoryService(storage),
appSettingsService: settings,
translationService: translation,
);
connector.reviewRadioFactoryForTest = () => ReviewRadio(
scheduledMessageInterval: const Duration(hours: 1),
ackDelay: const Duration(hours: 1),
replyDelay: const Duration(hours: 1),
);
await connector.connectReview();
final end = DateTime.now().add(const Duration(seconds: 8));
while ((connector.contacts.isEmpty || connector.channels.isEmpty) &&
DateTime.now().isBefore(end)) {
await Future<void>.delayed(const Duration(milliseconds: 25));
}
});
expect(connector.channels, isNotEmpty);
return (
connector,
<SingleChildWidget>[
ChangeNotifierProvider.value(value: connector),
ChangeNotifierProvider.value(value: retry),
ChangeNotifierProvider.value(value: PathHistoryService(storage)),
ChangeNotifierProvider.value(value: settings),
ChangeNotifierProvider.value(value: BleDebugLogService()),
ChangeNotifierProvider.value(value: AppDebugLogService()),
ChangeNotifierProvider.value(value: ChatTextScaleService()),
ChangeNotifierProvider.value(value: translation),
ChangeNotifierProvider.value(value: UiViewStateService()),
Provider.value(value: storage),
ChangeNotifierProvider.value(
value: MapTileCacheService(appSettingsService: settings),
),
ChangeNotifierProvider.value(value: TimeoutPredictionService(storage)),
ChangeNotifierProvider.value(value: ImageCodecService(settings)),
ChangeNotifierProvider.value(value: ReceivedImageStore()),
],
);
}
+649
View File
@@ -0,0 +1,649 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:provider/provider.dart';
import 'package:provider/single_child_widget.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:meshcore_open/connector/meshcore_connector.dart';
import 'package:meshcore_open/connector/meshcore_protocol.dart';
import 'package:meshcore_open/helpers/link_handler.dart';
import 'package:meshcore_open/l10n/app_localizations.dart';
import 'package:meshcore_open/models/custom_theme.dart';
import 'package:meshcore_open/review_mode/review_frames.dart';
import 'package:meshcore_open/review_mode/review_radio.dart';
import 'package:meshcore_open/screens/channel_chat_screen.dart';
import 'package:meshcore_open/screens/chat_screen.dart';
import 'package:meshcore_open/screens/coordinate_map_screen.dart';
import 'package:meshcore_open/services/app_debug_log_service.dart';
import 'package:meshcore_open/services/app_settings_service.dart';
import 'package:meshcore_open/services/ble_debug_log_service.dart';
import 'package:meshcore_open/services/chat_text_scale_service.dart';
import 'package:meshcore_open/services/image_codec_service.dart';
import 'package:meshcore_open/services/map_tile_cache_service.dart';
import 'package:meshcore_open/services/message_retry_service.dart';
import 'package:meshcore_open/services/path_history_service.dart';
import 'package:meshcore_open/services/received_image_store.dart';
import 'package:meshcore_open/services/storage_service.dart';
import 'package:meshcore_open/services/timeout_prediction_service.dart';
import 'package:meshcore_open/services/translation_service.dart';
import 'package:meshcore_open/services/ui_view_state_service.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:meshcore_open/theme/mesh_theme.dart';
import 'package:meshcore_open/utils/platform_info.dart';
final _l10n = lookupAppLocalizations(const Locale('en'));
(MeshCoreConnector, List<SingleChildWidget>)? _shared;
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final tempDir = Directory.systemTemp.createTempSync(
'coordinate_messages_test',
);
String? copiedText;
final launchedUrls = <String>[];
setUpAll(() async {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(
const MethodChannel('plugins.flutter.io/path_provider'),
(call) async => tempDir.path,
);
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(SystemChannels.platform, (call) async {
if (call.method == 'Clipboard.setData') {
copiedText =
(call.arguments as Map<dynamic, dynamic>)['text'] as String?;
}
return null;
});
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(
const MethodChannel('plugins.flutter.io/url_launcher'),
(call) async {
if (call.method == 'launch' || call.method == 'launchUrl') {
final args = call.arguments as Map<dynamic, dynamic>;
launchedUrls.add(args['url'] as String);
return true;
}
if (call.method == 'canLaunch') {
return true;
}
return true;
},
);
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
});
tearDownAll(() {
_shared = null;
if (tempDir.existsSync()) {
tempDir.deleteSync(recursive: true);
}
});
setUp(() {
copiedText = null;
launchedUrls.clear();
});
/// Finds the global center of the first substring matching [target] inside
/// a [RenderParagraph] (mobile) or [RenderEditable] (desktop).
Offset findSpanOffset(WidgetTester tester, String target) {
for (final render in tester.renderObjectList<RenderParagraph>(
find.byType(RichText),
)) {
final plain = render.text.toPlainText();
final idx = plain.indexOf(target);
if (idx < 0) continue;
final boxes = render.getBoxesForSelection(
TextSelection(baseOffset: idx, extentOffset: idx + target.length),
);
if (boxes.isNotEmpty) {
final localCenter = boxes.first.toRect().center;
return render.localToGlobal(localCenter);
}
}
for (final state in tester.stateList<EditableTextState>(
find.byType(EditableText),
)) {
final editable = state.renderEditable;
final plain = editable.plainText;
final idx = plain.indexOf(target);
if (idx < 0) continue;
final boxes = editable.getEndpointsForSelection(
TextSelection(baseOffset: idx, extentOffset: idx + target.length),
);
if (boxes.isNotEmpty) {
final first = boxes.first.point;
final last = boxes.last.point;
final localCenter = Offset((first.dx + last.dx) / 2, first.dy - 6);
return editable.localToGlobal(localCenter);
}
}
fail('Could not locate rendered span for "$target"');
}
for (final isDesktop in [false, true]) {
final platformLabel = isDesktop ? 'desktop' : 'phone';
testWidgets(
'DM message with URL and coordinate: tap opens map, Back preserves scroll, '
'long-press shows menu, non-coordinate gestures preserved ($platformLabel)',
(tester) async {
PlatformInfo.debugIsDesktopOverride = isDesktop;
addTearDown(() => PlatformInfo.debugIsDesktopOverride = null);
final (connector, providers) = _shared ??= await _connect(tester);
final contact = connector.contacts.firstWhere(
(c) => c.type == advTypeChat,
);
final nowSecs = DateTime.now().millisecondsSinceEpoch ~/ 1000;
const coord = '37.7749, -122.4194';
const url = 'https://example.com/trail';
const messageText = 'Check $url and meet at $coord soon';
await tester.runAsync(() async {
connector.handleFrameForTest(
ReviewFrames.contactMessage(
senderPublicKey: contact.publicKey,
text: messageText,
timestampSecs: nowSecs - 60,
),
);
for (var i = 0; i < 18; i++) {
connector.handleFrameForTest(
ReviewFrames.contactMessage(
senderPublicKey: contact.publicKey,
text: 'Filler message #$i',
timestampSecs: nowSecs - 30 + i,
),
);
}
connector.handleFrameForTest(
ReviewFrames.contactMessage(
senderPublicKey: contact.publicKey,
text: 'Reply sent at 45.5152, -122.6784',
timestampSecs: nowSecs,
),
);
await Future<void>.delayed(const Duration(milliseconds: 50));
});
await _pumpApp(tester, providers, ChatScreen(contact: contact));
final scrollable = tester.widget<Scrollable>(
find.byType(Scrollable).first,
);
final controller = scrollable.controller!;
final targetFinder = find.textContaining(coord, findRichText: true);
if (targetFinder.evaluate().isEmpty) {
await tester.dragUntilVisible(
targetFinder,
find.byType(Scrollable).first,
const Offset(0, 200),
maxIteration: 30,
);
}
await Scrollable.ensureVisible(
tester.element(targetFinder.first),
alignment: 0.5,
);
await _settle(tester);
final savedOffset = controller.offset;
expect(savedOffset, greaterThan(0));
// 1. Tap coordinate -> opens CoordinateMapScreen with pin + label + centered AppBar.
final coordCenter = findSpanOffset(tester, coord);
await tester.tapAt(coordCenter);
await _settle(tester);
expect(find.byType(CoordinateMapScreen), findsOneWidget);
expect(find.text(coord), findsOneWidget);
final appBar = tester.widget<AppBar>(find.byType(AppBar));
expect(appBar.centerTitle, isTrue);
final flutterMap = tester.widget<FlutterMap>(find.byType(FlutterMap));
expect(
flutterMap.options.initialCenter.latitude,
closeTo(37.7749, 1e-6),
);
expect(
flutterMap.options.initialCenter.longitude,
closeTo(-122.4194, 1e-6),
);
expect(find.byIcon(Icons.location_on), findsOneWidget);
// 2. Pressing Back returns to exact same chat and scroll position.
await tester.pageBack();
await _settle(tester);
expect(find.byType(CoordinateMapScreen), findsNothing);
expect(find.byType(ChatScreen), findsOneWidget);
expect(controller.offset, closeTo(savedOffset, 1.0));
// 3. Long-press coordinate -> opens Copy & Open in maps sheet (NOT bubble menu).
await tester.longPressAt(findSpanOffset(tester, coord));
await _settle(tester);
expect(find.text(_l10n.coordinate_copyLocation), findsOneWidget);
expect(find.text(_l10n.coordinate_openInMaps), findsOneWidget);
expect(find.text(_l10n.chat_reply), findsNothing);
// Copy location writes to clipboard and shows snackbar.
await tester.tap(find.text(_l10n.coordinate_copyLocation));
await _settle(tester);
expect(copiedText, coord);
expect(find.text(_l10n.coordinate_copied), findsOneWidget);
// Re-open long-press sheet and tap Open in maps.
await tester.longPressAt(findSpanOffset(tester, coord));
await _settle(tester);
await tester.tap(find.text(_l10n.coordinate_openInMaps));
await _settle(tester);
expect(launchedUrls, isNotEmpty);
expect(launchedUrls.last, contains('37.7749'));
expect(launchedUrls.last, contains('-122.4194'));
// 4. Tapping URL still opens existing URL confirmation dialog.
await tester.tapAt(findSpanOffset(tester, url));
await _settle(tester);
expect(find.text(_l10n.chat_openLink), findsOneWidget);
await tester.tap(find.text(_l10n.common_cancel));
await _settle(tester);
// 5. Long-pressing non-coordinate text in same message opens bubble actions.
if (!isDesktop) {
await tester.longPressAt(findSpanOffset(tester, 'Check'));
await _settle(tester);
expect(find.text(_l10n.chat_addReaction), findsOneWidget);
Navigator.of(tester.element(find.text(_l10n.chat_addReaction))).pop();
await _settle(tester);
}
await _tearDown(tester);
},
);
}
testWidgets(
'Channel messages render coordinates, support tap/long-press, and fit 320dp @ 1.3x & 2.0x',
(tester) async {
PlatformInfo.debugIsDesktopOverride = false;
addTearDown(() => PlatformInfo.debugIsDesktopOverride = null);
final (connector, providers) = _shared ??= await _connect(tester);
final channel = connector.channels.first;
final nowSecs = DateTime.now().millisecondsSinceEpoch ~/ 1000;
const channelCoord = '-33.86882, 151.20929';
const channelMsg =
'#wardriving https://meshcore.co.uk at ($channelCoord) SNR 7.5dB';
await tester.runAsync(() async {
connector.handleFrameForTest(
ReviewFrames.channelMessage(
channelIndex: channel.index,
sender: 'Maya',
message: channelMsg,
timestampSecs: nowSecs - 30,
),
);
await Future<void>.delayed(const Duration(milliseconds: 50));
});
final customTheme = MeshTheme.fromCustom(
CustomTheme(
id: 'test-forest',
name: 'Forest',
background: const Color(0xFF0E1A13),
accent: const Color(0xFF4ADE80),
),
);
for (final scale in [1.3, 2.0]) {
tester.view.physicalSize = const Size(320, 568);
tester.view.devicePixelRatio = 1.0;
addTearDown(tester.view.reset);
final overflows = <String>[];
final previousError = FlutterError.onError;
FlutterError.onError = (details) {
final text = details.exceptionAsString();
if (text.contains('overflowed')) {
overflows.add(text.split('\n').first);
} else {
previousError?.call(details);
}
};
addTearDown(() => FlutterError.onError = previousError);
await _pumpApp(
tester,
providers,
ChannelChatScreen(channel: channel),
theme: customTheme,
textScaler: TextScaler.linear(scale),
);
final coordFinder = find.textContaining(
channelCoord,
findRichText: true,
);
if (coordFinder.evaluate().isEmpty) {
await tester.dragUntilVisible(
coordFinder,
find.byType(Scrollable).first,
const Offset(0, 200),
maxIteration: 30,
);
}
await Scrollable.ensureVisible(
tester.element(coordFinder.first),
alignment: 0.5,
);
await _settle(tester);
// Long-press coordinate in channel message -> bottom sheet fits 320dp without overflow.
await tester.longPressAt(findSpanOffset(tester, channelCoord));
await _settle(tester);
expect(find.text(_l10n.coordinate_copyLocation), findsOneWidget);
expect(find.text(_l10n.coordinate_openInMaps), findsOneWidget);
Navigator.of(
tester.element(find.text(_l10n.coordinate_copyLocation)),
).pop();
await _settle(tester);
// Tap coordinate -> CoordinateMapScreen fits 320dp without overflow.
await tester.tapAt(findSpanOffset(tester, channelCoord));
await _settle(tester);
expect(find.byType(CoordinateMapScreen), findsOneWidget);
// Verify 48dp touch targets on CoordinateMapScreen controls & AppBar buttons.
for (final iconButton in tester.widgetList<IconButton>(
find.byType(IconButton),
)) {
final box = tester.renderObject<RenderBox>(find.byWidget(iconButton));
expect(box.size.width, greaterThanOrEqualTo(48));
expect(box.size.height, greaterThanOrEqualTo(48));
}
await tester.pageBack();
await _settle(tester);
FlutterError.onError = previousError;
expect(overflows, isEmpty);
}
await _tearDown(tester);
},
);
for (final isDesktop in [false, true]) {
final platformLabel = isDesktop ? 'desktop' : 'phone';
testWidgets('MeshCoreConnector rebuild mid-press preserves coordinate tap, '
'coordinate long-press, and URL tap ($platformLabel)', (tester) async {
PlatformInfo.debugIsDesktopOverride = isDesktop;
addTearDown(() => PlatformInfo.debugIsDesktopOverride = null);
final (connector, providers) = _shared ??= await _connect(tester);
final contact = connector.contacts.firstWhere(
(c) => c.type == advTypeChat,
);
final channel = connector.channels.first;
var nextSecs = DateTime.now().millisecondsSinceEpoch ~/ 1000;
const coord = '40.7128, -74.0060';
const url = 'https://example.com/mid-press';
const messageText = 'Visit $url or $coord now';
await tester.runAsync(() async {
connector.handleFrameForTest(
ReviewFrames.contactMessage(
senderPublicKey: contact.publicKey,
text: messageText,
timestampSecs: nextSecs - 10,
),
);
await Future<void>.delayed(const Duration(milliseconds: 50));
});
await _pumpApp(tester, providers, ChatScreen(contact: contact));
Future<void> triggerConnectorRebuild(String label) async {
nextSecs += 1;
await tester.runAsync(() async {
connector.handleFrameForTest(
ReviewFrames.channelMessage(
channelIndex: channel.index,
sender: 'Relay',
message: 'Rebuild trigger $label',
timestampSecs: nextSecs,
),
);
await Future<void>.delayed(const Duration(milliseconds: 20));
});
await tester.pump();
}
// 1. Coordinate tap survives a connector rebuild between pointer down and up.
final tapCoordGesture = await tester.startGesture(
findSpanOffset(tester, coord),
);
await tester.pump(const Duration(milliseconds: 50));
await triggerConnectorRebuild('coord-tap');
await tapCoordGesture.up();
await _settle(tester);
expect(find.byType(CoordinateMapScreen), findsOneWidget);
expect(find.text(coord), findsOneWidget);
await tester.pageBack();
await _settle(tester);
expect(find.byType(CoordinateMapScreen), findsNothing);
// 2. Coordinate long-press survives a connector rebuild mid-hold.
final longPressGesture = await tester.startGesture(
findSpanOffset(tester, coord),
);
await tester.pump(const Duration(milliseconds: 250));
await triggerConnectorRebuild('coord-long-press');
await tester.pump(const Duration(milliseconds: 350));
await longPressGesture.up();
await _settle(tester);
expect(find.text(_l10n.coordinate_copyLocation), findsOneWidget);
expect(find.text(_l10n.coordinate_openInMaps), findsOneWidget);
Navigator.of(
tester.element(find.text(_l10n.coordinate_copyLocation)),
).pop();
await _settle(tester);
// 3. Ordinary URL tap survives a connector rebuild between pointer down and up.
final urlTapGesture = await tester.startGesture(
findSpanOffset(tester, url),
);
await tester.pump(const Duration(milliseconds: 50));
await triggerConnectorRebuild('url-tap');
await urlTapGesture.up();
await _settle(tester);
expect(find.text(_l10n.chat_openLink), findsOneWidget);
await tester.tap(find.text(_l10n.common_cancel));
await _settle(tester);
await _tearDown(tester);
});
}
testWidgets(
'buildLinkifyText keeps recognizers across style rebuilds and updates on text change',
(tester) async {
PlatformInfo.debugIsDesktopOverride = false;
addTearDown(() => PlatformInfo.debugIsDesktopOverride = null);
final (_, providers) = _shared ??= await _connect(tester);
final stateNotifier = ValueNotifier<({String text, Color color})>((
text: 'Check https://example.com/a and 37.7749, -122.4194',
color: Colors.black,
));
addTearDown(stateNotifier.dispose);
await _pumpApp(
tester,
providers,
Scaffold(
body: Center(
child: ValueListenableBuilder<({String text, Color color})>(
valueListenable: stateNotifier,
builder: (context, value, _) => LinkHandler.buildLinkifyText(
context: context,
text: value.text,
style: TextStyle(fontSize: 14, color: value.color),
),
),
),
),
);
// Rebuild with a new style while holding down on the coordinate.
final gesture = await tester.startGesture(
findSpanOffset(tester, '37.7749, -122.4194'),
);
await tester.pump(const Duration(milliseconds: 50));
stateNotifier.value = (
text: stateNotifier.value.text,
color: Colors.blue,
);
await tester.pump();
await gesture.up();
await _settle(tester);
expect(find.byType(CoordinateMapScreen), findsOneWidget);
expect(find.text('37.7749, -122.4194'), findsOneWidget);
await tester.pageBack();
await _settle(tester);
// Updating text replaces recognizers so tapping the new coordinate opens its pin.
stateNotifier.value = (
text: 'Moved to 48.8566, 2.3522',
color: Colors.blue,
);
await _settle(tester);
await tester.tapAt(findSpanOffset(tester, '48.8566, 2.3522'));
await _settle(tester);
expect(find.byType(CoordinateMapScreen), findsOneWidget);
final flutterMap = tester.widget<FlutterMap>(find.byType(FlutterMap));
expect(flutterMap.options.initialCenter.latitude, closeTo(48.8566, 1e-6));
expect(flutterMap.options.initialCenter.longitude, closeTo(2.3522, 1e-6));
await _tearDown(tester);
},
);
}
Future<void> _pumpApp(
WidgetTester tester,
List<SingleChildWidget> providers,
Widget home, {
ThemeData? theme,
TextScaler textScaler = TextScaler.noScaling,
}) async {
await tester.pumpWidget(
MultiProvider(
providers: providers,
child: MaterialApp(
theme: theme ?? MeshTheme.light(),
locale: const Locale('en'),
localizationsDelegates: const [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: AppLocalizations.supportedLocales,
builder: (context, child) => MediaQuery(
data: MediaQuery.of(context).copyWith(textScaler: textScaler),
child: child!,
),
home: home,
),
),
);
await _settle(tester);
}
Future<void> _settle(WidgetTester tester) async {
for (var i = 0; i < 10; i++) {
await tester.pump(const Duration(milliseconds: 100));
}
}
Future<void> _tearDown(WidgetTester tester) async {
await tester.pumpWidget(const SizedBox());
await tester.pump(const Duration(minutes: 1));
}
Future<(MeshCoreConnector, List<SingleChildWidget>)> _connect(
WidgetTester tester,
) async {
final storage = StorageService();
final connector = MeshCoreConnector();
final retry = MessageRetryService();
final settings = AppSettingsService();
final translation = TranslationService(settings);
await tester.runAsync(() async {
await settings.loadSettings();
connector.initialize(
retryService: retry,
pathHistoryService: PathHistoryService(storage),
appSettingsService: settings,
translationService: translation,
);
connector.reviewRadioFactoryForTest = () => ReviewRadio(
scheduledMessageInterval: const Duration(hours: 1),
ackDelay: const Duration(hours: 1),
replyDelay: const Duration(hours: 1),
);
await connector.connectReview();
final end = DateTime.now().add(const Duration(seconds: 8));
while ((connector.contacts.isEmpty ||
connector.channels.isEmpty ||
!connector.channelMapConfirmed) &&
DateTime.now().isBefore(end)) {
await Future<void>.delayed(const Duration(milliseconds: 25));
}
});
return (
connector,
<SingleChildWidget>[
ChangeNotifierProvider.value(value: connector),
ChangeNotifierProvider.value(value: retry),
ChangeNotifierProvider.value(value: PathHistoryService(storage)),
ChangeNotifierProvider.value(value: settings),
ChangeNotifierProvider.value(value: BleDebugLogService()),
ChangeNotifierProvider.value(value: AppDebugLogService()),
ChangeNotifierProvider.value(value: ChatTextScaleService()),
ChangeNotifierProvider.value(value: translation),
ChangeNotifierProvider.value(value: UiViewStateService()),
Provider.value(value: storage),
ChangeNotifierProvider.value(
value: MapTileCacheService(appSettingsService: settings),
),
ChangeNotifierProvider.value(value: TimeoutPredictionService(storage)),
ChangeNotifierProvider.value(value: ImageCodecService(settings)),
ChangeNotifierProvider.value(value: ReceivedImageStore()),
],
);
}
+619
View File
@@ -0,0 +1,619 @@
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:provider/provider.dart';
import 'package:provider/single_child_widget.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:meshcore_open/connector/meshcore_connector.dart';
import 'package:meshcore_open/connector/meshcore_protocol.dart';
import 'package:meshcore_open/helpers/message_url_image_helper.dart';
import 'package:meshcore_open/l10n/app_localizations.dart';
import 'package:meshcore_open/models/image_codec_support.dart';
import 'package:meshcore_open/review_mode/review_frames.dart';
import 'package:meshcore_open/review_mode/review_radio.dart';
import 'package:meshcore_open/screens/channel_chat_screen.dart';
import 'package:meshcore_open/screens/chat_screen.dart';
import 'package:meshcore_open/services/app_debug_log_service.dart';
import 'package:meshcore_open/services/app_settings_service.dart';
import 'package:meshcore_open/services/ble_debug_log_service.dart';
import 'package:meshcore_open/services/chat_text_scale_service.dart';
import 'package:meshcore_open/services/image_codec_service.dart';
import 'package:meshcore_open/services/map_tile_cache_service.dart';
import 'package:meshcore_open/services/message_retry_service.dart';
import 'package:meshcore_open/services/path_history_service.dart';
import 'package:meshcore_open/services/received_image_store.dart';
import 'package:meshcore_open/services/storage_service.dart';
import 'package:meshcore_open/services/timeout_prediction_service.dart';
import 'package:meshcore_open/services/translation_service.dart';
import 'package:meshcore_open/services/ui_view_state_service.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:meshcore_open/theme/mesh_theme.dart';
import 'package:meshcore_open/widgets/gif_message.dart';
import 'package:meshcore_open/widgets/message_bubble_frame.dart';
import 'package:meshcore_open/widgets/received_image_message.dart';
import 'package:meshcore_open/widgets/shared_contact_card.dart';
final _l10n = lookupAppLocalizations(const Locale('en'));
const _contactShareHex =
'50ba28f599799142622d188469a63f3890d495cdcedd24239052abd364c0283d';
const _contactShareToken = '<$_contactShareHex:1:Bob>';
const _gifToken = 'g:testgif123';
const _markerToken = 'm:45.515232,-122.678385|Camp|poi';
const _urlText = 'Check https://example.com/photo.png';
const _png1x1 =
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==';
(MeshCoreConnector, List<SingleChildWidget>, ReceivedImageStore)? _shared;
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final tempDir = Directory.systemTemp.createTempSync('copy_messages_test');
String? copiedText;
late bool previousLoadLinkImages;
setUpAll(() async {
previousLoadLinkImages = MessageUrlImageHelper.loadLinkImages.value;
MessageUrlImageHelper.loadLinkImages.value = false;
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(
const MethodChannel('plugins.flutter.io/path_provider'),
(call) async => tempDir.path,
);
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(SystemChannels.platform, (call) async {
if (call.method == 'Clipboard.setData') {
copiedText =
(call.arguments as Map<dynamic, dynamic>)['text'] as String?;
}
return null;
});
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
});
tearDownAll(() {
MessageUrlImageHelper.loadLinkImages.value = previousLoadLinkImages;
_shared = null;
if (tempDir.existsSync()) {
tempDir.deleteSync(recursive: true);
}
});
setUp(() {
copiedText = null;
});
/// Scrolls the reversed chat ListView upward toward older items until
/// [target] is built and centered in the viewport.
Future<void> scrollToTarget(WidgetTester tester, Finder target) async {
final scrollable = find.byType(Scrollable).first;
if (target.evaluate().isEmpty) {
await tester.dragUntilVisible(
target,
scrollable,
const Offset(0, 200),
maxIteration: 30,
);
}
await Scrollable.ensureVisible(tester.element(target), alignment: 0.5);
await _settle(tester);
}
/// Opens the message action sheet by long-pressing the bubble padding
/// (outside desktop SelectableLinkify) and taps Copy.
Future<void> copyFromBubbleContaining(
WidgetTester tester,
Finder contentFinder,
) async {
await scrollToTarget(tester, contentFinder);
final bubble = find.ancestor(
of: contentFinder,
matching: find.byType(MessageBubbleFrame),
);
await tester.longPressAt(tester.getTopLeft(bubble) + const Offset(8, 8));
await _settle(tester);
await tester.tap(find.text(_l10n.common_copy));
await _settle(tester);
}
/// Opens the action sheet on a non-text special widget and taps Copy.
Future<void> copyFromWidget(WidgetTester tester, Finder widgetFinder) async {
await scrollToTarget(tester, widgetFinder);
await tester.longPressAt(tester.getCenter(widgetFinder));
await _settle(tester);
await tester.tap(find.text(_l10n.common_copy));
await _settle(tester);
}
group('ChannelChatScreen & ChatScreen copy', () {
testWidgets('copies special channel messages (contact, GIF, location, URL) '
'and image metadata/caption', (tester) async {
final (connector, providers, imageStore) = _shared ??= await _connect(
tester,
);
final channel = connector.channels[2];
final nowSecs = DateTime.now().millisecondsSinceEpoch ~/ 1000;
await tester.runAsync(() async {
await connector.sendChannelMessage(channel, _contactShareToken);
await connector.sendChannelMessage(channel, _gifToken);
await connector.sendChannelMessage(channel, _markerToken);
await connector.sendChannelMessage(channel, _urlText);
connector.handleFrameForTest(
ReviewFrames.channelMessage(
channelIndex: channel.index,
sender: 'Maya',
message: _contactShareToken,
timestampSecs: nowSecs - 40,
),
);
connector.handleFrameForTest(
ReviewFrames.channelMessage(
channelIndex: channel.index,
sender: 'Maya',
message: _gifToken,
timestampSecs: nowSecs - 30,
),
);
connector.handleFrameForTest(
ReviewFrames.channelMessage(
channelIndex: channel.index,
sender: 'Maya',
message: _markerToken,
timestampSecs: nowSecs - 20,
),
);
connector.handleFrameForTest(
ReviewFrames.channelMessage(
channelIndex: channel.index,
sender: 'Maya',
message: _urlText,
timestampSecs: nowSecs - 10,
),
);
await imageStore.registerOutgoing(
channelIndex: channel.index,
channelId: channel.storageId,
senderPrefix: 0x1234,
imgId: 1,
previewPng: Uint8List.fromList(base64Decode(_png1x1)),
rate: AeicRatePoint.ft32,
chunkCount: 2,
synthesized: true,
payloadBytes: 156,
);
await Future<void>.delayed(const Duration(milliseconds: 50));
});
await _pump(tester, providers, ChannelChatScreen(channel: channel));
// Image message (newest, at bottom): long-press -> Copy copies metadata
// + R6 caption.
final imageBubble = find.byType(ReceivedImageMessage);
expect(imageBubble, findsOneWidget);
await copyFromWidget(tester, imageBubble);
expect(copiedText, contains(_l10n.receivedImage_awaiting(156, 2)));
expect(copiedText, contains(_l10n.receivedImage_shareCaption(156)));
// Received special messages
await copyFromBubbleContaining(
tester,
find
.textContaining('https://example.com/photo.png', findRichText: true)
.first,
);
expect(copiedText, _urlText);
await copyFromWidget(tester, find.text(_l10n.chat_poiShared).first);
expect(copiedText, _markerToken);
await copyFromWidget(tester, find.byType(GifMessage).first);
expect(copiedText, _gifToken);
await copyFromWidget(tester, find.byType(SharedContactCard).first);
expect(copiedText, _contactShareToken);
// Sent special messages (further up the transcript)
await copyFromBubbleContaining(
tester,
find
.textContaining('https://example.com/photo.png', findRichText: true)
.last,
);
expect(copiedText, _urlText);
await copyFromWidget(tester, find.text(_l10n.chat_poiShared).last);
expect(copiedText, _markerToken);
await copyFromWidget(tester, find.byType(GifMessage).last);
expect(copiedText, _gifToken);
await copyFromWidget(tester, find.byType(SharedContactCard).last);
expect(copiedText, _contactShareToken);
// Verify image action sheet fits 320dp at 1.3x and 2.0x text scale.
for (final scale in [1.3, 2.0]) {
tester.view.physicalSize = const Size(320, 568);
tester.view.devicePixelRatio = 1.0;
await tester.pumpWidget(
MediaQuery(
data: MediaQueryData(
size: const Size(320, 568),
textScaler: TextScaler.linear(scale),
),
child: MultiProvider(
providers: providers,
child: MaterialApp(
theme: MeshTheme.light(),
locale: const Locale('en'),
localizationsDelegates: const [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: AppLocalizations.supportedLocales,
home: ChannelChatScreen(channel: channel),
),
),
),
);
await _settle(tester);
await scrollToTarget(tester, find.byType(ReceivedImageMessage));
await tester.longPress(find.byType(ReceivedImageMessage));
await _settle(tester);
expect(find.text(_l10n.common_copy), findsOneWidget);
expect(tester.takeException(), isNull);
Navigator.of(tester.element(find.text(_l10n.common_copy))).pop();
await _settle(tester);
}
tester.view.resetPhysicalSize();
tester.view.resetDevicePixelRatio();
await _tearDown(tester);
});
testWidgets('copies regular, @[username], and special DM messages '
'(sent and received)', (tester) async {
final (connector, providers, _) = _shared ??= await _connect(tester);
final contact = connector.contacts.firstWhere(
(c) => c.type == advTypeChat,
);
final nowSecs = DateTime.now().millisecondsSinceEpoch ~/ 1000;
await tester.runAsync(() async {
await connector.sendMessage(contact, '@[Maya] DM mention sent');
await connector.sendMessage(contact, _contactShareToken);
await connector.sendMessage(contact, _gifToken);
await connector.sendMessage(contact, _markerToken);
await connector.sendMessage(contact, _urlText);
connector.handleFrameForTest(
ReviewFrames.contactMessage(
senderPublicKey: contact.publicKey,
text: 'Regular DM received',
timestampSecs: nowSecs - 50,
),
);
connector.handleFrameForTest(
ReviewFrames.contactMessage(
senderPublicKey: contact.publicKey,
text: '@[Review Radio] DM mention received',
timestampSecs: nowSecs - 40,
),
);
connector.handleFrameForTest(
ReviewFrames.contactMessage(
senderPublicKey: contact.publicKey,
text: _contactShareToken,
timestampSecs: nowSecs - 30,
),
);
connector.handleFrameForTest(
ReviewFrames.contactMessage(
senderPublicKey: contact.publicKey,
text: _gifToken,
timestampSecs: nowSecs - 20,
),
);
connector.handleFrameForTest(
ReviewFrames.contactMessage(
senderPublicKey: contact.publicKey,
text: _markerToken,
timestampSecs: nowSecs - 10,
),
);
connector.handleFrameForTest(
ReviewFrames.contactMessage(
senderPublicKey: contact.publicKey,
text: _urlText,
timestampSecs: nowSecs - 5,
),
);
await Future<void>.delayed(const Duration(milliseconds: 50));
});
await _pump(tester, providers, ChatScreen(contact: contact));
await copyFromBubbleContaining(
tester,
find
.textContaining('https://example.com/photo.png', findRichText: true)
.first,
);
expect(copiedText, _urlText);
await copyFromWidget(tester, find.text(_l10n.chat_poiShared).first);
expect(copiedText, _markerToken);
await copyFromWidget(tester, find.byType(GifMessage).first);
expect(copiedText, _gifToken);
await copyFromWidget(tester, find.byType(SharedContactCard).first);
expect(copiedText, _contactShareToken);
await copyFromBubbleContaining(
tester,
find.textContaining('DM mention received', findRichText: true),
);
expect(copiedText, '@[Review Radio] DM mention received');
await copyFromBubbleContaining(
tester,
find.textContaining('Regular DM received', findRichText: true),
);
expect(copiedText, 'Regular DM received');
await copyFromBubbleContaining(
tester,
find
.textContaining('https://example.com/photo.png', findRichText: true)
.last,
);
expect(copiedText, _urlText);
await copyFromWidget(tester, find.text(_l10n.chat_poiShared).last);
expect(copiedText, _markerToken);
await copyFromWidget(tester, find.byType(GifMessage).last);
expect(copiedText, _gifToken);
await copyFromWidget(tester, find.byType(SharedContactCard).last);
expect(copiedText, _contactShareToken);
await copyFromBubbleContaining(
tester,
find.textContaining('DM mention sent', findRichText: true),
);
expect(copiedText, '@[Maya] DM mention sent');
await _tearDown(tester);
});
testWidgets('copies sent and received channel replies with @[username] '
'and leaves regular messages unchanged', (tester) async {
final (connector, providers, _) = _shared ??= await _connect(tester);
final channel = connector.channels[1];
final nowSecs = DateTime.now().millisecondsSinceEpoch ~/ 1000;
await tester.runAsync(() async {
await connector.sendChannelMessage(channel, 'Plain outgoing');
connector.handleFrameForTest(
ReviewFrames.channelMessage(
channelIndex: channel.index,
sender: 'Maya',
message: 'Regular channel hello',
timestampSecs: nowSecs - 40,
),
);
connector.handleFrameForTest(
ReviewFrames.channelMessage(
channelIndex: channel.index,
sender: 'Jordan',
message: '@[Maya] Matched channel reply',
timestampSecs: nowSecs - 30,
),
);
connector.handleFrameForTest(
ReviewFrames.channelMessage(
channelIndex: channel.index,
sender: 'Sam',
message: '@[GhostNode] Unmatched channel reply',
timestampSecs: nowSecs - 20,
),
);
connector.handleFrameForTest(
ReviewFrames.channelMessage(
channelIndex: channel.index,
sender: 'Ranger Pat',
message: 'Reply target message',
timestampSecs: nowSecs - 10,
),
);
await Future<void>.delayed(const Duration(milliseconds: 50));
});
await _pump(tester, providers, ChannelChatScreen(channel: channel));
// Reply to Ranger Pat's message via UI composer and send.
final replyTargetText = find.textContaining(
'Reply target message',
findRichText: true,
);
await scrollToTarget(tester, replyTargetText);
final targetBubble = find.ancestor(
of: replyTargetText,
matching: find.byType(MessageBubbleFrame),
);
await tester.longPressAt(
tester.getTopLeft(targetBubble) + const Offset(8, 8),
);
await _settle(tester);
await tester.tap(find.text(_l10n.chat_reply));
await _settle(tester);
await tester.enterText(find.byType(TextField), 'Sent reply body');
await _settle(tester);
await tester.tap(find.byTooltip(_l10n.chat_sendMessage));
await _settle(tester);
// 1. Sent reply includes @[Ranger Pat].
await copyFromBubbleContaining(
tester,
find.textContaining('Sent reply body', findRichText: true),
);
expect(copiedText, '@[Ranger Pat] Sent reply body');
// 2. Bulk copy on the sent reply also includes @[Ranger Pat].
final sentReplyBubble = find.ancestor(
of: find.textContaining('Sent reply body', findRichText: true),
matching: find.byType(MessageBubbleFrame),
);
await tester.longPressAt(
tester.getTopLeft(sentReplyBubble) + const Offset(8, 8),
);
await _settle(tester);
await tester.tap(find.text(_l10n.chat_selectMessages));
await _settle(tester);
await tester.tap(find.byIcon(Icons.more_vert));
await _settle(tester);
await tester.tap(find.text(_l10n.common_copy));
await _settle(tester);
expect(copiedText, '@[Ranger Pat] Sent reply body');
// 3. Received unmatched reply includes @[GhostNode].
await copyFromBubbleContaining(
tester,
find.textContaining('Unmatched channel reply', findRichText: true),
);
expect(copiedText, '@[GhostNode] Unmatched channel reply');
// 4. Received matched reply includes @[Maya].
await copyFromBubbleContaining(
tester,
find.textContaining('Matched channel reply', findRichText: true),
);
expect(copiedText, '@[Maya] Matched channel reply');
// 5. Regular incoming message unchanged.
await copyFromBubbleContaining(
tester,
find.textContaining('Regular channel hello', findRichText: true).last,
);
expect(copiedText, 'Regular channel hello');
// 6. Regular outgoing message unchanged.
await copyFromBubbleContaining(
tester,
find.textContaining('Plain outgoing', findRichText: true),
);
expect(copiedText, 'Plain outgoing');
await _tearDown(tester);
});
});
}
Future<void> _pump(
WidgetTester tester,
List<SingleChildWidget> providers,
Widget home,
) async {
await tester.pumpWidget(
MultiProvider(
providers: providers,
child: MaterialApp(
theme: MeshTheme.light(),
locale: const Locale('en'),
localizationsDelegates: const [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: AppLocalizations.supportedLocales,
home: home,
),
),
);
await _settle(tester);
}
Future<void> _settle(WidgetTester tester) async {
for (var i = 0; i < 10; i++) {
await tester.pump(const Duration(milliseconds: 100));
}
}
Future<void> _tearDown(WidgetTester tester) async {
await tester.pumpWidget(const SizedBox());
await tester.pump(const Duration(hours: 2));
}
Future<(MeshCoreConnector, List<SingleChildWidget>, ReceivedImageStore)>
_connect(WidgetTester tester) async {
final storage = StorageService();
final connector = MeshCoreConnector();
final retry = MessageRetryService();
final settings = AppSettingsService();
final translation = TranslationService(settings);
final imageStore = ReceivedImageStore();
await tester.runAsync(() async {
await settings.loadSettings();
connector.initialize(
retryService: retry,
pathHistoryService: PathHistoryService(storage),
appSettingsService: settings,
translationService: translation,
);
connector.reviewRadioFactoryForTest = () => ReviewRadio(
scheduledMessageInterval: const Duration(hours: 1),
ackDelay: const Duration(milliseconds: 50),
replyDelay: const Duration(hours: 1),
);
await connector.connectReview();
final end = DateTime.now().add(const Duration(seconds: 8));
while ((connector.contacts.isEmpty ||
connector.channels.isEmpty ||
!connector.channelMapConfirmed) &&
DateTime.now().isBefore(end)) {
await Future<void>.delayed(const Duration(milliseconds: 25));
}
});
expect(connector.channels, isNotEmpty);
return (
connector,
<SingleChildWidget>[
ChangeNotifierProvider.value(value: connector),
ChangeNotifierProvider.value(value: retry),
ChangeNotifierProvider.value(value: PathHistoryService(storage)),
ChangeNotifierProvider.value(value: settings),
ChangeNotifierProvider.value(value: BleDebugLogService()),
ChangeNotifierProvider.value(value: AppDebugLogService()),
ChangeNotifierProvider.value(value: ChatTextScaleService()),
ChangeNotifierProvider.value(value: translation),
ChangeNotifierProvider.value(value: UiViewStateService()),
Provider.value(value: storage),
ChangeNotifierProvider.value(
value: MapTileCacheService(appSettingsService: settings),
),
ChangeNotifierProvider.value(value: TimeoutPredictionService(storage)),
ChangeNotifierProvider.value(value: ImageCodecService(settings)),
ChangeNotifierProvider.value(value: imageStore),
],
imageStore,
);
}
+356
View File
@@ -0,0 +1,356 @@
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:meshcore_open/connector/meshcore_connector.dart';
import 'package:meshcore_open/connector/meshcore_protocol.dart';
import 'package:meshcore_open/l10n/app_localizations.dart';
import 'package:meshcore_open/models/channel.dart';
import 'package:meshcore_open/models/channel_message.dart';
import 'package:meshcore_open/models/contact.dart';
import 'package:meshcore_open/screens/channels_screen.dart';
import 'package:meshcore_open/screens/contacts_screen.dart';
import 'package:meshcore_open/services/app_settings_service.dart';
import 'package:meshcore_open/services/ui_view_state_service.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:meshcore_open/theme/mesh_theme.dart';
import 'package:meshcore_open/widgets/mesh_ui.dart';
/// Repeatable stand-in for profiling rapid scrolling on a phone: builds the
/// contacts list with 500 contacts and the channels list with 40 channels,
/// flings each list, and counts widget builds and rows that are not fully
/// drawn while scrolling. Run with `flutter test
/// test/screens/list_scroll_perf_test.dart` and read the printed lines.
/// See documentation/performance-profiling.md for the on-device check.
const _contactCount = 500;
const _channelCount = 40;
class _Connector extends MeshCoreConnector {
List<Contact> nodes = [];
List<Channel> slots = [];
final Map<String, int> unread = {};
final Map<int, ChannelMessage> latest = {};
@override
List<Contact> get contacts => List.unmodifiable(nodes);
@override
List<Channel> get channels => List.unmodifiable(slots);
@override
int getUnreadCountForContact(Contact contact) =>
unread[contact.publicKeyHex] ?? 0;
@override
int getUnreadCountForChannel(Channel channel) => channel.unreadCount;
@override
ChannelMessage? latestVisibleChannelMessage(Channel channel) =>
latest[channel.index];
@override
Future<void> getChannels({int? maxChannels, bool force = false}) async {}
}
Contact _contact(int i, DateTime now) {
final key = Uint8List(32)
..[0] = i >> 8
..[1] = i & 0xff
..[2] = 0x5a;
final type = i % 10 == 0
? advTypeRepeater
: i % 25 == 0
? advTypeRoom
: advTypeChat;
return Contact(
publicKey: key,
name: 'Node ${i.toString().padLeft(3, '0')}',
type: type,
pathLength: i % 4,
path: Uint8List.fromList(List.filled(i % 4, i & 0xff)),
latitude: i.isEven ? 35.0 : null,
longitude: i.isEven ? -112.0 : null,
lastSeen: now.subtract(Duration(minutes: i * 7)),
);
}
/// Counts element builds per widget type, via the framework's debug hook.
class _BuildCounter {
final Map<String, int> counts = {};
void start() {
counts.clear();
debugOnRebuildDirtyWidget = (element, _) {
final name = element.widget.runtimeType.toString();
counts[name] = (counts[name] ?? 0) + 1;
};
}
void stop() => debugOnRebuildDirtyWidget = null;
int operator [](String type) => counts[type] ?? 0;
int get total => counts.values.fold(0, (a, b) => a + b);
}
/// Rows inside the visible list area whose entrance fade has not finished:
/// they are blank or partly transparent while the user scrolls.
int _rowsNotFullyDrawn(WidgetTester tester, Rect viewport) {
final fades = find.descendant(
of: find.byType(ListEntrance),
matching: find.byType(FadeTransition),
);
var count = 0;
for (final element in fades.evaluate()) {
final fade = element.widget as FadeTransition;
final box = element.renderObject as RenderBox?;
if (box == null || !box.attached || !box.hasSize) continue;
final rect = box.localToGlobal(Offset.zero) & box.size;
if (!rect.overlaps(viewport)) continue;
if (fade.opacity.value < 1) count++;
}
return count;
}
class _ScrollResult {
int frames = 0;
int notFullyDrawnRowFrames = 0;
int maxNotFullyDrawn = 0;
int notFullyDrawnAfterStop = 0;
}
/// Flings [list] like a rapid swipe and pumps 60 Hz frames until the list
/// stops, firing a connector notify partway through.
Future<_ScrollResult> _fling(
WidgetTester tester,
Finder list,
_Connector connector, {
required Offset offset,
}) async {
final viewport = tester.getRect(list);
final position = tester.state<ScrollableState>(
find.descendant(of: list, matching: find.byType(Scrollable)).first,
);
final result = _ScrollResult();
await tester.fling(list, offset, 6000);
for (var i = 0; i < 400; i++) {
if (i == 10) connector.notifyListeners();
await tester.pump(const Duration(milliseconds: 16));
result.frames++;
final hidden = _rowsNotFullyDrawn(tester, viewport);
result.notFullyDrawnRowFrames += hidden;
if (hidden > result.maxNotFullyDrawn) result.maxNotFullyDrawn = hidden;
if (i > 12 && !position.position.isScrollingNotifier.value) break;
}
result.notFullyDrawnAfterStop = _rowsNotFullyDrawn(tester, viewport);
return result;
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late _Connector connector;
late AppSettingsService settings;
late UiViewStateService viewState;
final counter = _BuildCounter();
setUp(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
connector = _Connector();
settings = AppSettingsService();
viewState = UiViewStateService();
});
tearDown(() {
counter.stop();
connector.dispose();
settings.dispose();
viewState.dispose();
});
/// Opens [home] and returns how many rows played the entrance animation.
Future<int> open(WidgetTester tester, Widget home) async {
tester.view.physicalSize = const Size(1080, 2340);
tester.view.devicePixelRatio = 3;
addTearDown(tester.view.reset);
await tester.pumpWidget(
MultiProvider(
providers: [
ChangeNotifierProvider<MeshCoreConnector>.value(value: connector),
ChangeNotifierProvider.value(value: settings),
ChangeNotifierProvider.value(value: viewState),
],
child: MaterialApp(
theme: MeshTheme.light(),
locale: const Locale('en'),
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: home,
),
),
);
await tester.pump();
final animatedRows = find
.descendant(
of: find.byType(ListEntrance),
matching: find.byType(FadeTransition),
)
.evaluate()
.length;
// Let the first screen's entrance animations finish.
for (var i = 0; i < 40; i++) {
await tester.pump(const Duration(milliseconds: 16));
}
return animatedRows;
}
Future<void> notifyAndSettle(WidgetTester tester) async {
connector.notifyListeners();
await tester.pump(const Duration(milliseconds: 60));
await tester.pump();
}
Future<void> close(WidgetTester tester) async {
counter.stop();
await tester.pumpWidget(const SizedBox.shrink());
// Drain entrance-delay timers.
await tester.pump(const Duration(seconds: 1));
}
testWidgets('contacts list: rapid fling with 500 contacts', (tester) async {
final now = DateTime.now();
connector.nodes = [
for (var i = 0; i < _contactCount; i++) _contact(i, now),
];
for (var i = 1; i < _contactCount; i += 9) {
connector.unread[connector.nodes[i].publicKeyHex] = i % 5 + 1;
}
final animatedRows = await open(tester, const ContactsScreen());
final list = find.byType(ListView);
expect(list, findsOneWidget);
counter.start();
final down = await _fling(
tester,
list,
connector,
offset: const Offset(0, -2500),
);
final flingBuilds = Map.of(counter.counts);
final flingTotal = counter.total;
counter.start();
await notifyAndSettle(tester);
final notifyTiles = counter['_ContactTile'];
final notifyTotal = counter.total;
// A live change still reaches the visible tile.
final visible = tester
.widgetList(
find.byWidgetPredicate(
(w) => w.runtimeType.toString() == '_ContactTile',
),
)
.map((w) => (w as dynamic).contact as Contact)
.toList();
final target = visible[visible.length ~/ 2];
connector.unread[target.publicKeyHex] = 42;
counter.start();
await notifyAndSettle(tester);
final changeTiles = counter['_ContactTile'];
expect(find.text('42'), findsOneWidget);
// So does a replaced contact.
final renamedAt = connector.nodes.indexOf(visible.first);
connector.nodes = List.of(connector.nodes)
..[renamedAt] = visible.first.copyWith(name: 'Renamed node');
await notifyAndSettle(tester);
expect(find.text('Renamed node'), findsOneWidget);
// ignore: avoid_print
print(
'[list-perf] contacts fling: frames=${down.frames} '
'itemBuilds=${flingBuilds['_ContactTileEntrance'] ?? 0} '
'tileBuilds=${flingBuilds['_ContactTile'] ?? 0} '
'entranceBuilds=${flingBuilds['ListEntrance'] ?? 0} '
'allBuilds=$flingTotal '
'rowFramesNotFullyDrawn=${down.notFullyDrawnRowFrames} '
'maxRowsNotFullyDrawn=${down.maxNotFullyDrawn} '
'rowsNotFullyDrawnAtStop=${down.notFullyDrawnAfterStop}\n'
'[list-perf] contacts notify (no change): tileBuilds=$notifyTiles '
'allBuilds=$notifyTotal; one unread change: tileBuilds=$changeTiles',
);
// The first screen still animates in; rows a fling brings in do not.
expect(animatedRows, greaterThan(0));
expect(down.notFullyDrawnRowFrames, 0);
// A notify that changes nothing rebuilds no rows; a change rebuilds one.
expect(notifyTiles, 0);
expect(changeTiles, 1);
await close(tester);
});
testWidgets('channels list: rapid fling with 40 channels', (tester) async {
final now = DateTime.now();
connector.slots = [
for (var i = 0; i < _channelCount; i++)
Channel(
index: i,
name: i == 0 ? 'Public' : '#topic-$i',
psk: Uint8List.fromList(List.filled(16, i + 1)),
unreadCount: i % 3 == 0 ? i : 0,
),
];
for (var i = 0; i < _channelCount; i++) {
connector.latest[i] = ChannelMessage(
senderName: 'Sender $i',
text: 'Message preview number $i on the mesh',
timestamp: now.subtract(Duration(minutes: i * 13)),
isOutgoing: false,
status: ChannelMessageStatus.sent,
channelIndex: i,
);
}
viewState.setChannelsSortOption(ChannelSortOption.name);
final animatedRows = await open(tester, const ChannelsScreen());
final list = find.byType(ListView);
expect(list, findsOneWidget);
counter.start();
final down = await _fling(
tester,
list,
connector,
offset: const Offset(0, -2500),
);
final flingBuilds = Map.of(counter.counts);
final flingTotal = counter.total;
counter.start();
await notifyAndSettle(tester);
final notifyTiles = counter['MeshCard'];
// ignore: avoid_print
print(
'[list-perf] channels fling: frames=${down.frames} '
'itemBuilds=${flingBuilds['ListEntrance'] ?? 0} '
'cardBuilds=${flingBuilds['MeshCard'] ?? 0} '
'allBuilds=$flingTotal '
'rowFramesNotFullyDrawn=${down.notFullyDrawnRowFrames} '
'maxRowsNotFullyDrawn=${down.maxNotFullyDrawn} '
'rowsNotFullyDrawnAtStop=${down.notFullyDrawnAfterStop}\n'
'[list-perf] channels notify (no change): cardBuilds=$notifyTiles',
);
expect(animatedRows, greaterThan(0));
expect(down.notFullyDrawnRowFrames, 0);
await close(tester);
});
}
+545
View File
@@ -0,0 +1,545 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:meshcore_open/connector/meshcore_connector.dart';
import 'package:meshcore_open/l10n/app_localizations.dart';
import 'package:meshcore_open/review_mode/review_radio.dart';
import 'package:meshcore_open/screens/channels_screen.dart';
import 'package:meshcore_open/screens/contacts_screen.dart';
import 'package:meshcore_open/screens/map_screen.dart';
import 'package:meshcore_open/screens/settings_screen.dart';
import 'package:meshcore_open/services/app_debug_log_service.dart';
import 'package:meshcore_open/services/app_settings_service.dart';
import 'package:meshcore_open/services/ble_debug_log_service.dart';
import 'package:meshcore_open/services/chat_text_scale_service.dart';
import 'package:meshcore_open/services/image_codec_service.dart';
import 'package:meshcore_open/services/map_tile_cache_service.dart';
import 'package:meshcore_open/services/message_retry_service.dart';
import 'package:meshcore_open/services/network_map/network_map_upload_service.dart';
import 'package:meshcore_open/services/path_history_service.dart';
import 'package:meshcore_open/services/received_image_store.dart';
import 'package:meshcore_open/services/storage_service.dart';
import 'package:meshcore_open/services/timeout_prediction_service.dart';
import 'package:meshcore_open/services/translation_service.dart';
import 'package:meshcore_open/services/ui_view_state_service.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:meshcore_open/theme/mesh_theme.dart';
import 'package:meshcore_open/widgets/connect_sheet.dart';
final _l10n = lookupAppLocalizations(const Locale('en'));
class _TestEnv {
final MeshCoreConnector connector;
final UiViewStateService viewState;
final Widget Function(Widget home, {double textScale}) wrap;
_TestEnv({
required this.connector,
required this.viewState,
required this.wrap,
});
}
_TestEnv? _sharedConnected;
Future<_TestEnv> _createConnectedEnv(WidgetTester tester) async {
if (_sharedConnected != null) {
_sharedConnected!.viewState.mapPathTrace.active = false;
return _sharedConnected!;
}
final storage = StorageService();
final connector = MeshCoreConnector();
final retry = MessageRetryService();
final settings = AppSettingsService();
final translation = TranslationService(settings);
final viewState = UiViewStateService();
await tester.runAsync(() async {
await settings.loadSettings();
connector.initialize(
retryService: retry,
pathHistoryService: PathHistoryService(storage),
appSettingsService: settings,
translationService: translation,
);
connector.reviewRadioFactoryForTest = () => ReviewRadio(
scheduledMessageInterval: const Duration(hours: 1),
ackDelay: const Duration(hours: 1),
replyDelay: const Duration(hours: 1),
);
await connector.connectReview();
final end = DateTime.now().add(const Duration(seconds: 8));
while ((connector.contacts.isEmpty || connector.channels.isEmpty) &&
DateTime.now().isBefore(end)) {
await Future<void>.delayed(const Duration(milliseconds: 25));
}
});
final providers = [
ChangeNotifierProvider.value(value: connector),
ChangeNotifierProvider.value(value: retry),
ChangeNotifierProvider.value(value: PathHistoryService(storage)),
ChangeNotifierProvider.value(value: settings),
ChangeNotifierProvider.value(value: BleDebugLogService()),
ChangeNotifierProvider.value(value: AppDebugLogService()),
ChangeNotifierProvider.value(value: ChatTextScaleService()),
ChangeNotifierProvider.value(value: translation),
ChangeNotifierProvider.value(value: viewState),
Provider.value(value: storage),
ChangeNotifierProvider.value(
value: MapTileCacheService(appSettingsService: settings),
),
ChangeNotifierProvider.value(value: TimeoutPredictionService(storage)),
ChangeNotifierProvider.value(value: ImageCodecService(settings)),
ChangeNotifierProvider.value(value: ReceivedImageStore()),
ChangeNotifierProvider.value(
value: NetworkMapUploadService(connector: connector, settings: settings),
),
];
Widget wrap(Widget home, {double textScale = 1.0}) {
return MultiProvider(
providers: providers,
child: MaterialApp(
theme: MeshTheme.light(),
locale: const Locale('en'),
localizationsDelegates: const [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: AppLocalizations.supportedLocales,
builder: (context, child) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(textScaler: TextScaler.linear(textScale)),
child: child!,
),
home: home,
),
);
}
return _sharedConnected = _TestEnv(
connector: connector,
viewState: viewState,
wrap: wrap,
);
}
Future<_TestEnv> _createEnv(
WidgetTester tester, {
required bool connected,
}) async {
final shared = await _createConnectedEnv(tester);
if (connected) return shared;
final offlineConnector = MeshCoreConnector();
addTearDown(offlineConnector.dispose);
final storage = StorageService();
final settings = AppSettingsService();
await tester.runAsync(settings.loadSettings);
final viewState = UiViewStateService();
final offlineProviders = [
ChangeNotifierProvider.value(value: offlineConnector),
ChangeNotifierProvider.value(value: MessageRetryService()),
ChangeNotifierProvider.value(value: PathHistoryService(storage)),
ChangeNotifierProvider.value(value: settings),
ChangeNotifierProvider.value(value: BleDebugLogService()),
ChangeNotifierProvider.value(value: AppDebugLogService()),
ChangeNotifierProvider.value(value: ChatTextScaleService()),
ChangeNotifierProvider.value(value: TranslationService(settings)),
ChangeNotifierProvider.value(value: viewState),
Provider.value(value: storage),
ChangeNotifierProvider.value(
value: MapTileCacheService(appSettingsService: settings),
),
ChangeNotifierProvider.value(value: TimeoutPredictionService(storage)),
ChangeNotifierProvider.value(value: ImageCodecService(settings)),
ChangeNotifierProvider.value(value: ReceivedImageStore()),
ChangeNotifierProvider.value(
value: NetworkMapUploadService(
connector: offlineConnector,
settings: settings,
),
),
];
Widget wrap(Widget home, {double textScale = 1.0}) {
return MultiProvider(
providers: offlineProviders,
child: MaterialApp(
theme: MeshTheme.light(),
locale: const Locale('en'),
localizationsDelegates: const [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: AppLocalizations.supportedLocales,
builder: (context, child) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(textScaler: TextScaler.linear(textScale)),
child: child!,
),
home: home,
),
);
}
return _TestEnv(
connector: offlineConnector,
viewState: viewState,
wrap: wrap,
);
}
Future<void> _pumpSettleFrames(WidgetTester tester) async {
for (var i = 0; i < 10; i++) {
await tester.pump(const Duration(milliseconds: 100));
}
}
/// Returns the rendered entries of an open [PopupMenuButton] in top-to-bottom
/// visual order: label strings for [PopupMenuItem]s and `'---'` for
/// [PopupMenuDivider]s.
List<String> _openMenuEntries(WidgetTester tester) {
final entries = <({double dy, String label})>[];
for (final element in find.byType(PopupMenuDivider).evaluate()) {
final box = element.renderObject! as RenderBox;
final dy = box.localToGlobal(Offset.zero).dy;
entries.add((dy: dy, label: '---'));
}
for (final element
in find.byWidgetPredicate((w) => w is PopupMenuItem).evaluate()) {
final box = element.renderObject! as RenderBox;
final dy = box.localToGlobal(Offset.zero).dy;
final text = tester.widget<Text>(
find.descendant(
of: find.byWidget(element.widget),
matching: find.byType(Text),
),
);
entries.add((dy: dy, label: text.data!));
}
entries.sort((a, b) => a.dy.compareTo(b.dy));
return entries.map((e) => e.label).toList();
}
PopupMenuItem<Object?> _menuItemByLabel(String label) {
return find
.ancestor(
of: find.text(label),
matching: find.byWidgetPredicate((w) => w is PopupMenuItem),
)
.evaluate()
.single
.widget
as PopupMenuItem<Object?>;
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final tempDir = Directory.systemTemp.createTempSync(
'main_overflow_menus_test',
);
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(
const MethodChannel('plugins.flutter.io/path_provider'),
(call) async => tempDir.path,
);
setUp(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
});
group('mainOverflowTrailingItems helper', () {
testWidgets('includes leading divider when hasPrecedingItems is true', (
tester,
) async {
final env = await _createEnv(tester, connected: false);
late List<PopupMenuEntry<dynamic>> entries;
await tester.pumpWidget(
env.wrap(
Builder(
builder: (context) => PopupMenuButton<dynamic>(
itemBuilder: (menuContext) {
entries = mainOverflowTrailingItems(
context,
menuContext,
hasPrecedingItems: true,
);
return entries;
},
),
),
),
);
await tester.tap(find.byType(PopupMenuButton<dynamic>));
await _pumpSettleFrames(tester);
expect(entries, hasLength(3));
expect(entries[0], isA<PopupMenuDivider>());
expect(_openMenuEntries(tester), [
'---',
_l10n.common_connect,
_l10n.settings_title,
]);
await tester.pumpWidget(const SizedBox());
});
testWidgets('omits leading divider when hasPrecedingItems is false', (
tester,
) async {
final env = await _createEnv(tester, connected: true);
late List<PopupMenuEntry<dynamic>> entries;
await tester.pumpWidget(
env.wrap(
Builder(
builder: (context) => PopupMenuButton<dynamic>(
itemBuilder: (menuContext) {
entries = mainOverflowTrailingItems(
context,
menuContext,
hasPrecedingItems: false,
);
return entries;
},
),
),
),
);
await tester.tap(find.byType(PopupMenuButton<dynamic>));
await _pumpSettleFrames(tester);
expect(entries, hasLength(2));
expect(entries[0], isNot(isA<PopupMenuDivider>()));
expect(_openMenuEntries(tester), [
_l10n.common_disconnect,
_l10n.settings_title,
]);
// Tapping Settings uses the screen context safely after the menu pops.
await tester.tap(find.text(_l10n.settings_title));
await _pumpSettleFrames(tester);
expect(find.byType(SettingsScreen), findsOneWidget);
await tester.pumpWidget(const SizedBox());
await tester.pump(const Duration(minutes: 1));
});
});
group('Main screen overflow menus order and state', () {
for (final connected in [true, false]) {
final stateLabel = connected ? 'connected' : 'disconnected';
final connectionLabel = connected
? _l10n.common_disconnect
: _l10n.common_connect;
testWidgets('Contacts overflow menu ($stateLabel)', (tester) async {
final env = await _createEnv(tester, connected: connected);
await tester.pumpWidget(env.wrap(const ContactsScreen()));
await _pumpSettleFrames(tester);
final button = tester.widget<PopupMenuButton<dynamic>>(
find.descendant(
of: find.byType(AppBar),
matching: find.byWidgetPredicate((w) => w is PopupMenuButton),
),
);
expect(button.tooltip, _l10n.contacts_moreOptions);
await tester.tap(find.byIcon(Icons.more_vert));
await _pumpSettleFrames(tester);
expect(_openMenuEntries(tester), [
_l10n.addContact_title,
_l10n.discoveredContacts_Title,
'---',
_l10n.contacts_zeroHopAdvert,
_l10n.contacts_floodAdvert,
_l10n.contacts_copyAdvertToClipboard,
_l10n.manualTrace_menuItem,
'---',
connectionLabel,
_l10n.settings_title,
]);
expect(_menuItemByLabel(_l10n.addContact_title).enabled, connected);
expect(
_menuItemByLabel(_l10n.discoveredContacts_Title).enabled,
isTrue,
);
expect(
_menuItemByLabel(_l10n.contacts_zeroHopAdvert).enabled,
connected,
);
expect(_menuItemByLabel(_l10n.contacts_floodAdvert).enabled, connected);
expect(
_menuItemByLabel(_l10n.contacts_copyAdvertToClipboard).enabled,
connected,
);
expect(_menuItemByLabel(_l10n.manualTrace_menuItem).enabled, connected);
expect(_menuItemByLabel(connectionLabel).enabled, isTrue);
expect(_menuItemByLabel(_l10n.settings_title).enabled, isTrue);
await tester.pumpWidget(const SizedBox());
await tester.pump(const Duration(minutes: 1));
});
testWidgets('Channels overflow menu ($stateLabel)', (tester) async {
final env = await _createEnv(tester, connected: connected);
await tester.pumpWidget(env.wrap(const ChannelsScreen()));
await _pumpSettleFrames(tester);
final button = tester.widget<PopupMenuButton<dynamic>>(
find.descendant(
of: find.byType(AppBar),
matching: find.byWidgetPredicate((w) => w is PopupMenuButton),
),
);
expect(button.tooltip, _l10n.contacts_moreOptions);
await tester.tap(find.byIcon(Icons.more_vert));
await _pumpSettleFrames(tester);
expect(_openMenuEntries(tester), [
_l10n.bookmarks_title,
_l10n.community_manageCommunities,
'---',
connectionLabel,
_l10n.settings_title,
]);
expect(_menuItemByLabel(_l10n.bookmarks_title).enabled, isTrue);
expect(
_menuItemByLabel(_l10n.community_manageCommunities).enabled,
isTrue,
);
expect(_menuItemByLabel(connectionLabel).enabled, isTrue);
expect(_menuItemByLabel(_l10n.settings_title).enabled, isTrue);
await tester.pumpWidget(const SizedBox());
await tester.pump(const Duration(minutes: 1));
});
testWidgets('Map overflow menu ($stateLabel)', (tester) async {
final env = await _createEnv(tester, connected: connected);
await tester.pumpWidget(env.wrap(const MapScreen()));
await _pumpSettleFrames(tester);
final button = tester.widget<PopupMenuButton<dynamic>>(
find.descendant(
of: find.byType(AppBar),
matching: find.byWidgetPredicate((w) => w is PopupMenuButton),
),
);
expect(button.tooltip, _l10n.contacts_moreOptions);
await tester.tap(find.byIcon(Icons.more_vert));
await _pumpSettleFrames(tester);
final hasSelfLocation =
env.connector.selfLatitude != null &&
env.connector.selfLongitude != null;
expect(_openMenuEntries(tester), [
if (hasSelfLocation) _l10n.contacts_pathTrace,
_l10n.manualTrace_menuItem,
_l10n.map_lineOfSight,
'---',
connectionLabel,
_l10n.settings_title,
]);
expect(_menuItemByLabel(_l10n.manualTrace_menuItem).enabled, connected);
expect(_menuItemByLabel(_l10n.map_lineOfSight).enabled, isTrue);
expect(_menuItemByLabel(connectionLabel).enabled, isTrue);
expect(_menuItemByLabel(_l10n.settings_title).enabled, isTrue);
await tester.pumpWidget(const SizedBox());
await tester.pump(const Duration(minutes: 1));
});
}
testWidgets(
'Map overflow menu omits leading divider while building path trace',
(tester) async {
final env = await _createEnv(tester, connected: true);
env.viewState.mapPathTrace.active = true;
await tester.pumpWidget(env.wrap(const MapScreen()));
await _pumpSettleFrames(tester);
await tester.tap(find.byIcon(Icons.more_vert));
await _pumpSettleFrames(tester);
expect(_openMenuEntries(tester), [
_l10n.common_disconnect,
_l10n.settings_title,
]);
await tester.pumpWidget(const SizedBox());
await tester.pump(const Duration(minutes: 1));
},
);
});
group('Overflow menus at 320dp with 1.3x and 2.0x text scale', () {
final screens = <String, Widget Function()>{
'Contacts': () => const ContactsScreen(),
'Channels': () => const ChannelsScreen(),
'Map': () => const MapScreen(),
};
for (final entry in screens.entries) {
for (final scale in [1.3, 2.0]) {
testWidgets('${entry.key} overflow menu fits 320dp at ${scale}x', (
tester,
) async {
tester.view.physicalSize = const Size(320, 568);
tester.view.devicePixelRatio = 1.0;
addTearDown(tester.view.reset);
final env = await _createEnv(tester, connected: true);
final overflows = <String>[];
final previous = FlutterError.onError;
FlutterError.onError = (details) {
final text = details.exceptionAsString();
if (!text.contains('overflowed')) {
previous?.call(details);
return;
}
overflows.add(text.split('\n').first);
};
addTearDown(() => FlutterError.onError = previous);
await tester.pumpWidget(env.wrap(entry.value(), textScale: scale));
await _pumpSettleFrames(tester);
await tester.tap(find.byIcon(Icons.more_vert));
await _pumpSettleFrames(tester);
await tester.pumpWidget(const SizedBox());
await tester.pump(const Duration(minutes: 1));
FlutterError.onError = previous;
expect(overflows, isEmpty, reason: overflows.join('\n'));
});
}
}
});
}
+59 -2
View File
@@ -95,7 +95,11 @@ void main() {
viewState.dispose();
});
Future<void> openMap(WidgetTester tester) async {
Future<void> openMap(
WidgetTester tester, {
ThemeMode themeMode = ThemeMode.light,
LatLng? highlight,
}) async {
await tester.pumpWidget(
MultiProvider(
providers: [
@@ -107,9 +111,11 @@ void main() {
],
child: MaterialApp(
theme: MeshTheme.light(),
darkTheme: MeshTheme.dark(),
themeMode: themeMode,
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: const MapScreen(),
home: MapScreen(highlightPosition: highlight),
),
),
);
@@ -185,4 +191,55 @@ void main() {
expect(markerPoints(tester), contains(const LatLng(35, -112)));
await tester.pumpWidget(const SizedBox.shrink());
});
testWidgets('node labels follow a system light/dark switch', (tester) async {
addTearDown(tester.platformDispatcher.clearPlatformBrightnessTestValue);
tester.platformDispatcher.platformBrightnessTestValue = Brightness.light;
connector.nodes = [_node()];
// Zoomed in past the label threshold so node names are drawn.
await openMap(
tester,
themeMode: ThemeMode.system,
highlight: const LatLng(35, -112),
);
Color? labelColor() => tester
.widget<Text>(
find.descendant(
of: find.byType(MarkerLayer),
matching: find.text('Repeater'),
),
)
.style
?.color;
expect(labelColor(), MeshTheme.light().colorScheme.onSurface);
tester.platformDispatcher.platformBrightnessTestValue = Brightness.dark;
await tester.pumpAndSettle();
expect(labelColor(), MapPalette.textPrimary);
tester.platformDispatcher.platformBrightnessTestValue = Brightness.light;
await tester.pumpAndSettle();
expect(labelColor(), MeshTheme.light().colorScheme.onSurface);
await tester.pumpWidget(const SizedBox.shrink());
});
testWidgets('a fixed light theme ignores the system switch', (tester) async {
addTearDown(tester.platformDispatcher.clearPlatformBrightnessTestValue);
tester.platformDispatcher.platformBrightnessTestValue = Brightness.light;
connector.nodes = [_node()];
await openMap(tester, highlight: const LatLng(35, -112));
tester.platformDispatcher.platformBrightnessTestValue = Brightness.dark;
await tester.pumpAndSettle();
final label = tester.widget<Text>(
find.descendant(
of: find.byType(MarkerLayer),
matching: find.text('Repeater'),
),
);
expect(label.style?.color, MeshTheme.light().colorScheme.onSurface);
await tester.pumpWidget(const SizedBox.shrink());
});
}
@@ -0,0 +1,498 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:meshcore_open/connector/meshcore_connector.dart';
import 'package:meshcore_open/l10n/app_localizations.dart';
import 'package:meshcore_open/screens/app_settings_screen.dart';
import 'package:meshcore_open/services/app_settings_service.dart';
import 'package:meshcore_open/services/network_map/network_map_upload_service.dart';
import 'package:meshcore_open/services/notification_service.dart';
import 'package:meshcore_open/services/translation_service.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:meshcore_open/theme/mesh_theme.dart';
import 'package:meshcore_open/utils/platform_info.dart';
import 'package:meshcore_open/widgets/mesh_nav_tile.dart';
import 'package:meshcore_open/widgets/mesh_ui.dart';
import 'package:meshcore_open/widgets/settings_reveal.dart';
Future<AppSettingsService> _createSettingsService({
bool notificationsEnabled = true,
}) async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
final settings = AppSettingsService();
await settings.loadSettings();
if (!notificationsEnabled) {
await settings.setNotificationsEnabled(false);
}
return settings;
}
Widget _buildSectionTestApp({
required AppSettingsService settings,
ThemeData? theme,
double textScale = 1.0,
Future<bool> Function()? hasPermission,
Future<bool> Function()? requestPermission,
}) {
return ChangeNotifierProvider.value(
value: settings,
child: MaterialApp(
theme: theme ?? MeshTheme.light(),
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
builder: (context, child) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(textScaler: TextScaler.linear(textScale)),
child: child!,
),
home: Scaffold(
body: MeshSettingsTileTheme(
child: SingleChildScrollView(
child: MeshCard(
padding: EdgeInsets.zero,
child: NotificationsSettingsSection(
hasPermission: hasPermission,
requestPermission: requestPermission,
),
),
),
),
),
),
);
}
void main() {
setUp(() {
NotificationService().resetForTest();
PlatformInfo.debugIsAndroidOverride = null;
});
tearDown(() {
NotificationService().resetForTest();
PlatformInfo.debugIsAndroidOverride = null;
});
testWidgets(
'notificationsEnabled + OS permission granted shows switch ON, expanded SettingsReveal, and exact row order including Android Background Activity last',
(tester) async {
PlatformInfo.debugIsAndroidOverride = true;
final settings = await _createSettingsService(notificationsEnabled: true);
await tester.pumpWidget(
_buildSectionTestApp(
settings: settings,
hasPermission: () async => true,
),
);
await tester.pumpAndSettle();
final context = tester.element(find.byType(NotificationsSettingsSection));
final l10n = AppLocalizations.of(context);
final enableTile = tester.widget<SwitchListTile>(
find.widgetWithText(
SwitchListTile,
l10n.appSettings_enableNotifications,
),
);
expect(enableTile.value, isTrue);
expect(
find.text(l10n.appSettings_enableNotificationsSubtitle),
findsOneWidget,
);
final reveal = tester.widget<SettingsReveal>(find.byType(SettingsReveal));
expect(reveal.visible, isTrue);
final msgFinder = find.text(l10n.appSettings_messageNotifications);
final channelFinder = find.text(
l10n.appSettings_channelMessageNotifications,
);
final advertFinder = find.text(
l10n.appSettings_advertisementNotifications,
);
final bgActivityFinder = find.text(l10n.appSettings_batteryOptimization);
expect(msgFinder, findsOneWidget);
expect(channelFinder, findsOneWidget);
expect(advertFinder, findsOneWidget);
expect(bgActivityFinder, findsOneWidget);
final msgY = tester.getTopLeft(msgFinder).dy;
final channelY = tester.getTopLeft(channelFinder).dy;
final advertY = tester.getTopLeft(advertFinder).dy;
final bgActivityY = tester.getTopLeft(bgActivityFinder).dy;
expect(msgY, lessThan(channelY));
expect(channelY, lessThan(advertY));
expect(advertY, lessThan(bgActivityY));
},
);
testWidgets(
'notificationsEnabled + OS permission denied shows switch OFF, hides child toggles, shows denied subtitle, and requests permission on tap',
(tester) async {
PlatformInfo.debugIsAndroidOverride = true;
final settings = await _createSettingsService(notificationsEnabled: true);
var requestResult = false;
var requestCalls = 0;
await tester.pumpWidget(
_buildSectionTestApp(
settings: settings,
hasPermission: () async => false,
requestPermission: () async {
requestCalls++;
return requestResult;
},
),
);
await tester.pumpAndSettle();
final context = tester.element(find.byType(NotificationsSettingsSection));
final l10n = AppLocalizations.of(context);
SwitchListTile enableTile() => tester.widget<SwitchListTile>(
find.widgetWithText(
SwitchListTile,
l10n.appSettings_enableNotifications,
),
);
// Even though settings.notificationsEnabled is true, switch is OFF when OS permission is denied.
expect(settings.settings.notificationsEnabled, isTrue);
expect(enableTile().value, isFalse);
expect(
find.text(l10n.appSettings_notificationPermissionDenied),
findsOneWidget,
);
expect(find.text(l10n.appSettings_messageNotifications), findsNothing);
expect(
find.text(l10n.appSettings_channelMessageNotifications),
findsNothing,
);
expect(
find.text(l10n.appSettings_advertisementNotifications),
findsNothing,
);
expect(find.text(l10n.appSettings_batteryOptimization), findsNothing);
// No stray Divider when collapsed.
expect(find.byType(Divider), findsNothing);
// Tapping switch while permission request is denied keeps it OFF and shows snackbar.
await tester.tap(find.text(l10n.appSettings_enableNotifications));
await tester.pumpAndSettle();
expect(requestCalls, 1);
expect(enableTile().value, isFalse);
expect(find.text(l10n.appSettings_messageNotifications), findsNothing);
expect(
find.descendant(
of: find.byType(SnackBar),
matching: find.text(l10n.appSettings_notificationPermissionDenied),
),
findsOneWidget,
);
// Now grant permission on the next tap: switch turns ON, snackbar appears, and children expand.
requestResult = true;
await tester.tap(find.text(l10n.appSettings_enableNotifications));
await tester.pump();
await tester.pump(RevealOnEnable.duration);
await tester.pumpAndSettle();
expect(requestCalls, 2);
expect(enableTile().value, isTrue);
expect(settings.settings.notificationsEnabled, isTrue);
expect(
find.text(l10n.appSettings_enableNotificationsSubtitle),
findsOneWidget,
);
expect(
find.descendant(
of: find.byType(SnackBar),
matching: find.text(l10n.appSettings_notificationsEnabled),
),
findsOneWidget,
);
expect(find.text(l10n.appSettings_messageNotifications), findsOneWidget);
expect(
find.text(l10n.appSettings_channelMessageNotifications),
findsOneWidget,
);
expect(
find.text(l10n.appSettings_advertisementNotifications),
findsOneWidget,
);
expect(find.text(l10n.appSettings_batteryOptimization), findsOneWidget);
},
);
testWidgets('does not flash ON while async OS permission check is in flight', (
tester,
) async {
final settings = await _createSettingsService(notificationsEnabled: true);
final completer = Completer<bool>();
await tester.pumpWidget(
_buildSectionTestApp(
settings: settings,
hasPermission: () => completer.future,
),
);
final context = tester.element(find.byType(NotificationsSettingsSection));
final l10n = AppLocalizations.of(context);
// While async permission check is in flight, switch is OFF and children are hidden,
// and the normal subtitle is shown rather than flashing an error prematurely.
final initialTile = tester.widget<SwitchListTile>(
find.widgetWithText(SwitchListTile, l10n.appSettings_enableNotifications),
);
expect(initialTile.value, isFalse);
expect(
find.text(l10n.appSettings_enableNotificationsSubtitle),
findsOneWidget,
);
expect(find.text(l10n.appSettings_messageNotifications), findsNothing);
completer.complete(false);
await tester.pumpAndSettle();
final settledTile = tester.widget<SwitchListTile>(
find.widgetWithText(SwitchListTile, l10n.appSettings_enableNotifications),
);
expect(settledTile.value, isFalse);
expect(
find.text(l10n.appSettings_notificationPermissionDenied),
findsOneWidget,
);
expect(find.text(l10n.appSettings_messageNotifications), findsNothing);
});
testWidgets(
'toggling OFF -> ON collapses children out of tree and expands them back',
(tester) async {
final settings = await _createSettingsService(notificationsEnabled: true);
await tester.pumpWidget(
_buildSectionTestApp(
settings: settings,
hasPermission: () async => true,
requestPermission: () async => true,
),
);
await tester.pumpAndSettle();
final context = tester.element(find.byType(NotificationsSettingsSection));
final l10n = AppLocalizations.of(context);
expect(find.text(l10n.appSettings_messageNotifications), findsOneWidget);
// Toggle OFF
await tester.tap(find.text(l10n.appSettings_enableNotifications));
await tester.pump();
await tester.pump(RevealOnEnable.duration);
await tester.pumpAndSettle();
expect(settings.settings.notificationsEnabled, isFalse);
expect(find.text(l10n.appSettings_messageNotifications), findsNothing);
expect(
find.text(l10n.appSettings_channelMessageNotifications),
findsNothing,
);
expect(
find.text(l10n.appSettings_advertisementNotifications),
findsNothing,
);
expect(find.byType(Divider), findsNothing);
expect(
find.descendant(
of: find.byType(SnackBar),
matching: find.text(l10n.appSettings_notificationsDisabled),
),
findsOneWidget,
);
// Toggle back ON
await tester.tap(find.text(l10n.appSettings_enableNotifications));
await tester.pump();
await tester.pump(RevealOnEnable.duration);
await tester.pumpAndSettle();
expect(settings.settings.notificationsEnabled, isTrue);
expect(find.text(l10n.appSettings_messageNotifications), findsOneWidget);
expect(
find.text(l10n.appSettings_channelMessageNotifications),
findsOneWidget,
);
expect(
find.text(l10n.appSettings_advertisementNotifications),
findsOneWidget,
);
},
);
testWidgets(
'AppLifecycleState.resumed re-checks OS permission for revoke and grant',
(tester) async {
final settings = await _createSettingsService(notificationsEnabled: true);
var osPermissionGranted = true;
await tester.pumpWidget(
_buildSectionTestApp(
settings: settings,
hasPermission: () async => osPermissionGranted,
),
);
await tester.pumpAndSettle();
final context = tester.element(find.byType(NotificationsSettingsSection));
final l10n = AppLocalizations.of(context);
SwitchListTile enableTile() => tester.widget<SwitchListTile>(
find.widgetWithText(
SwitchListTile,
l10n.appSettings_enableNotifications,
),
);
expect(enableTile().value, isTrue);
expect(find.text(l10n.appSettings_messageNotifications), findsOneWidget);
// User revokes permission in OS settings and resumes app.
osPermissionGranted = false;
tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.paused);
tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
await tester.pump();
await tester.pump(RevealOnEnable.duration);
await tester.pumpAndSettle();
expect(enableTile().value, isFalse);
expect(
find.text(l10n.appSettings_notificationPermissionDenied),
findsOneWidget,
);
expect(find.text(l10n.appSettings_messageNotifications), findsNothing);
// User grants permission in OS settings and resumes app.
osPermissionGranted = true;
tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.paused);
tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
await tester.pump();
await tester.pump(RevealOnEnable.duration);
await tester.pumpAndSettle();
expect(enableTile().value, isTrue);
expect(
find.text(l10n.appSettings_enableNotificationsSubtitle),
findsOneWidget,
);
expect(find.text(l10n.appSettings_messageNotifications), findsOneWidget);
},
);
testWidgets(
'AppSettingsScreen integrates NotificationService permission hook',
(tester) async {
final settings = await _createSettingsService(notificationsEnabled: true);
NotificationService().permissionCheckerForTest = () async => false;
tester.view.physicalSize = const Size(800, 4000);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
final connector = MeshCoreConnector();
final translation = TranslationService(settings);
final uploads = NetworkMapUploadService(
connector: connector,
settings: settings,
);
addTearDown(connector.dispose);
addTearDown(translation.dispose);
addTearDown(uploads.dispose);
await tester.pumpWidget(
MultiProvider(
providers: [
ChangeNotifierProvider.value(value: settings),
ChangeNotifierProvider.value(value: connector),
ChangeNotifierProvider.value(value: translation),
ChangeNotifierProvider.value(value: uploads),
],
child: MaterialApp(
theme: MeshTheme.light(),
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: const AppSettingsScreen(),
),
),
);
await tester.pumpAndSettle();
final context = tester.element(find.byType(AppSettingsScreen));
final l10n = AppLocalizations.of(context);
final enableTile = tester.widget<SwitchListTile>(
find.widgetWithText(
SwitchListTile,
l10n.appSettings_enableNotifications,
),
);
expect(enableTile.value, isFalse);
expect(
find.text(l10n.appSettings_notificationPermissionDenied),
findsOneWidget,
);
expect(find.text(l10n.appSettings_messageNotifications), findsNothing);
},
);
for (final isDark in [false, true]) {
for (final scale in [1.3, 2.0]) {
for (final granted in [true, false]) {
testWidgets(
'NotificationsSettingsSection fits 320dp at ${scale}x in ${isDark ? "dark" : "light"} theme when permission=${granted ? "granted" : "denied"}',
(tester) async {
PlatformInfo.debugIsAndroidOverride = true;
tester.view.physicalSize = const Size(320, 568);
tester.view.devicePixelRatio = 1.0;
addTearDown(tester.view.reset);
final settings = await _createSettingsService(
notificationsEnabled: true,
);
await tester.pumpWidget(
_buildSectionTestApp(
settings: settings,
theme: isDark ? MeshTheme.dark() : MeshTheme.light(),
textScale: scale,
hasPermission: () async => granted,
),
);
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
// Verify 48dp minimum touch target height on all rendered tiles.
final tiles = find.byType(ListTile);
expect(tiles, findsWidgets);
for (final element in tiles.evaluate()) {
final size = tester.getSize(find.byWidget(element.widget));
expect(size.height, greaterThanOrEqualTo(48));
}
},
);
}
}
}
}
+247 -1
View File
@@ -34,13 +34,17 @@ import 'package:meshcore_open/services/timeout_prediction_service.dart';
import 'package:meshcore_open/services/translation_service.dart';
import 'package:meshcore_open/services/ui_view_state_service.dart';
import 'package:meshcore_open/storage/channel_message_store.dart';
import 'package:meshcore_open/storage/channel_settings_store.dart';
import 'package:meshcore_open/storage/contact_settings_store.dart';
import 'package:meshcore_open/storage/channel_store.dart';
import 'package:meshcore_open/storage/contact_store.dart';
import 'package:meshcore_open/storage/last_radio_store.dart';
import 'package:meshcore_open/storage/message_store.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:meshcore_open/theme/mesh_theme.dart';
import 'package:meshcore_open/widgets/chat_background.dart';
import 'package:meshcore_open/widgets/chat_composer.dart';
import 'package:meshcore_open/widgets/chat_compression_selector.dart';
import 'package:meshcore_open/widgets/connect_sheet.dart';
final _radioKey = Uint8List.fromList(List<int>.generate(32, (i) => 0xA0 + i));
@@ -247,7 +251,7 @@ void main() {
await _settle(tester);
expect(_menuItem(_l10n.contacts_floodAdvert).enabled, isFalse);
expect(_menuItem(_l10n.contacts_zeroHopAdvert).enabled, isFalse);
expect(_menuItem(_l10n.contacts_addContactFromClipboard).enabled, isFalse);
expect(_menuItem(_l10n.addContact_title).enabled, isFalse);
expect(_menuItem(_l10n.common_connect).enabled, isTrue);
await tester.pumpWidget(const SizedBox());
});
@@ -344,4 +348,246 @@ void main() {
await tester.pumpWidget(const SizedBox());
await tester.pump(const Duration(minutes: 1));
});
group('compression selector', () {
Future<void> choose(WidgetTester tester, String mode) async {
await tester.tap(find.byType(ChatCompressionSelector));
await _settle(tester);
await tester.tap(find.text(mode));
await _settle(tester);
// Connector notifications are debounced on a real timer.
await tester.runAsync(
() => Future<void>.delayed(const Duration(milliseconds: 200)),
);
await _settle(tester);
}
testWidgets('DM chat shows it at the top and saves offline', (
tester,
) async {
final connector = await _offlineConnector(tester);
final alice = connector.contacts.single;
final store = ContactSettingsStore()..setPublicKeyHex = _radioHex;
await tester.pumpWidget(
await _app(tester, connector, ChatScreen(contact: alice)),
);
await _settle(tester);
expect(find.byType(ChatCompressionSelector), findsOneWidget);
expect(find.text(_l10n.chatCompression_label('Off')), findsOneWidget);
// Above the transcript, outside its scroll view.
expect(
find.ancestor(
of: find.byType(ChatCompressionSelector),
matching: find.byType(Scrollable),
),
findsNothing,
);
expect(
tester.getBottomLeft(find.byType(ChatCompressionSelector)).dy,
lessThanOrEqualTo(tester.getTopLeft(find.byType(ChatBackdrop)).dy),
);
await choose(tester, _l10n.chatCompression_smaz);
expect(find.text(_l10n.chatCompression_label('SMAZ')), findsOneWidget);
expect(
await tester.runAsync(() => store.loadSmazEnabled(alice.publicKeyHex)),
isTrue,
);
await choose(tester, _l10n.chatCompression_cyr2lat);
// Cyr2Lat keeps the sheet open for its profile picker.
await tester.tap(find.byTooltip('Close'));
await _settle(tester);
expect(find.text(_l10n.chatCompression_label('Cyr2Lat')), findsOneWidget);
expect(
connector.contactCompressionMode(alice.publicKeyHex),
ChatCompressionMode.cyr2lat,
);
expect(
await tester.runAsync(() => store.loadSmazEnabled(alice.publicKeyHex)),
isFalse,
);
expect(
await tester.runAsync(
() => store.loadCyr2LatEnabled(alice.publicKeyHex),
),
isTrue,
);
// The settings dialog no longer carries the compression switches.
await tester.tap(find.byIcon(Icons.more_vert));
await _settle(tester);
await tester.tap(find.text(_l10n.contact_settings).last);
await _settle(tester);
expect(find.byType(AlertDialog), findsOneWidget);
expect(
find.descendant(
of: find.byType(AlertDialog),
matching: find.textContaining(RegExp('SMAZ|Cyr2Lat')),
),
findsNothing,
);
await tester.pumpWidget(const SizedBox());
});
testWidgets('channel chat uses the same selector and saves offline', (
tester,
) async {
final connector = await _offlineConnector(tester);
final channel = connector.channels.single;
final store = ChannelSettingsStore()..setPublicKeyHex = _radioHex;
await tester.pumpWidget(
await _app(tester, connector, ChannelChatScreen(channel: channel)),
);
await _settle(tester);
expect(find.byType(ChatCompressionSelector), findsOneWidget);
expect(find.text(_l10n.chatCompression_label('Off')), findsOneWidget);
await choose(tester, _l10n.chatCompression_smaz);
expect(find.text(_l10n.chatCompression_label('SMAZ')), findsOneWidget);
expect(
await tester.runAsync(() => store.loadSmazEnabled(channel.storageId!)),
isTrue,
);
expect(
await tester.runAsync(
() => store.loadCyr2LatEnabled(channel.storageId!),
),
isFalse,
);
await tester.pumpWidget(const SizedBox());
});
testWidgets('saving the channel edit sheet leaves compression alone', (
tester,
) async {
final connector = MeshCoreConnector();
addTearDown(connector.dispose);
connector.reviewRadioFactoryForTest = () => ReviewRadio(
scheduledMessageInterval: const Duration(hours: 1),
ackDelay: const Duration(hours: 1),
replyDelay: const Duration(hours: 1),
);
await tester.runAsync(connector.connectReview);
await _waitFor(tester, () => connector.channelMapConfirmed);
final channel = connector.channels.firstWhere((c) => c.index == 1);
await tester.runAsync(
() => connector.setChannelCompressionMode(1, ChatCompressionMode.smaz),
);
await tester.pumpWidget(
await _app(
tester,
connector,
Builder(
builder: (context) => Scaffold(
body: Center(
child: TextButton(
onPressed: () =>
showEditChannelSheet(context, connector, channel),
child: const Text('edit'),
),
),
),
),
),
);
await tester.tap(find.text('edit'));
await _settle(tester);
expect(find.text('SMAZ compression'), findsNothing);
// The chat's selector changes the mode while the sheet is open.
await tester.runAsync(
() =>
connector.setChannelCompressionMode(1, ChatCompressionMode.cyr2lat),
);
await tester.enterText(find.byType(TextField).first, 'Hiking Crew');
await tester.tap(find.text(_l10n.common_save));
await tester.runAsync(
() => Future<void>.delayed(const Duration(milliseconds: 500)),
);
await _settle(tester);
expect(
connector.channels.firstWhere((c) => c.index == 1).name,
'Hiking Crew',
);
expect(connector.channelCompressionMode(1), ChatCompressionMode.cyr2lat);
await tester.runAsync(connector.disconnect);
await tester.pumpWidget(const SizedBox());
await tester.pump(const Duration(minutes: 1));
});
testWidgets('a new PSK in the channel edit sheet keeps compression', (
tester,
) async {
final connector = MeshCoreConnector();
addTearDown(connector.dispose);
connector.reviewRadioFactoryForTest = () => ReviewRadio(
scheduledMessageInterval: const Duration(hours: 1),
ackDelay: const Duration(hours: 1),
replyDelay: const Duration(hours: 1),
);
await tester.runAsync(connector.connectReview);
await _waitFor(tester, () => connector.channelMapConfirmed);
final channel = connector.channels.firstWhere((c) => c.index == 1);
final oldId = connector.channelIdForSlot(1);
await tester.runAsync(
() => connector.setChannelCompressionMode(1, ChatCompressionMode.smaz),
);
await tester.pumpWidget(
await _app(
tester,
connector,
Builder(
builder: (context) => Scaffold(
body: Center(
child: TextButton(
onPressed: () =>
showEditChannelSheet(context, connector, channel),
child: const Text('edit'),
),
),
),
),
),
);
await tester.tap(find.text('edit'));
await _settle(tester);
await tester.enterText(find.byType(TextField).at(1), '0f' * 16);
await tester.tap(find.text(_l10n.common_save));
// The save runs in the test zone and waits on the radio's real I/O.
for (var i = 0; i < 40; i++) {
await tester.runAsync(
() => Future<void>.delayed(const Duration(milliseconds: 50)),
);
await tester.pump(const Duration(milliseconds: 100));
if (find
.text(_l10n.channels_channelUpdated(channel.name))
.evaluate()
.isNotEmpty) {
break;
}
}
await _settle(tester);
final newId = connector.channelIdForSlot(1);
expect(newId, isNot(oldId));
expect(connector.channelCompressionMode(1), ChatCompressionMode.smaz);
final store = ChannelSettingsStore()
..setPublicKeyHex = connector.selfPublicKeyHex;
expect(
await tester.runAsync(() => store.loadSmazEnabled(newId!)),
isTrue,
);
await tester.runAsync(connector.disconnect);
await tester.pumpWidget(const SizedBox());
await tester.pump(const Duration(minutes: 1));
});
});
}
+427 -4
View File
@@ -1,7 +1,11 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:latlong2/latlong.dart';
import 'package:provider/provider.dart';
import 'dart:typed_data';
import 'package:meshcore_open/connector/meshcore_connector.dart';
@@ -40,16 +44,57 @@ class _FakeMeshCoreConnector extends MeshCoreConnector {
Uint8List.fromList(List.generate(32, (i) => i));
@override
double? get selfLatitude => 48.8566;
bool get isConnected => _isConnected;
@override
double? get selfLongitude => 2.3522;
double? get selfLatitude => _selfLat;
@override
List<Contact> get allContactsUnfiltered => [];
double? get selfLongitude => _selfLon;
@override
List<Contact> get contacts => [];
List<Contact> get allContactsUnfiltered => _allContacts;
@override
List<Contact> get contacts => _peerContacts;
final bool _isConnected;
double? _selfLat;
double? _selfLon;
double? _pendingLat;
double? _pendingLon;
final List<Contact> _allContacts;
final List<Contact> _peerContacts;
_FakeMeshCoreConnector({
bool isConnected = false,
double? selfLat = 48.8566,
double? selfLon = 2.3522,
List<Contact> allContacts = const [],
List<Contact> peerContacts = const [],
}) : _isConnected = isConnected,
_selfLat = selfLat,
_selfLon = selfLon,
_allContacts = allContacts,
_peerContacts = peerContacts;
@override
Future<void> setNodeLocation({
required double lat,
required double lon,
}) async {
_pendingLat = lat;
_pendingLon = lon;
}
@override
Future<void> refreshDeviceInfo() async {
if (_pendingLat != null && _pendingLon != null) {
_selfLat = _pendingLat;
_selfLon = _pendingLon;
notifyListeners();
}
}
void emitFrame(Uint8List frame) {
_receivedFramesController.add(frame);
@@ -400,4 +445,382 @@ void main() {
// Verify it parsed correctly (should not show the unavailable message)
expect(find.text('Path trace not available.'), findsNothing);
});
testWidgets(
'PathTraceMapScreen ignores impossible distant repeater and peer inference',
(tester) async {
final localHop1 = Contact(
publicKey: Uint8List(32)..first = 0x48,
name: 'Local Hop',
type: advTypeRepeater,
path: Uint8List(0),
pathLength: 0,
latitude: 33.60097,
longitude: -112.02457,
lastSeen: DateTime.utc(2026),
);
final eastCoastBogus = Contact(
publicKey: Uint8List(32)..first = 0x9C,
name: 'East Coast 9C',
type: advTypeRepeater,
path: Uint8List(0),
pathLength: 0,
latitude: 42.3601,
longitude: -71.0589,
lastSeen: DateTime.utc(2026),
);
final distantPeerSharing9C = Contact(
publicKey: Uint8List(32)..first = 0xAA,
name: 'Distant Chat Peer',
type: advTypeChat,
path: Uint8List.fromList([0x9C]),
pathLength: 1,
latitude: 42.35,
longitude: -71.06,
lastSeen: DateTime.utc(2026),
);
final connector = _FakeMeshCoreConnector(
selfLat: 33.4484,
selfLon: -112.0740,
allContacts: [localHop1, eastCoastBogus],
peerContacts: [distantPeerSharing9C],
);
final screen = PathTraceMapScreen(
title: 'Trace Impossible Hop',
path: Uint8List.fromList([0x48, 0x9C]),
pathHashByteWidth: 1,
);
await tester.pumpWidget(
_buildTestApp(connector: connector, child: screen),
);
await tester.pump();
final sentFrame = connector.sentFrames.first;
final tag = sentFrame.sublist(1, 5);
final pushTraceFrame = Uint8List(17);
pushTraceFrame[0] = pushCodeTraceData;
pushTraceFrame[1] = 0;
pushTraceFrame[2] = 2;
pushTraceFrame[3] = 0;
pushTraceFrame.setRange(4, 8, tag);
pushTraceFrame.setRange(12, 14, [0x48, 0x9C]);
pushTraceFrame.setRange(14, 17, [12, 16, 20]);
connector.emitFrame(pushTraceFrame);
for (int i = 0; i < 5; i++) {
await tester.pump(const Duration(milliseconds: 100));
}
await tester.tap(find.byIcon(Icons.open_in_full));
await tester.pumpAndSettle();
expect(find.textContaining('East Coast 9C'), findsNothing);
expect(find.textContaining('9C: Unknown Repeater'), findsWidgets);
final polylineLayer = tester.widget<PolylineLayer>(
find.byType(PolylineLayer),
);
final allPoints = polylineLayer.polylines
.expand((p) => p.points)
.toList();
expect(allPoints, isNotEmpty);
for (final point in allPoints) {
expect(point.latitude, inInclusiveRange(33.0, 34.0));
expect(point.longitude, inInclusiveRange(-113.0, -111.0));
}
},
);
testWidgets(
'PathTraceMapScreen ignores impossible distant contact passed via pathContacts',
(tester) async {
final localHop1 = Contact(
publicKey: Uint8List(32)..first = 0x48,
name: 'Local Hop',
type: advTypeRepeater,
path: Uint8List(0),
pathLength: 0,
latitude: 33.60097,
longitude: -112.02457,
lastSeen: DateTime.utc(2026),
);
final eastCoastBogus = Contact(
publicKey: Uint8List(32)..first = 0x9C,
name: 'East Coast 9C',
type: advTypeRepeater,
path: Uint8List(0),
pathLength: 0,
latitude: 42.3601,
longitude: -71.0589,
lastSeen: DateTime.utc(2026),
);
final connector = _FakeMeshCoreConnector(
selfLat: 33.4484,
selfLon: -112.0740,
allContacts: [localHop1, eastCoastBogus],
);
final screen = PathTraceMapScreen(
title: 'Manual Trace Impossible Hop',
path: Uint8List.fromList([0x48, 0x9C]),
pathHashByteWidth: 1,
pathContacts: [localHop1, eastCoastBogus],
);
await tester.pumpWidget(
_buildTestApp(connector: connector, child: screen),
);
await tester.pump();
final sentFrame = connector.sentFrames.first;
final tag = sentFrame.sublist(1, 5);
final pushTraceFrame = Uint8List(17);
pushTraceFrame[0] = pushCodeTraceData;
pushTraceFrame[1] = 0;
pushTraceFrame[2] = 2;
pushTraceFrame[3] = 0;
pushTraceFrame.setRange(4, 8, tag);
pushTraceFrame.setRange(12, 14, [0x48, 0x9C]);
pushTraceFrame.setRange(14, 17, [12, 16, 20]);
connector.emitFrame(pushTraceFrame);
for (int i = 0; i < 5; i++) {
await tester.pump(const Duration(milliseconds: 100));
}
await tester.tap(find.byIcon(Icons.open_in_full));
await tester.pumpAndSettle();
expect(find.textContaining('East Coast 9C'), findsNothing);
expect(find.textContaining('9C: Unknown Repeater'), findsWidgets);
final polylineLayer = tester.widget<PolylineLayer>(
find.byType(PolylineLayer),
);
final allPoints = polylineLayer.polylines
.expand((p) => p.points)
.toList();
expect(allPoints.length, 2);
for (final point in allPoints) {
expect(point.latitude, inInclusiveRange(33.0, 34.0));
expect(point.longitude, inInclusiveRange(-113.0, -111.0));
}
},
);
testWidgets(
'PathTraceMapScreen preserves plausible explicit pathContacts over nearer contact with same prefix',
(tester) async {
final nearerCollision = Contact(
publicKey: Uint8List(32)
..[0] = 0x48
..[1] = 0x01,
name: 'Nearer 48',
type: advTypeRepeater,
path: Uint8List(0),
pathLength: 0,
latitude: 33.4600,
longitude: -112.0700,
lastSeen: DateTime.utc(2026, 6),
);
final selectedExplicit = Contact(
publicKey: Uint8List(32)
..[0] = 0x48
..[1] = 0x02,
name: 'Selected 48',
type: advTypeRepeater,
path: Uint8List(0),
pathLength: 0,
latitude: 33.9000,
longitude: -111.7000,
lastSeen: DateTime.utc(2026, 1),
);
final fallbackHop2 = Contact(
publicKey: Uint8List(32)..first = 0x53,
name: 'Fallback 53',
type: advTypeRepeater,
path: Uint8List(0),
pathLength: 0,
latitude: 33.9500,
longitude: -111.6500,
lastSeen: DateTime.utc(2026),
);
final connector = _FakeMeshCoreConnector(
selfLat: 33.4484,
selfLon: -112.0740,
allContacts: [nearerCollision, selectedExplicit, fallbackHop2],
);
final screen = PathTraceMapScreen(
title: 'Explicit Contact Priority',
path: Uint8List.fromList([0x48, 0x53]),
pathHashByteWidth: 1,
pathContacts: [selectedExplicit],
);
await tester.pumpWidget(
_buildTestApp(connector: connector, child: screen),
);
await tester.pump();
final sentFrame = connector.sentFrames.first;
final tag = sentFrame.sublist(1, 5);
final pushTraceFrame = Uint8List(17);
pushTraceFrame[0] = pushCodeTraceData;
pushTraceFrame[1] = 0;
pushTraceFrame[2] = 2;
pushTraceFrame[3] = 0;
pushTraceFrame.setRange(4, 8, tag);
pushTraceFrame.setRange(12, 14, [0x48, 0x53]);
pushTraceFrame.setRange(14, 17, [12, 16, 20]);
connector.emitFrame(pushTraceFrame);
for (int i = 0; i < 5; i++) {
await tester.pump(const Duration(milliseconds: 100));
}
await tester.tap(find.byIcon(Icons.open_in_full));
await tester.pumpAndSettle();
expect(find.textContaining('Selected 48'), findsWidgets);
expect(find.textContaining('Fallback 53'), findsWidgets);
expect(find.textContaining('Nearer 48'), findsNothing);
final polylineLayer = tester.widget<PolylineLayer>(
find.byType(PolylineLayer),
);
final allPoints = polylineLayer.polylines
.expand((p) => p.points)
.toList();
expect(allPoints.length, 3);
expect(allPoints[1].latitude, closeTo(33.9000, 1e-4));
expect(allPoints[1].longitude, closeTo(-111.7000, 1e-4));
expect(allPoints[2].latitude, closeTo(33.9500, 1e-4));
expect(allPoints[2].longitude, closeTo(-111.6500, 1e-4));
},
);
testWidgets(
'PathTraceMapScreen re-resolves primary hops when self location changes via _setMyLocation',
(tester) async {
final localHop1 = Contact(
publicKey: Uint8List(32)..first = 0x48,
name: 'Phoenix Hop 1',
type: advTypeRepeater,
path: Uint8List(0),
pathLength: 0,
latitude: 33.60097,
longitude: -112.02457,
lastSeen: DateTime.utc(2026),
);
final localHop2 = Contact(
publicKey: Uint8List(32)..first = 0x53,
name: 'Phoenix Hop 2',
type: advTypeRepeater,
path: Uint8List(0),
pathLength: 0,
latitude: 33.46300,
longitude: -111.65000,
lastSeen: DateTime.utc(2026),
);
final connector = _FakeMeshCoreConnector(
isConnected: true,
// Incorrect initial self location on the East Coast causes local hops to be rejected.
selfLat: 42.3601,
selfLon: -71.0589,
allContacts: [localHop1, localHop2],
);
final screen = PathTraceMapScreen(
title: 'Relocate Self Trace',
path: Uint8List.fromList([0x48, 0x53]),
pathHashByteWidth: 1,
);
await tester.pumpWidget(
_buildTestApp(connector: connector, child: screen),
);
await tester.pump();
expect(connector.sentFrames.length, 1);
final tag = connector.sentFrames.first.sublist(1, 5);
final pushTraceFrame = Uint8List(17);
pushTraceFrame[0] = pushCodeTraceData;
pushTraceFrame[1] = 0;
pushTraceFrame[2] = 2;
pushTraceFrame[3] = 0;
pushTraceFrame.setRange(4, 8, tag);
pushTraceFrame.setRange(12, 14, [0x48, 0x53]);
pushTraceFrame.setRange(14, 17, [12, 16, 20]);
connector.emitFrame(pushTraceFrame);
for (int i = 0; i < 5; i++) {
await tester.pump(const Duration(milliseconds: 100));
}
// Initially, both Phoenix hops are rejected as impossibly far from Boston.
await tester.tap(find.byIcon(Icons.open_in_full));
await tester.pumpAndSettle();
expect(find.textContaining('Phoenix Hop 1'), findsNothing);
expect(find.textContaining('Phoenix Hop 2'), findsNothing);
expect(find.textContaining('48: Unknown Repeater'), findsWidgets);
expect(find.textContaining('53: Unknown Repeater'), findsWidgets);
await tester.tap(find.byIcon(Icons.close_fullscreen));
await tester.pumpAndSettle();
expect(find.byType(PolylineLayer), findsNothing);
// Update self location to Phoenix via the map's long-press action.
final flutterMap = tester.widget<FlutterMap>(find.byType(FlutterMap));
flutterMap.options.onLongPress!(
const TapPosition(Offset.zero, Offset.zero),
const LatLng(33.4484, -112.0740),
);
await tester.pumpAndSettle();
await tester.tap(find.widgetWithText(FilledButton, 'Set location'));
await tester.pumpAndSettle();
// Primary hops must now be resolved without waiting for another trace packet.
expect(connector.sentFrames.length, 1);
final polylineLayer = tester.widget<PolylineLayer>(
find.byType(PolylineLayer),
);
final allPoints = polylineLayer.polylines
.expand((p) => p.points)
.toList();
expect(allPoints.length, 3);
expect(allPoints[0].latitude, closeTo(33.4484, 1e-4));
expect(allPoints[0].longitude, closeTo(-112.0740, 1e-4));
expect(allPoints[1].latitude, closeTo(33.60097, 1e-4));
expect(allPoints[1].longitude, closeTo(-112.02457, 1e-4));
expect(allPoints[2].latitude, closeTo(33.46300, 1e-4));
expect(allPoints[2].longitude, closeTo(-111.65000, 1e-4));
final markerLayer = tester.widget<MarkerLayer>(
find.byType(MarkerLayer).first,
);
expect(markerLayer.markers.length, greaterThanOrEqualTo(3));
for (final marker in markerLayer.markers) {
expect(marker.point.latitude, inInclusiveRange(33.0, 34.0));
expect(marker.point.longitude, inInclusiveRange(-113.0, -111.0));
}
await tester.tap(find.byIcon(Icons.open_in_full));
await tester.pumpAndSettle();
expect(find.textContaining('Phoenix Hop 1'), findsWidgets);
expect(find.textContaining('Phoenix Hop 2'), findsWidgets);
expect(find.textContaining('Unknown Repeater'), findsNothing);
},
);
}
+456
View File
@@ -0,0 +1,456 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:meshcore_open/connector/meshcore_connector.dart';
import 'package:meshcore_open/connector/meshcore_protocol.dart';
import 'package:meshcore_open/l10n/app_localizations.dart';
import 'package:meshcore_open/models/channel.dart';
import 'package:meshcore_open/models/channel_message.dart';
import 'package:meshcore_open/models/contact.dart';
import 'package:meshcore_open/models/message.dart';
import 'package:meshcore_open/screens/channels_screen.dart';
import 'package:meshcore_open/screens/chat_screen.dart';
import 'package:meshcore_open/screens/contacts_screen.dart';
import 'package:meshcore_open/services/app_debug_log_service.dart';
import 'package:meshcore_open/services/app_settings_service.dart';
import 'package:meshcore_open/services/ble_debug_log_service.dart';
import 'package:meshcore_open/services/chat_text_scale_service.dart';
import 'package:meshcore_open/services/image_codec_service.dart';
import 'package:meshcore_open/services/map_tile_cache_service.dart';
import 'package:meshcore_open/services/message_filter/message_filter_service.dart';
import 'package:meshcore_open/services/message_retry_service.dart';
import 'package:meshcore_open/services/network_map/network_map_upload_service.dart';
import 'package:meshcore_open/services/path_history_service.dart';
import 'package:meshcore_open/services/received_image_store.dart';
import 'package:meshcore_open/services/storage_service.dart';
import 'package:meshcore_open/services/timeout_prediction_service.dart';
import 'package:meshcore_open/services/translation_service.dart';
import 'package:meshcore_open/services/ui_view_state_service.dart';
import 'package:meshcore_open/storage/channel_message_store.dart';
import 'package:meshcore_open/storage/channel_store.dart';
import 'package:meshcore_open/storage/contact_store.dart';
import 'package:meshcore_open/storage/last_radio_store.dart';
import 'package:meshcore_open/storage/message_store.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:meshcore_open/theme/mesh_theme.dart';
import 'package:meshcore_open/utils/contact_filter_types.dart';
final _radioKey = Uint8List.fromList(List<int>.generate(32, (i) => 0xA0 + i));
final _radioHex = pubKeyToHex(_radioKey);
Uint8List _key(int seed) =>
Uint8List.fromList(List<int>.generate(32, (i) => seed + i));
Uint8List _psk(int seed) =>
Uint8List.fromList(List<int>.generate(16, (i) => seed + i));
/// Local arrival times, an hour apart. Sender clocks are set far off them.
final _base = DateTime(2026, 11, 20, 12);
DateTime _arrived(int hours) => _base.add(Duration(hours: hours));
final _farFuture = DateTime(2099);
final _farPast = DateTime(2001);
ChannelMessage _channelMessage(
int slot,
String text, {
required DateTime sentAt,
required DateTime receivedAt,
String? filterReason,
}) => ChannelMessage(
senderName: 'Bob',
text: text,
timestamp: sentAt,
receivedAt: receivedAt,
isOutgoing: false,
status: ChannelMessageStatus.sent,
channelIndex: slot,
filterReason: filterReason,
);
Message _directMessage(
Uint8List senderKey,
String text, {
required DateTime sentAt,
required DateTime receivedAt,
}) => Message(
senderKey: senderKey,
text: text,
timestamp: sentAt,
receivedAt: receivedAt,
isOutgoing: false,
status: MessageStatus.delivered,
);
/// Seeds the remembered radio with channels (slots in map order) and
/// contacts, each with its saved messages.
Future<void> _seed({
Map<String, List<ChannelMessage> Function(int slot)> channelMessages =
const {},
Map<String, List<Message> Function(Uint8List key)> contactMessages = const {},
}) async {
final channelStore = ChannelStore()..setPublicKeyHex = _radioHex;
final messageStore = ChannelMessageStore()..setPublicKeyHex = _radioHex;
final channels = <Channel>[];
var slot = 0;
for (final entry in channelMessages.entries) {
final channel = Channel(index: slot, name: entry.key, psk: _psk(slot * 16));
channels.add(channel);
await messageStore.saveChannelMessages(
channel.storageId!,
entry.value(slot),
);
slot++;
}
await channelStore.saveChannels(channels);
await channelStore.saveSlotChannelIds({
for (final c in channels) c.index: c.storageId!,
});
final contacts = <Contact>[];
final directStore = MessageStore()..setPublicKeyHex = _radioHex;
var seed = 0x10;
for (final entry in contactMessages.entries) {
final key = _key(seed);
seed += 0x20;
final contact = Contact(
publicKey: key,
name: entry.key,
type: advTypeChat,
pathLength: 1,
path: Uint8List.fromList([0x22]),
lastSeen: DateTime.fromMillisecondsSinceEpoch(1700000000000),
);
contacts.add(contact);
await directStore.saveMessages(contact.publicKeyHex, entry.value(key));
}
await (ContactStore()..setPublicKeyHex = _radioHex).saveContacts(contacts);
await LastRadioStore().save(
LastRadio(
publicKeyHex: _radioHex,
name: 'Base',
transport: LastRadio.transportBle,
bleRemoteId: 'AA:BB:CC:DD:EE:FF',
savedAt: DateTime.fromMillisecondsSinceEpoch(1700000000000),
),
);
ChannelMessageStore().forgetArchive();
MessageStore().forgetArchive();
}
/// Restores the seeded radio into a connector that never connects.
Future<MeshCoreConnector> _connector(
WidgetTester tester, {
MessageFilterService? filter,
}) async {
final connector = MeshCoreConnector();
addTearDown(connector.dispose);
if (filter != null) {
final retry = MessageRetryService();
addTearDown(retry.dispose);
connector.initialize(
retryService: retry,
pathHistoryService: PathHistoryService(StorageService()),
messageFilterService: filter,
);
}
await tester.runAsync(connector.restoreLastRadio);
return connector;
}
Future<void> _pumpScreen(
WidgetTester tester,
MeshCoreConnector connector,
UiViewStateService viewState,
Widget home,
) async {
final storage = StorageService();
final settings = AppSettingsService();
await tester.runAsync(settings.loadSettings);
await tester.pumpWidget(
MultiProvider(
providers: [
ChangeNotifierProvider.value(value: connector),
ChangeNotifierProvider.value(value: MessageRetryService()),
ChangeNotifierProvider.value(value: PathHistoryService(storage)),
ChangeNotifierProvider.value(value: settings),
ChangeNotifierProvider.value(value: BleDebugLogService()),
ChangeNotifierProvider.value(value: AppDebugLogService()),
ChangeNotifierProvider.value(value: ChatTextScaleService()),
ChangeNotifierProvider.value(value: TranslationService(settings)),
ChangeNotifierProvider.value(value: viewState),
Provider.value(value: storage),
ChangeNotifierProvider.value(
value: MapTileCacheService(appSettingsService: settings),
),
ChangeNotifierProvider.value(value: TimeoutPredictionService(storage)),
ChangeNotifierProvider.value(value: ImageCodecService(settings)),
ChangeNotifierProvider.value(value: ReceivedImageStore()),
ChangeNotifierProvider.value(
value: NetworkMapUploadService(
connector: connector,
settings: settings,
),
),
],
child: MaterialApp(
theme: MeshTheme.light(),
locale: const Locale('en'),
localizationsDelegates: const [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: AppLocalizations.supportedLocales,
home: home,
),
),
);
for (var i = 0; i < 10; i++) {
await tester.pump(const Duration(milliseconds: 100));
}
}
/// [names] in the order they appear on screen, top to bottom.
List<String> _screenOrder(WidgetTester tester, List<String> names) {
final top = {
for (final name in names) name: tester.getTopLeft(find.text(name).first).dy,
};
return [...names]..sort((a, b) => top[a]!.compareTo(top[b]!));
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final tempDir = Directory.systemTemp.createTempSync('recency_sort_test');
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(
const MethodChannel('plugins.flutter.io/path_provider'),
(call) async => tempDir.path,
);
setUp(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
ChannelMessageStore().forgetArchive();
MessageStore().forgetArchive();
});
Future<void> pumpChannels(
WidgetTester tester, {
MessageFilterService? filter,
}) async {
final connector = await _connector(tester, filter: filter);
final viewState = UiViewStateService()
..setChannelsSortOption(ChannelSortOption.latestMessages);
await _pumpScreen(tester, connector, viewState, const ChannelsScreen());
}
Future<void> pumpContacts(WidgetTester tester) async {
final connector = await _connector(tester);
final viewState = UiViewStateService()
..setContactsSortOption(ContactSortOption.recentMessages);
await _pumpScreen(tester, connector, viewState, const ContactsScreen());
}
testWidgets('Latest messages sorts channels by local arrival, not sender '
'clocks far in the future or past', (tester) async {
await _seed(
channelMessages: {
// Oldest arrival, but the sender's clock is decades ahead.
'Future Clock': (slot) => [
_channelMessage(
slot,
'from the future',
sentAt: _farFuture,
receivedAt: _arrived(0),
),
],
// Newest arrival, but the sender's clock is decades behind.
'Past Clock': (slot) => [
_channelMessage(
slot,
'from the past',
sentAt: _farPast,
receivedAt: _arrived(2),
),
],
'Correct Clock': (slot) => [
_channelMessage(
slot,
'on time',
sentAt: _arrived(1),
receivedAt: _arrived(1),
),
],
'Quiet': (_) => [],
},
);
await pumpChannels(tester);
expect(
_screenOrder(tester, [
'Future Clock',
'Past Clock',
'Correct Clock',
'Quiet',
]),
['Past Clock', 'Correct Clock', 'Future Clock', 'Quiet'],
);
await tester.pumpWidget(const SizedBox());
});
testWidgets('A newer message hidden by the message filter does not bump '
'its channel', (tester) async {
await _seed(
channelMessages: {
'Spammed': (slot) => [
_channelMessage(
slot,
'real message',
sentAt: _arrived(0),
receivedAt: _arrived(0),
),
_channelMessage(
slot,
'buy now',
sentAt: _farFuture,
receivedAt: _arrived(5),
filterReason: 'rule',
),
],
'Normal': (slot) => [
_channelMessage(
slot,
'hello',
sentAt: _arrived(1),
receivedAt: _arrived(1),
),
],
},
);
final filter = MessageFilterService();
addTearDown(filter.dispose);
await tester.runAsync(filter.load);
await pumpChannels(tester, filter: filter);
expect(_screenOrder(tester, ['Spammed', 'Normal']), ['Normal', 'Spammed']);
await tester.pumpWidget(const SizedBox());
});
testWidgets('Channels with equal arrival times fall back to name order', (
tester,
) async {
List<ChannelMessage> same(int slot) => [
_channelMessage(slot, 'tie $slot', sentAt: _farFuture, receivedAt: _base),
];
await _seed(
channelMessages: {'Charlie': same, 'Alpha': same, 'Bravo': same},
);
await pumpChannels(tester);
expect(_screenOrder(tester, ['Charlie', 'Alpha', 'Bravo']), [
'Alpha',
'Bravo',
'Charlie',
]);
await tester.pumpWidget(const SizedBox());
});
testWidgets('Recent messages sorts contacts by local arrival, not sender '
'clocks far in the future or past', (tester) async {
await _seed(
contactMessages: {
'Fiona': (key) => [
_directMessage(
key,
'from the future',
sentAt: _farFuture,
receivedAt: _arrived(0),
),
],
'Paul': (key) => [
_directMessage(
key,
'from the past',
sentAt: _farPast,
receivedAt: _arrived(2),
),
],
'Carl': (key) => [
_directMessage(
key,
'on time',
sentAt: _arrived(1),
receivedAt: _arrived(1),
),
],
},
);
await pumpContacts(tester);
expect(_screenOrder(tester, ['Fiona', 'Paul', 'Carl']), [
'Paul',
'Carl',
'Fiona',
]);
await tester.pumpWidget(const SizedBox());
});
testWidgets('Contacts with equal arrival times fall back to name order', (
tester,
) async {
List<Message> same(Uint8List key) => [
_directMessage(key, 'tie', sentAt: _farPast, receivedAt: _base),
];
await _seed(contactMessages: {'Zed': same, 'Amy': same, 'Mo': same});
await pumpContacts(tester);
expect(_screenOrder(tester, ['Zed', 'Amy', 'Mo']), ['Amy', 'Mo', 'Zed']);
await tester.pumpWidget(const SizedBox());
});
testWidgets('Contact rows still open after the list was replaced by an '
'empty search result', (tester) async {
List<Message> none(Uint8List key) => [];
await _seed(
contactMessages: {
'Amy': none,
'Ben': none,
'Cal': none,
'Dee': none,
'Eve': none,
},
);
final connector = await _connector(tester);
final viewState = UiViewStateService();
await _pumpScreen(tester, connector, viewState, const ContactsScreen());
expect(find.text('Amy'), findsOneWidget);
viewState.setContactsSearchText('no such contact');
await tester.pumpAndSettle();
expect(find.text('Amy'), findsNothing);
viewState.setContactsSearchText('');
await tester.pumpAndSettle();
await tester.longPress(find.text('Amy'));
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
expect(find.byType(BottomSheet), findsOneWidget);
Navigator.of(tester.element(find.byType(BottomSheet))).pop();
await tester.pumpAndSettle();
await tester.tap(find.text('Amy'));
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
expect(find.byType(ChatScreen), findsOneWidget);
await tester.pumpWidget(const SizedBox());
});
}
+336
View File
@@ -0,0 +1,336 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:provider/provider.dart';
import 'package:provider/single_child_widget.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:meshcore_open/connector/meshcore_connector.dart';
import 'package:meshcore_open/connector/meshcore_protocol.dart';
import 'package:meshcore_open/l10n/app_localizations.dart';
import 'package:meshcore_open/models/contact.dart';
import 'package:meshcore_open/review_mode/review_frames.dart';
import 'package:meshcore_open/review_mode/review_radio.dart';
import 'package:meshcore_open/screens/chat_screen.dart';
import 'package:meshcore_open/services/app_debug_log_service.dart';
import 'package:meshcore_open/services/app_settings_service.dart';
import 'package:meshcore_open/services/ble_debug_log_service.dart';
import 'package:meshcore_open/services/chat_text_scale_service.dart';
import 'package:meshcore_open/services/image_codec_service.dart';
import 'package:meshcore_open/services/map_tile_cache_service.dart';
import 'package:meshcore_open/services/message_retry_service.dart';
import 'package:meshcore_open/services/path_history_service.dart';
import 'package:meshcore_open/services/received_image_store.dart';
import 'package:meshcore_open/services/storage_service.dart';
import 'package:meshcore_open/services/timeout_prediction_service.dart';
import 'package:meshcore_open/services/translation_service.dart';
import 'package:meshcore_open/services/ui_view_state_service.dart';
import 'package:meshcore_open/storage/message_store.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:meshcore_open/theme/mesh_theme.dart';
import 'package:meshcore_open/widgets/unread_divider.dart';
/// Room chats receive their backlog as a burst of messages right after login.
/// These tests feed such a burst into an open room chat and check that the
/// reader's place holds, and that opening the chat still lands where the
/// unread preference says.
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final tempDir = Directory.systemTemp.createTempSync('room_scroll_test');
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(
const MethodChannel('plugins.flutter.io/path_provider'),
(call) async => tempDir.path,
);
setUpAll(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
});
setUp(() {
final view =
TestWidgetsFlutterBinding.instance.platformDispatcher.views.first;
view.physicalSize = const Size(400, 800);
view.devicePixelRatio = 1.0;
});
tearDown(
() => TestWidgetsFlutterBinding.instance.platformDispatcher.views.first
.reset(),
);
testWidgets('a sync burst keeps the reader on the message they were '
'reading', (tester) async {
final (connector, room) = await _openRoom(tester, history: 60);
final controller = _listController(tester);
controller.jumpTo(1500);
await _settle(tester);
final reading = _lowestVisibleMessage(tester);
final before = tester.getTopLeft(reading).dy;
// One at a time, as the radio hands queued posts over, then a batch
// that lands within a single frame.
for (var i = 0; i < 5; i++) {
_receive(connector, room, 'synced single $i');
await tester.pump();
}
for (var i = 0; i < 25; i++) {
_receive(connector, room, 'synced batch $i');
}
await _settle(tester);
expect(connector.getMessages(room), hasLength(90));
expect(reading, findsOneWidget);
expect(tester.getTopLeft(reading).dy, moreOrLessEquals(before));
await _tearDown(tester);
});
testWidgets('a reader starting to scroll up during sync is not pulled '
'back to the newest message', (tester) async {
final (connector, room) = await _openRoom(tester, history: 60);
final controller = _listController(tester);
expect(controller.position.pixels, 0);
final gesture = await tester.startGesture(const Offset(200, 400));
for (var i = 0; i < 12; i++) {
await gesture.moveBy(const Offset(0, 25));
_receive(connector, room, 'during drag $i');
await tester.pump(const Duration(milliseconds: 16));
}
await gesture.up();
await _settle(tester);
expect(connector.getMessages(room), hasLength(72));
expect(controller.position.pixels, greaterThan(200));
await _tearDown(tester);
});
testWidgets('first open at the bottom still follows new messages', (
tester,
) async {
final (connector, room) = await _openRoom(tester, history: 60);
final controller = _listController(tester);
expect(controller.position.pixels, 0);
for (var i = 0; i < 5; i++) {
_receive(connector, room, 'newest $i');
await tester.pump();
}
await _settle(tester);
expect(connector.getMessages(room), hasLength(65));
expect(controller.position.pixels, 0);
expect(find.text('newest 4', findRichText: true), findsOneWidget);
await _tearDown(tester);
});
testWidgets('jump to oldest unread lands on the divider and holds through '
'a sync burst', (tester) async {
final (connector, room) = await _openRoom(
tester,
history: 60,
unread: 30,
jumpToOldestUnread: true,
);
final controller = _listController(tester);
// history 30 is the oldest of the 30 unread messages.
final anchor = find.text('history 30', findRichText: true);
expect(anchor, findsOneWidget);
expect(find.byType(UnreadDivider), findsOneWidget);
expect(controller.position.pixels, greaterThan(100));
final before = tester.getTopLeft(anchor).dy;
expect(before, inInclusiveRange(0, 800));
for (var i = 0; i < 10; i++) {
_receive(connector, room, 'after open $i');
await tester.pump();
}
await _settle(tester);
expect(connector.getMessages(room), hasLength(70));
expect(tester.getTopLeft(anchor).dy, moreOrLessEquals(before));
await _tearDown(tester);
});
testWidgets('older pages loaded in an open chat survive new messages', (
tester,
) async {
final (connector, room) = await _openRoom(tester, history: 230);
final window = connector.getMessages(room);
expect(window, hasLength(200));
final older = await tester.runAsync(
() => connector.loadOlderMessages(room.publicKeyHex),
);
expect(older, isNotEmpty);
final paged = connector.getMessages(room).length;
expect(paged, greaterThan(200));
_receive(connector, room, 'arrives while reading history');
await _settle(tester);
expect(connector.getMessages(room), hasLength(paged + 1));
expect(connector.getMessages(room).first.text, older!.first.text);
await _tearDown(tester);
});
testWidgets('an open chat still caps its window at the stored limit', (
tester,
) async {
final (connector, room) = await _openRoom(tester, history: 0);
for (var i = 0; i < MessageStore.maxStoredMessages + 10; i++) {
_receive(connector, room, 'flood $i');
}
final window = connector.getMessages(room);
expect(window, hasLength(MessageStore.maxStoredMessages));
expect(window.last.text, 'flood ${MessageStore.maxStoredMessages + 9}');
await _tearDown(tester);
});
}
var _timestamp = 1700000000;
void _receive(MeshCoreConnector connector, Contact room, String text) {
connector.handleFrameForTest(
ReviewFrames.contactMessage(
senderPublicKey: room.publicKey,
text: text,
timestampSecs: _timestamp++,
),
);
}
ScrollController _listController(WidgetTester tester) => tester
.widget<ListView>(find.byWidgetPredicate((w) => w is ListView))
.controller!;
/// The on-screen history message nearest the bottom of the list.
Finder _lowestVisibleMessage(WidgetTester tester) {
Finder? best;
var bestY = double.negativeInfinity;
for (var i = 0; i < 60; i++) {
final finder = find.text('history $i', findRichText: true);
if (finder.evaluate().isEmpty) continue;
final y = tester.getTopLeft(finder).dy;
if (y > 80 && y < 600 && y > bestY) {
bestY = y;
best = finder;
}
}
expect(best, isNotNull, reason: 'a history message should be on screen');
return best!;
}
Future<void> _settle(WidgetTester tester) async {
for (var i = 0; i < 10; i++) {
await tester.pump(const Duration(milliseconds: 100));
}
}
Future<void> _tearDown(WidgetTester tester) async {
await tester.pumpWidget(const SizedBox());
await tester.pump(const Duration(minutes: 1));
}
/// Connects the review radio, gives its room [history] messages and opens
/// the room chat as a login does, with [unread] of them unread.
Future<(MeshCoreConnector, Contact)> _openRoom(
WidgetTester tester, {
required int history,
int unread = 0,
bool jumpToOldestUnread = false,
}) async {
final (connector, providers, settings) = _shared ??= await _connect(tester);
await tester.runAsync(
() => settings.setJumpToOldestUnread(jumpToOldestUnread),
);
final room = connector.contacts.firstWhere((c) => c.type == advTypeRoom);
connector.clearMessagesForContact(room);
await tester.runAsync(() => connector.flushPendingWrites());
for (var i = 0; i < history; i++) {
_receive(connector, room, 'history $i');
}
expect(connector.getMessages(room), hasLength(history.clamp(0, 200)));
connector.markContactRead(room.publicKeyHex);
await tester.pumpWidget(
MultiProvider(
providers: providers,
child: MaterialApp(
theme: MeshTheme.light(),
locale: const Locale('en'),
localizationsDelegates: const [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: AppLocalizations.supportedLocales,
home: ChatScreen(contact: room, initialUnreadCount: unread),
),
),
);
await _settle(tester);
return (connector, room);
}
/// One review-radio connection shared by the tests: reconnecting it in the
/// same run does not resend the contact list.
(MeshCoreConnector, List<SingleChildWidget>, AppSettingsService)? _shared;
Future<(MeshCoreConnector, List<SingleChildWidget>, AppSettingsService)>
_connect(WidgetTester tester) async {
final storage = StorageService();
final connector = MeshCoreConnector();
final retry = MessageRetryService();
final settings = AppSettingsService();
final translation = TranslationService(settings);
await tester.runAsync(() async {
await settings.loadSettings();
connector.initialize(
retryService: retry,
pathHistoryService: PathHistoryService(storage),
appSettingsService: settings,
translationService: translation,
);
connector.reviewRadioFactoryForTest = () => ReviewRadio(
scheduledMessageInterval: const Duration(hours: 1),
ackDelay: const Duration(hours: 1),
replyDelay: const Duration(hours: 1),
);
await connector.connectReview();
final end = DateTime.now().add(const Duration(seconds: 8));
while (!connector.contacts.any((c) => c.type == advTypeRoom) &&
DateTime.now().isBefore(end)) {
await Future<void>.delayed(const Duration(milliseconds: 25));
}
// Let the connect-time message sync finish so test frames are not held.
await Future<void>.delayed(const Duration(milliseconds: 500));
});
expect(connector.contacts.any((c) => c.type == advTypeRoom), isTrue);
return (
connector,
<SingleChildWidget>[
ChangeNotifierProvider.value(value: connector),
ChangeNotifierProvider.value(value: retry),
ChangeNotifierProvider.value(value: PathHistoryService(storage)),
ChangeNotifierProvider.value(value: settings),
ChangeNotifierProvider.value(value: BleDebugLogService()),
ChangeNotifierProvider.value(value: AppDebugLogService()),
ChangeNotifierProvider.value(value: ChatTextScaleService()),
ChangeNotifierProvider.value(value: translation),
ChangeNotifierProvider.value(value: UiViewStateService()),
Provider.value(value: storage),
ChangeNotifierProvider.value(
value: MapTileCacheService(appSettingsService: settings),
),
ChangeNotifierProvider.value(value: TimeoutPredictionService(storage)),
ChangeNotifierProvider.value(value: ImageCodecService(settings)),
ChangeNotifierProvider.value(value: ReceivedImageStore()),
],
settings,
);
}
@@ -0,0 +1,601 @@
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:meshcore_open/connector/meshcore_connector.dart';
import 'package:meshcore_open/l10n/app_localizations.dart';
import 'package:meshcore_open/models/contact.dart';
import 'package:meshcore_open/models/custom_theme.dart';
import 'package:meshcore_open/models/send_attempt_plan.dart';
import 'package:meshcore_open/screens/app_settings_screen.dart';
import 'package:meshcore_open/screens/repeater_settings_screen.dart';
import 'package:meshcore_open/services/app_settings_service.dart';
import 'package:meshcore_open/services/network_map/network_map_upload_service.dart';
import 'package:meshcore_open/services/storage_service.dart';
import 'package:meshcore_open/services/translation_service.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:meshcore_open/theme/mesh_theme.dart';
import 'package:meshcore_open/widgets/mesh_ui.dart';
import 'package:meshcore_open/widgets/settings_reveal.dart';
void main() {
testWidgets(
'routing settings show both retry limits and reveal channel options',
(tester) async {
SharedPreferences.setMockInitialValues({});
await PrefsManager.initialize();
final settings = AppSettingsService();
await settings.loadSettings();
await settings.updateSettings(
settings.settings.copyWith(autoRouteRotationEnabled: false),
);
tester.view.physicalSize = const Size(800, 8000);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
final connector = MeshCoreConnector();
final translation = TranslationService(settings);
final uploads = NetworkMapUploadService(
connector: connector,
settings: settings,
);
addTearDown(connector.dispose);
addTearDown(translation.dispose);
addTearDown(uploads.dispose);
await tester.pumpWidget(
MultiProvider(
providers: [
ChangeNotifierProvider.value(value: settings),
ChangeNotifierProvider.value(value: connector),
ChangeNotifierProvider.value(value: translation),
ChangeNotifierProvider.value(value: uploads),
],
child: const MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: AppSettingsScreen(),
),
),
);
await tester.pumpAndSettle();
final context = tester.element(find.byType(AppSettingsScreen));
final l10n = AppLocalizations.of(context);
expect(find.text(l10n.appSettings_clearPathOnMaxRetry), findsOneWidget);
expect(
find.text(
l10n.appSettings_directRetries(SendAttemptPlan.defaultDirectRetries),
),
findsOneWidget,
);
expect(
find.text(
l10n.appSettings_floodRetries(SendAttemptPlan.defaultFloodRetries),
),
findsOneWidget,
);
expect(
find.text(
l10n.appSettings_loginAttempts(SendAttemptPlan.defaultLoginAttempts),
),
findsOneWidget,
);
// Retry limits stay visible while route rotation is off.
expect(find.text(l10n.appSettings_autoRouteRotation), findsOneWidget);
expect(find.text(l10n.appSettings_channelMinHopsCount(2)), findsNothing);
expect(find.text(l10n.appSettings_resetRoutingToDefault), findsOneWidget);
expect(
find.text(l10n.appSettings_repeatersAndRooms.toUpperCase()),
findsOneWidget,
);
expect(find.text(l10n.appSettings_clockSyncAfterLogin), findsOneWidget);
expect(
find.text(l10n.appSettings_loginPasswordAutofocus),
findsOneWidget,
);
expect(
find.text(l10n.appSettings_autoFetchRepeaterSettings),
findsOneWidget,
);
final channelSwitch = find.text(l10n.appSettings_channelMinHops);
await tester.tap(channelSwitch);
await tester.pump();
await tester.pump(RevealOnEnable.duration);
await tester.pumpAndSettle();
expect(
find.text(l10n.appSettings_channelMinHopsCount(2)),
findsOneWidget,
);
expect(
find.text(l10n.appSettings_channelMinHopsRetries(1)),
findsOneWidget,
);
await tester.tap(channelSwitch);
await tester.pumpAndSettle();
expect(find.text(l10n.appSettings_channelMinHopsCount(2)), findsNothing);
},
);
testWidgets(
'routing and repeaters/rooms rows and clock-sync selector have leading 24px icons with aligned titles',
(tester) async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
final settings = AppSettingsService();
await settings.loadSettings();
await settings.updateSettings(
settings.settings.copyWith(channelMinHopsEnabled: true),
);
tester.view.physicalSize = const Size(800, 8000);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
final connector = MeshCoreConnector();
final translation = TranslationService(settings);
final uploads = NetworkMapUploadService(
connector: connector,
settings: settings,
);
addTearDown(connector.dispose);
addTearDown(translation.dispose);
addTearDown(uploads.dispose);
await tester.pumpWidget(
MultiProvider(
providers: [
ChangeNotifierProvider.value(value: settings),
ChangeNotifierProvider.value(value: connector),
ChangeNotifierProvider.value(value: translation),
ChangeNotifierProvider.value(value: uploads),
],
child: MaterialApp(
theme: MeshTheme.light(),
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: const AppSettingsScreen(),
),
),
);
await tester.pumpAndSettle();
final context = tester.element(find.byType(AppSettingsScreen));
final l10n = AppLocalizations.of(context);
final topLevelTitles = [
l10n.appSettings_clearPathOnMaxRetry,
l10n.appSettings_directRetries(settings.settings.directRetries),
l10n.appSettings_floodRetries(settings.settings.floodRetries),
l10n.appSettings_autoRouteRotation,
l10n.appSettings_channelMinHops,
l10n.appSettings_resetRoutingToDefault,
l10n.appSettings_clockSyncAfterLogin,
l10n.appSettings_loginPasswordAutofocus,
l10n.appSettings_loginAttempts(settings.settings.loginAttempts),
l10n.appSettings_autoFetchRepeaterSettings,
l10n.appSettings_resetRepeaterRoomSettings,
];
final revealedTitles = [
l10n.appSettings_channelMinHopsCount(settings.settings.channelMinHops),
l10n.appSettings_channelMinHopsRetries(
settings.settings.channelMinHopsRetries,
),
l10n.appSettings_channelMinHopsCountRepeaters,
];
double expectRowLeadingIcon(String title) {
final titleFinder = find.text(title);
expect(titleFinder, findsOneWidget, reason: 'Missing row "$title"');
final tileFinder = find.ancestor(
of: titleFinder,
matching: find.byType(ListTile),
);
expect(tileFinder, findsOneWidget, reason: 'No ListTile for "$title"');
final iconFinder = find.descendant(
of: tileFinder,
matching: find.byType(Icon),
);
final icons = tester.widgetList<Icon>(iconFinder).toList();
final titleRect = tester.getRect(titleFinder);
final leadingIcons = [
for (var i = 0; i < icons.length; i++)
if (tester.getRect(iconFinder.at(i)).right < titleRect.left)
(icon: icons[i], rect: tester.getRect(iconFinder.at(i))),
];
expect(
leadingIcons,
hasLength(1),
reason: 'Expected 1 leading icon for "$title"',
);
expect(
leadingIcons.single.icon.size,
24,
reason: 'Leading icon for "$title" must be 24px',
);
expect(
leadingIcons.single.rect.size,
const Size(24, 24),
reason: 'Rendered leading icon for "$title" must be 24x24',
);
return titleRect.left;
}
final topTitleLefts = [
for (final title in topLevelTitles) expectRowLeadingIcon(title),
];
for (final left in topTitleLefts) {
expect(left, closeTo(topTitleLefts.first, 0.5));
}
final revealedTitleLefts = [
for (final title in revealedTitles) expectRowLeadingIcon(title),
];
for (final left in revealedTitleLefts) {
expect(left, closeTo(topTitleLefts.first + 16, 0.5));
}
// Check the Default / On / Off clock-sync selector on RepeaterSettingsScreen.
await tester.pumpWidget(
MultiProvider(
providers: [
ChangeNotifierProvider.value(value: connector),
ChangeNotifierProvider.value(value: settings),
],
child: MaterialApp(
theme: MeshTheme.light(),
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: RepeaterSettingsScreen(
repeater: Contact(
publicKey: Uint8List(32),
name: 'Repeater',
type: 2,
pathLength: 0,
path: Uint8List(0),
lastSeen: DateTime(2026),
),
password: 'x',
),
),
),
);
await tester.pump(const Duration(milliseconds: 500));
final rContext = tester.element(find.byType(RepeaterSettingsScreen));
final rL10n = AppLocalizations.of(rContext);
final selectorTitle = find.text(rL10n.repeater_clockSyncAfterLogin);
await tester.ensureVisible(selectorTitle);
await tester.pump();
expect(
find.byType(SegmentedButton<RepeaterClockSyncOverride>),
findsOneWidget,
);
for (final label in [
rL10n.repeater_clockSyncDefault,
rL10n.repeater_clockSyncOn,
rL10n.repeater_clockSyncOff,
]) {
expect(
find.byWidgetPredicate(
(w) => w is MeshSegmentLabel && w.text == label,
),
findsOneWidget,
);
}
final clockIconFinder = find.byIcon(Icons.schedule);
expect(clockIconFinder, findsOneWidget);
final clockIcon = tester.widget<Icon>(clockIconFinder);
expect(clockIcon.size, 24);
final clockIconRect = tester.getRect(clockIconFinder);
final selectorTitleRect = tester.getRect(selectorTitle);
expect(clockIconRect.size, const Size(24, 24));
expect(selectorTitleRect.left - clockIconRect.right, closeTo(16, 0.5));
},
);
for (final scale in [1.3, 2.0]) {
testWidgets(
'routing, repeaters/rooms, and clock-sync selector fit 320dp at ${scale}x',
(tester) async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
final settings = AppSettingsService();
await settings.loadSettings();
await settings.updateSettings(
settings.settings.copyWith(channelMinHopsEnabled: true),
);
tester.view.physicalSize = const Size(320, 568);
tester.view.devicePixelRatio = 1.0;
addTearDown(tester.view.reset);
final overflows = <String>[];
final previous = FlutterError.onError;
FlutterError.onError = (details) {
final text = details.exceptionAsString();
if (text.contains('overflowed')) {
overflows.add(text.split('\n').first);
} else {
previous?.call(details);
}
};
addTearDown(() => FlutterError.onError = previous);
final connector = MeshCoreConnector();
final translation = TranslationService(settings);
final uploads = NetworkMapUploadService(
connector: connector,
settings: settings,
);
addTearDown(connector.dispose);
addTearDown(translation.dispose);
addTearDown(uploads.dispose);
await tester.pumpWidget(
MultiProvider(
providers: [
ChangeNotifierProvider.value(value: settings),
ChangeNotifierProvider.value(value: connector),
ChangeNotifierProvider.value(value: translation),
ChangeNotifierProvider.value(value: uploads),
],
child: MaterialApp(
theme: MeshTheme.light(),
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
builder: (context, child) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(textScaler: TextScaler.linear(scale)),
child: child!,
),
home: const AppSettingsScreen(),
),
),
);
await tester.pumpAndSettle();
final context = tester.element(find.byType(AppSettingsScreen));
final l10n = AppLocalizations.of(context);
for (final label in [
l10n.appSettings_clearPathOnMaxRetry,
l10n.appSettings_directRetries(settings.settings.directRetries),
l10n.appSettings_floodRetries(settings.settings.floodRetries),
l10n.appSettings_channelMinHopsCount(
settings.settings.channelMinHops,
),
l10n.appSettings_channelMinHopsRetries(
settings.settings.channelMinHopsRetries,
),
l10n.appSettings_channelMinHopsCountRepeaters,
l10n.appSettings_resetRoutingToDefault,
l10n.appSettings_clockSyncAfterLogin,
l10n.appSettings_loginPasswordAutofocus,
l10n.appSettings_loginAttempts(settings.settings.loginAttempts),
l10n.appSettings_autoFetchRepeaterSettings,
l10n.appSettings_resetRepeaterRoomSettings,
]) {
await tester.scrollUntilVisible(
find.text(label),
200,
maxScrolls: 100,
scrollable: find.byType(Scrollable).first,
);
await tester.pump();
expect(find.text(label), findsOneWidget);
}
await tester.pumpWidget(
MultiProvider(
providers: [
ChangeNotifierProvider.value(value: connector),
ChangeNotifierProvider.value(value: settings),
],
child: MaterialApp(
theme: MeshTheme.light(),
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
builder: (context, child) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(textScaler: TextScaler.linear(scale)),
child: child!,
),
home: RepeaterSettingsScreen(
repeater: Contact(
publicKey: Uint8List(32),
name: 'Repeater',
type: 2,
pathLength: 0,
path: Uint8List(0),
lastSeen: DateTime(2026),
),
password: 'x',
),
),
),
);
await tester.pump(const Duration(milliseconds: 500));
final rContext = tester.element(find.byType(RepeaterSettingsScreen));
final rL10n = AppLocalizations.of(rContext);
await tester.scrollUntilVisible(
find.text(rL10n.repeater_clockSyncAfterLogin),
200,
scrollable: find.byType(Scrollable).first,
);
await tester.pump();
expect(find.text(rL10n.repeater_clockSyncAfterLogin), findsOneWidget);
expect(
find.byWidgetPredicate(
(w) =>
w is MeshSegmentLabel &&
w.text == rL10n.repeater_clockSyncDefault,
),
findsOneWidget,
);
FlutterError.onError = previous;
expect(overflows, isEmpty, reason: overflows.join('\n'));
},
);
}
for (final entry in <(String, ThemeData)>[
('light', MeshTheme.light()),
('dark', MeshTheme.dark()),
for (final preset in [
...CustomTheme.presets,
...CustomTheme.holidayPresets,
])
('custom:${preset.name}', MeshTheme.fromCustom(preset)),
]) {
testWidgets(
'slider inactive track, tick marks, and drag bubble contrast inside SettingsReveal and MeshCard (${entry.$1})',
(tester) async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
final settings = AppSettingsService();
await settings.loadSettings();
await settings.updateSettings(
settings.settings.copyWith(channelMinHopsEnabled: true),
);
tester.view.physicalSize = const Size(800, 8000);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
final connector = MeshCoreConnector();
final translation = TranslationService(settings);
final uploads = NetworkMapUploadService(
connector: connector,
settings: settings,
);
addTearDown(connector.dispose);
addTearDown(translation.dispose);
addTearDown(uploads.dispose);
await tester.pumpWidget(
MultiProvider(
providers: [
ChangeNotifierProvider.value(value: settings),
ChangeNotifierProvider.value(value: connector),
ChangeNotifierProvider.value(value: translation),
ChangeNotifierProvider.value(value: uploads),
],
child: MaterialApp(
theme: entry.$2,
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: const AppSettingsScreen(),
),
),
);
await tester.pumpAndSettle();
final screenContext = tester.element(find.byType(AppSettingsScreen));
final l10n = AppLocalizations.of(screenContext);
final scheme = entry.$2.colorScheme;
final revealFinder = find.byType(SettingsReveal).first;
final revealMaterial = tester.widget<Material>(
find
.descendant(of: revealFinder, matching: find.byType(Material))
.first,
);
final revealBg = revealMaterial.color!;
expect(revealBg, scheme.surfaceContainerHighest);
final directRowFinder = find.ancestor(
of: find.text(
l10n.appSettings_directRetries(settings.settings.directRetries),
),
matching: find.byType(SettingsValueSlider),
);
final directCardMaterial = tester.widget<Material>(
find
.ancestor(of: directRowFinder, matching: find.byType(Material))
.first,
);
final cardBg = directCardMaterial.color!;
expect(cardBg, scheme.surfaceContainerLow);
final hopsRowFinder = find.ancestor(
of: find.text(
l10n.appSettings_channelMinHopsCount(
settings.settings.channelMinHops,
),
),
matching: find.byType(SettingsValueSlider),
);
final revealedSliderFinder = find.descendant(
of: hopsRowFinder,
matching: find.byType(Slider),
);
final directSliderFinder = find.descendant(
of: directRowFinder,
matching: find.byType(Slider),
);
for (final sliderFinder in [revealedSliderFinder, directSliderFinder]) {
final sliderContext = tester.element(sliderFinder);
final sliderTheme = SliderTheme.of(sliderContext);
final inactiveTrack = sliderTheme.inactiveTrackColor!;
final inactiveTick = sliderTheme.inactiveTickMarkColor!;
final activeTick = sliderTheme.activeTickMarkColor!;
final valueIndicator = sliderTheme.valueIndicatorColor!;
expect(inactiveTrack.a, 1.0);
expect(inactiveTrack, isNot(revealBg));
expect(inactiveTrack, isNot(cardBg));
expect(
meshContrastRatio(inactiveTrack, revealBg),
greaterThanOrEqualTo(2.1),
reason: 'Inactive track must stand out on SettingsReveal',
);
expect(
meshContrastRatio(inactiveTrack, cardBg),
greaterThanOrEqualTo(2.5),
reason: 'Inactive track must stand out on MeshCard',
);
expect(
meshContrastRatio(inactiveTick, inactiveTrack),
greaterThanOrEqualTo(2.5),
reason: 'Inactive tick marks must stand out on inactive track',
);
expect(
meshContrastRatio(activeTick, sliderTheme.activeTrackColor!),
greaterThanOrEqualTo(1.8),
reason: 'Active tick marks must stand out on active track',
);
expect(
meshContrastRatio(valueIndicator, revealBg),
greaterThanOrEqualTo(3.0),
reason: 'Drag bubble must stand out on SettingsReveal',
);
expect(
meshContrastRatio(valueIndicator, cardBg),
greaterThanOrEqualTo(3.0),
reason: 'Drag bubble must stand out on MeshCard',
);
}
},
);
}
}
+87 -2
View File
@@ -12,9 +12,17 @@ import 'package:shared_preferences/shared_preferences.dart';
import 'package:meshcore_open/connector/meshcore_connector.dart';
import 'package:meshcore_open/connector/meshcore_protocol.dart';
import 'package:meshcore_open/games/chess/chess_game.dart';
import 'package:meshcore_open/games/chess/chess_link.dart';
import 'package:meshcore_open/games/chess/chess_packets.dart';
import 'package:meshcore_open/games/chess/chess_service.dart';
import 'package:meshcore_open/games/chess/ui/chess_game_screen.dart';
import 'package:meshcore_open/games/chess/ui/chess_games_sheet.dart';
import 'package:meshcore_open/games/hash_chain.dart';
import 'package:meshcore_open/l10n/app_localizations.dart';
import 'package:meshcore_open/models/contact.dart';
import 'package:meshcore_open/review_mode/review_radio.dart';
import 'package:meshcore_open/screens/add_contact_screen.dart';
import 'package:meshcore_open/screens/app_debug_log_screen.dart';
import 'package:meshcore_open/screens/app_settings_screen.dart';
import 'package:meshcore_open/screens/ble_debug_log_screen.dart';
@@ -25,6 +33,7 @@ import 'package:meshcore_open/screens/chat_screen.dart';
import 'package:meshcore_open/screens/chrome_required_screen.dart';
import 'package:meshcore_open/screens/companion_radio_stats_screen.dart';
import 'package:meshcore_open/screens/contacts_screen.dart';
import 'package:meshcore_open/screens/coordinate_map_screen.dart';
import 'package:meshcore_open/screens/discovery_screen.dart';
import 'package:meshcore_open/screens/line_of_sight_map_screen.dart';
import 'package:meshcore_open/screens/map_cache_screen.dart';
@@ -79,8 +88,13 @@ Future<_Env> _connect(WidgetTester tester) async {
final retry = MessageRetryService();
final settings = AppSettingsService();
final translation = TranslationService(settings);
final chess = ChessService(
link: ConnectorChessLink(connector, settings: settings),
startHousekeeping: false,
);
final env = _Env(connector, [
ChangeNotifierProvider.value(value: connector),
ChangeNotifierProvider.value(value: chess),
ChangeNotifierProvider.value(value: retry),
ChangeNotifierProvider.value(value: PathHistoryService(storage)),
ChangeNotifierProvider.value(value: settings),
@@ -120,9 +134,60 @@ Future<_Env> _connect(WidgetTester tester) async {
await Future<void>.delayed(const Duration(milliseconds: 25));
}
});
_seedChessGames(chess, connector.channels.first.storageId!);
return env;
}
const _chessGameId = 77;
/// A game in progress (long names, a few moves) and an open invite.
void _seedChessGames(ChessService chess, String channelId) {
void feed(ChessPacket p) =>
chess.handleIncoming(ChessIncoming(channelId, p.encode()));
final white = HashChain(Uint8List(16));
final black = HashChain(Uint8List(16)..[0] = 1);
feed(
ChessInfoPacket(
gameId: _chessGameId,
ply: 0,
startedAtUnix: 1700000000,
deadline: ChessDeadline.hour1,
whiteCommitment: white.commitment,
blackCommitment: black.commitment,
inviterValue: white.valueAt(1),
whiteName: 'Alexandra the Long-Named',
blackName: 'Bartholomew Repeater Fan',
),
);
final game = chess.game(channelId, _chessGameId)!;
for (final (i, uci) in ['e2e4', 'e7e5', 'g1f3'].indexed) {
final probe = ChessGame.fromJson(game.toJson())!;
final index = probe.legalUci().indexOf(uci);
probe.applyUci(uci);
feed(
ChessMovePacket(
gameId: _chessGameId,
ply: i + 1,
moveIndex: index,
// White invited, so its value 1 belongs to the game info.
chainValue: i.isEven
? white.valueAt(i ~/ 2 + 2)
: black.valueAt(i ~/ 2 + 1),
position: probe.packedPosition(),
),
);
}
feed(
ChessInvitePacket(
gameId: 78,
deadline: ChessDeadline.day1,
colour: ChessColourPreference.random,
commitment: HashChain(Uint8List(16)..[0] = 2).commitment,
inviterName: 'Cornelius Openinvite',
),
);
}
Contact _contactOfType(MeshCoreConnector c, int type) => c.contacts.firstWhere(
(x) => x.type == type,
orElse: () => c.contacts.first,
@@ -145,10 +210,18 @@ _interactions = {
.first,
);
},
'Contacts add sheet': (t, _) async {
'Contacts add page': (t, _) async {
await t.tap(find.byType(FloatingActionButton));
},
// Four routing modes (Auto, Flood, Direct, Manual) share one row.
'Chess games sheet': (t, c) async {
unawaited(
showChessGamesSheet(
t.element(find.byType(ChannelChatScreen)),
c.channels.first,
),
);
},
'Routing sheet': (t, c) async {
unawaited(
ContactRoutingSheet.show(
@@ -161,7 +234,8 @@ _interactions = {
final Map<String, _ScreenBuilder> _screens = {
'Contacts options sheet': (_) => const ContactsScreen(),
'Contacts add sheet': (_) => const ContactsScreen(),
'Contacts add page': (_) => const ContactsScreen(),
'AddContact': (_) => const AddContactScreen(),
'Routing sheet': (c) => ChatScreen(contact: _contactOfType(c, advTypeChat)),
'Scanner': (_) => const ScannerScreen(),
'Tcp': (_) => const TcpScreen(),
@@ -180,6 +254,11 @@ final Map<String, _ScreenBuilder> _screens = {
'Map': (_) => const MapScreen(),
'Chat': (c) => ChatScreen(contact: _contactOfType(c, advTypeChat)),
'ChannelChat': (c) => ChannelChatScreen(channel: c.channels.first),
'Chess games sheet': (c) => ChannelChatScreen(channel: c.channels.first),
'ChessGame': (c) => ChessGameScreen(
channelId: c.channels.first.storageId!,
gameId: _chessGameId,
),
'ChannelMessagePath': (c) {
final msgs = c.getChannelMessages(c.channels.first);
return ChannelMessagePathScreen(message: msgs.last);
@@ -221,6 +300,11 @@ final Map<String, _ScreenBuilder> _screens = {
LineOfSightEndpoint(label: 'B', point: LatLng(45.6, -122.7)),
],
),
'CoordinateMap': (_) => const CoordinateMapScreen(
latitude: 45.515232,
longitude: -122.678385,
label: '45.515232, -122.678385',
),
};
void main() {
@@ -253,6 +337,7 @@ void main() {
'Map',
'Chat',
'ChannelChat',
'ChessGame',
'Settings',
}.contains(entry.key))
(entry, true),
@@ -0,0 +1,15 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/services/background_service.dart';
void main() {
test('the foreground service does not stop when the app goes to the '
'background', () {
// flutter_foreground_task's stopWithTask option stops the service on the
// first activity pause, not on task removal. Swipe-away is handled by
// android:stopWithTask in the manifest instead.
final options = BackgroundService.taskOptions;
expect(options.stopWithTask, isNull);
expect(options.toJson().containsKey('stopWithTask'), isFalse);
expect(options.allowAutoRestart, isFalse);
});
}
+26
View File
@@ -132,6 +132,32 @@ void main() {
},
);
test('keeps contact added times out of app settings', () async {
SharedPreferences.setMockInitialValues({
'app_settings': jsonEncode({'theme_mode': 'dark'}),
'contact_added_at_0011223344': jsonEncode({'aa': 1}),
});
PrefsManager.reset();
await PrefsManager.initialize();
addTearDown(PrefsManager.reset);
final connector = MeshCoreConnector();
addTearDown(connector.dispose);
final json = await const BackupService().createBackup(
items: {BackupItem.appSettings},
connector: connector,
settings: AppSettings(),
password: '',
);
final payload = jsonDecode(json) as Map<String, dynamic>;
final section =
(payload['sections'] as Map<String, dynamic>)['appSettings']
as Map<String, dynamic>;
final preferences = section['preferences'] as Map<String, dynamic>;
expect(preferences, contains('app_settings'));
expect(preferences, isNot(contains('contact_added_at_0011223344')));
});
test('backs up a sensitive key without unrelated app settings', () async {
SharedPreferences.setMockInitialValues({
'app_settings': jsonEncode({
@@ -0,0 +1,35 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/models/image_codec_support.dart';
import 'package:meshcore_open/services/app_settings_service.dart';
import 'package:meshcore_open/services/image_codec_backend.dart';
import 'package:meshcore_open/services/image_codec_service.dart';
import 'package:meshcore_open/services/image_codec_settings_store.dart';
import 'package:meshcore_open/widgets/image_send_codec_binding.dart';
/// Runs in both build modes; each half skips in the other (`scripts/onnx.sh`).
void main() {
ImageCodecService newService() {
final service = ImageCodecService(
AppSettingsService(),
settingsStore: InMemoryImageCodecSettingsStore(
const ImageCodecPreferences(enabled: true),
),
);
addTearDown(service.dispose);
return service;
}
test('ONNX-free build reports the image codec unavailable', () {
final service = newService();
expect(createImageCodecBackend(), isNull);
expect(service.availability, ImageCodecAvailability.unavailable);
expect(service.unavailableReason, contains('without ONNX Runtime'));
expect(service.canRunInference, isFalse);
}, skip: imageCodecRuntimeAvailable ? 'ONNX Runtime is compiled in' : false);
test('ONNX build has a codec backend', () {
final service = newService();
expect(createImageCodecBackend(), isA<OnnxImageCodecBackend>());
expect(service.unavailableReason, isNull);
}, skip: imageCodecRuntimeAvailable ? false : 'built without ONNX Runtime');
}
@@ -0,0 +1,286 @@
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:meshcore_open/models/contact.dart';
import 'package:meshcore_open/models/message.dart';
import 'package:meshcore_open/models/path_selection.dart';
import 'package:meshcore_open/services/app_settings_service.dart';
import 'package:meshcore_open/services/message_retry_service.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
Contact _contact({int pathLength = 1, List<int> path = const [0x11]}) =>
Contact(
publicKey: Uint8List.fromList(List<int>.generate(32, (i) => i + 1)),
name: 'Test',
type: 1,
pathLength: pathLength,
path: Uint8List.fromList(path),
lastSeen: DateTime.now(),
);
void main() {
setUp(() async {
SharedPreferences.setMockInitialValues({});
await PrefsManager.initialize();
});
test('rotation sends direct attempts, then flood, then stops', () async {
final settings = AppSettingsService();
await settings.loadSettings();
await settings.updateSettings(
settings.settings.copyWith(
autoRouteRotationEnabled: true,
directRetries: 1,
floodRetries: 1,
),
);
final service = MessageRetryService(
sentWatchdogGrace: const Duration(milliseconds: 5),
);
addTearDown(service.dispose);
final sends = <int>[];
final thresholds = <int>[];
service.initialize(
RetryServiceConfig(
sendMessage: (_, _, attempt, _) async {
sends.add(attempt);
},
addMessage: (_, _) {},
updateMessage: (_) {},
calculateTimeout: (_, _, {String? contactKey, int? deviceTimeoutMs}) =>
15,
appSettingsService: settings,
selectRetryPath: (_, attemptIndex, directRetries, _) {
thresholds.add(directRetries);
if (attemptIndex >= directRetries) {
return const PathSelection(
pathBytes: [],
hopCount: -1,
useFlood: true,
);
}
return const PathSelection(
pathBytes: [0x22],
hopCount: 1,
useFlood: false,
);
},
),
);
await service.sendMessageWithRetry(contact: _contact(), text: 'hello');
await pumpEventQueue();
await Future<void>.delayed(const Duration(milliseconds: 1400));
expect(sends, [0, 1]);
expect(thresholds, [1, 1]);
});
test('rotation off keeps retrying a direct path without flooding', () async {
final settings = AppSettingsService();
await settings.loadSettings();
await settings.updateSettings(
settings.settings.copyWith(
autoRouteRotationEnabled: false,
directRetries: 2,
floodRetries: 5,
),
);
final service = MessageRetryService(
sentWatchdogGrace: const Duration(milliseconds: 5),
);
addTearDown(service.dispose);
final sends = <int>[];
var picked = false;
service.initialize(
RetryServiceConfig(
sendMessage: (_, _, attempt, _) async {
sends.add(attempt);
},
addMessage: (_, _) {},
updateMessage: (_) {},
calculateTimeout: (_, _, {String? contactKey, int? deviceTimeoutMs}) =>
15,
appSettingsService: settings,
selectRetryPath: (_, _, _, _) {
picked = true;
return const PathSelection(
pathBytes: [],
hopCount: -1,
useFlood: true,
);
},
),
);
await service.sendMessageWithRetry(contact: _contact(), text: 'hello');
await pumpEventQueue();
await Future<void>.delayed(const Duration(milliseconds: 1400));
expect(sends, [0, 1]);
expect(picked, isFalse);
});
test('a flood path without rotation stops after the flood budget', () async {
final settings = AppSettingsService();
await settings.loadSettings();
await settings.updateSettings(
settings.settings.copyWith(
autoRouteRotationEnabled: false,
directRetries: 4,
floodRetries: 1,
),
);
final service = MessageRetryService(
sentWatchdogGrace: const Duration(milliseconds: 5),
);
addTearDown(service.dispose);
final latest = <Message>[];
final sends = <int>[];
service.initialize(
RetryServiceConfig(
sendMessage: (_, _, attempt, _) async {
sends.add(attempt);
},
addMessage: (_, message) => latest.add(message),
updateMessage: (message) => latest.add(message),
calculateTimeout: (_, _, {String? contactKey, int? deviceTimeoutMs}) =>
15,
appSettingsService: settings,
),
);
await service.sendMessageWithRetry(
contact: _contact(pathLength: -1, path: const []),
text: 'hello',
);
await pumpEventQueue();
await Future<void>.delayed(const Duration(milliseconds: 200));
expect(sends, [0]);
expect(latest.last.status, MessageStatus.failed);
});
test(
'flood-only rotation floods saved direct contact even if selector returns null',
() async {
final settings = AppSettingsService();
await settings.loadSettings();
await settings.updateSettings(
settings.settings.copyWith(
autoRouteRotationEnabled: true,
directRetries: 0,
floodRetries: 1,
),
);
final service = MessageRetryService(
sentWatchdogGrace: const Duration(milliseconds: 5),
);
addTearDown(service.dispose);
final latest = <Message>[];
final sends = <int>[];
var clearedCount = 0;
var setPathCount = 0;
service.initialize(
RetryServiceConfig(
sendMessage: (_, _, attempt, _) async {
sends.add(attempt);
},
addMessage: (_, message) => latest.add(message),
updateMessage: (message) => latest.add(message),
clearContactPath: (_) async {
clearedCount++;
},
setContactPath: (_, _, _) async {
setPathCount++;
},
calculateTimeout:
(_, _, {String? contactKey, int? deviceTimeoutMs}) => 15,
appSettingsService: settings,
selectRetryPath: (_, _, _, _) => null,
),
);
await service.sendMessageWithRetry(
contact: _contact(pathLength: 1, path: const [0x11]),
text: 'hello',
);
await pumpEventQueue();
await Future<void>.delayed(const Duration(milliseconds: 200));
expect(sends, [0]);
expect(clearedCount, 1);
expect(setPathCount, 0);
expect(latest.last.pathLength, -1);
expect(latest.last.pathBytes, isEmpty);
expect(latest.last.status, MessageStatus.failed);
},
);
test(
'rotation with direct attempts > 0 tries direct paths before flooding',
() async {
final settings = AppSettingsService();
await settings.loadSettings();
await settings.updateSettings(
settings.settings.copyWith(
autoRouteRotationEnabled: true,
directRetries: 2,
floodRetries: 1,
),
);
final service = MessageRetryService(
sentWatchdogGrace: const Duration(milliseconds: 5),
);
addTearDown(service.dispose);
final actions = <String>[];
final sends = <int>[];
service.initialize(
RetryServiceConfig(
sendMessage: (_, _, attempt, _) async {
sends.add(attempt);
},
addMessage: (_, _) {},
updateMessage: (_) {},
clearContactPath: (_) async => actions.add('flood'),
setContactPath: (_, bytes, _) async =>
actions.add('direct:${bytes.join(',')}'),
calculateTimeout:
(_, _, {String? contactKey, int? deviceTimeoutMs}) => 15,
appSettingsService: settings,
selectRetryPath: (_, attemptIndex, directRetries, _) {
if (attemptIndex >= directRetries) return null;
return attemptIndex == 0
? const PathSelection(
pathBytes: [0x22],
hopCount: 1,
useFlood: false,
)
: const PathSelection(
pathBytes: [0x33],
hopCount: 1,
useFlood: false,
);
},
),
);
await service.sendMessageWithRetry(
contact: _contact(pathLength: 1, path: const [0x11]),
text: 'hello',
);
await pumpEventQueue();
await Future<void>.delayed(const Duration(milliseconds: 3500));
expect(sends, [0, 1, 2]);
expect(actions, ['direct:34', 'direct:51', 'flood']);
},
);
}
+10 -2
View File
@@ -56,7 +56,12 @@ void main() {
);
test('missing RESP_CODE_SENT times out and retries', () async {
await service.sendMessageWithRetry(contact: _contact(), text: 'hello');
// A direct path uses the direct budget (default 4). A flood path would
// stop after the default single flood attempt.
await service.sendMessageWithRetry(
contact: _contact(pathLength: 1, path: const [0x11]),
text: 'hello',
);
await pumpEventQueue();
expect(sends.map((s) => s.attempt), [0]);
@@ -80,7 +85,10 @@ void main() {
});
test('late ACK for an attempt whose SENT was lost still delivers', () async {
await service.sendMessageWithRetry(contact: _contact(), text: 'hello');
await service.sendMessageWithRetry(
contact: _contact(pathLength: 1, path: const [0x11]),
text: 'hello',
);
await pumpEventQueue();
// Let the watchdog fire; the retry is now waiting on its backoff.
@@ -0,0 +1,194 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/services/notification_service.dart';
class _NoopNotificationsPlatform extends FlutterLocalNotificationsPlatform {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
const channel = MethodChannel('dexterous.com/flutter/local_notifications');
final service = NotificationService();
setUp(() {
service.resetForTest();
debugDefaultTargetPlatformOverride = null;
});
tearDown(() {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(channel, null);
FlutterLocalNotificationsPlatform.instance = _NoopNotificationsPlatform();
debugDefaultTargetPlatformOverride = null;
service.resetForTest();
});
group('NotificationService.hasNotificationPermission', () {
test('queries Android areNotificationsEnabled and updates cache', () async {
debugDefaultTargetPlatformOverride = TargetPlatform.android;
AndroidFlutterLocalNotificationsPlugin.registerWith();
bool? androidEnabled = true;
var checkCalls = 0;
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(channel, (call) async {
if (call.method == 'initialize') return true;
if (call.method == 'areNotificationsEnabled') {
checkCalls++;
return androidEnabled;
}
return null;
});
expect(await service.hasNotificationPermission(), isTrue);
expect(service.canNotifyCacheForTest, isTrue);
expect(checkCalls, 1);
// Subsequent ensureCanNotify uses the cached grant without re-querying.
expect(await service.ensureCanNotifyForTest(), isTrue);
expect(checkCalls, 1);
// Revoking OS permission invalidates the cached true on the next live check.
androidEnabled = false;
expect(await service.hasNotificationPermission(), isFalse);
expect(service.canNotifyCacheForTest, isNull);
expect(checkCalls, 2);
// _ensureCanNotify now re-queries and returns false instead of stale true.
expect(await service.ensureCanNotifyForTest(), isFalse);
expect(checkCalls, 3);
// Null response from channel is treated as false.
androidEnabled = null;
expect(await service.hasNotificationPermission(), isFalse);
expect(service.canNotifyCacheForTest, isNull);
});
test(
'queries iOS checkPermissions and invalidates cache when revoked',
() async {
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
IOSFlutterLocalNotificationsPlugin.registerWith();
Map<String, Object?>? permissionsResponse = {
'isEnabled': true,
'isAlertEnabled': true,
'isBadgeEnabled': true,
'isSoundEnabled': true,
'isProvisionalEnabled': false,
'isCriticalEnabled': false,
'isProvidesAppNotificationSettingsEnabled': false,
'isCarPlayEnabled': false,
};
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(channel, (call) async {
if (call.method == 'initialize') return true;
if (call.method == 'checkPermissions') return permissionsResponse;
return null;
});
expect(await service.hasNotificationPermission(), isTrue);
expect(service.canNotifyCacheForTest, isTrue);
expect(await service.ensureCanNotifyForTest(), isTrue);
// Provisional permission also counts as granted.
permissionsResponse = {
'isEnabled': false,
'isAlertEnabled': false,
'isBadgeEnabled': false,
'isSoundEnabled': false,
'isProvisionalEnabled': true,
};
expect(await service.hasNotificationPermission(), isTrue);
expect(service.canNotifyCacheForTest, isTrue);
// Denied in iOS Settings clears the cached grant.
permissionsResponse = {
'isEnabled': false,
'isAlertEnabled': false,
'isBadgeEnabled': false,
'isSoundEnabled': false,
'isProvisionalEnabled': false,
};
expect(await service.hasNotificationPermission(), isFalse);
expect(service.canNotifyCacheForTest, isNull);
expect(await service.ensureCanNotifyForTest(), isFalse);
permissionsResponse = null;
expect(await service.hasNotificationPermission(), isFalse);
},
);
test('queries macOS checkPermissions and updates cache', () async {
debugDefaultTargetPlatformOverride = TargetPlatform.macOS;
MacOSFlutterLocalNotificationsPlugin.registerWith();
Map<String, Object?>? permissionsResponse = {
'isEnabled': true,
'isAlertEnabled': true,
'isBadgeEnabled': true,
'isSoundEnabled': true,
};
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(channel, (call) async {
if (call.method == 'initialize') return true;
if (call.method == 'checkPermissions') return permissionsResponse;
return null;
});
expect(await service.hasNotificationPermission(), isTrue);
expect(service.canNotifyCacheForTest, isTrue);
permissionsResponse = {
'isEnabled': false,
'isAlertEnabled': false,
'isBadgeEnabled': false,
'isSoundEnabled': false,
};
expect(await service.hasNotificationPermission(), isFalse);
expect(service.canNotifyCacheForTest, isNull);
});
test(
'returns true on desktop platforms without an OS permission gate',
() async {
debugDefaultTargetPlatformOverride = TargetPlatform.linux;
FlutterLocalNotificationsPlatform.instance =
_NoopNotificationsPlatform();
expect(await service.hasNotificationPermission(), isTrue);
expect(service.canNotifyCacheForTest, isTrue);
},
);
test('requestPermissions updates and clears canNotify cache', () async {
debugDefaultTargetPlatformOverride = TargetPlatform.android;
AndroidFlutterLocalNotificationsPlugin.registerWith();
var grantResult = true;
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(channel, (call) async {
if (call.method == 'initialize') return true;
if (call.method == 'requestNotificationsPermission') {
return grantResult;
}
if (call.method == 'areNotificationsEnabled') {
return grantResult;
}
return null;
});
expect(await service.requestPermissions(), isTrue);
expect(service.canNotifyCacheForTest, isTrue);
grantResult = false;
expect(await service.requestPermissions(), isFalse);
expect(service.canNotifyCacheForTest, isNull);
expect(await service.ensureCanNotifyForTest(), isFalse);
});
});
}
+19 -12
View File
@@ -121,7 +121,7 @@ void main() {
final pick = svc.selectPathForAttempt(
pubKey,
attemptIndex: attemptIndex,
maxRetries: 5,
directRetries: 4,
recentSelections: recent,
);
final key = pick.useFlood
@@ -139,7 +139,7 @@ void main() {
final selection = svc.selectPathForAttempt(
pubKey,
attemptIndex: 0,
maxRetries: 5,
directRetries: 4,
);
expect(selection.useFlood, isTrue);
});
@@ -150,7 +150,7 @@ void main() {
final selection = svc.selectPathForAttempt(
pubKey,
attemptIndex: 0,
maxRetries: 0,
directRetries: 0,
);
expect(selection.useFlood, isTrue);
});
@@ -163,7 +163,7 @@ void main() {
final selection = svc.selectPathForAttempt(
pubKey,
attemptIndex: i,
maxRetries: 5,
directRetries: 4,
);
expect(
selection.useFlood,
@@ -274,7 +274,7 @@ void main() {
final pick = svc.selectPathForAttempt(
pubKey,
attemptIndex: 0,
maxRetries: 5,
directRetries: 4,
);
expect(pick.useFlood, isFalse);
expect(pick.hopCount, 0);
@@ -299,21 +299,28 @@ void main() {
expect(resolved.pathBytes, isEmpty);
});
test('final attempt is always flood regardless of known paths', () async {
test('attempts at and after directRetries flood', () async {
final pubKey = _hex('ef01');
await _seed(svc, pubKey, pathBytes: [0x01], hopCount: 1);
for (final retries in [1, 2, 5, 10]) {
final lastAttempt = svc.selectPathForAttempt(
for (final direct in [0, 1, 4, 9]) {
final flooded = svc.selectPathForAttempt(
pubKey,
attemptIndex: retries - 1,
maxRetries: retries,
attemptIndex: direct,
directRetries: direct,
);
expect(
lastAttempt.useFlood,
flooded.useFlood,
isTrue,
reason: 'maxRetries=$retries: last attempt must be flood',
reason: 'directRetries=$direct: that attempt floods',
);
if (direct == 0) continue;
final routed = svc.selectPathForAttempt(
pubKey,
attemptIndex: direct - 1,
directRetries: direct,
);
expect(routed.useFlood, isFalse);
}
});
});
@@ -0,0 +1,81 @@
import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:meshcore_open/services/storage_service.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
void main() {
setUp(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
});
test('a saved on or off overrides the global clock-sync default', () async {
SharedPreferences.setMockInitialValues({
'repeater_auto_clock_sync_after_login': jsonEncode({
'on-node': true,
'off-node': false,
}),
});
PrefsManager.reset();
await PrefsManager.initialize();
final storage = StorageService();
expect(
await storage.repeaterClockSyncAfterLogin(
'on-node',
globalDefault: false,
),
isTrue,
);
expect(
await storage.repeaterClockSyncAfterLogin(
'off-node',
globalDefault: true,
),
isFalse,
);
expect(
await storage.repeaterClockSyncAfterLogin(
'new-node',
globalDefault: true,
),
isTrue,
);
expect(
await storage.repeaterClockSyncAfterLogin(
'new-node',
globalDefault: false,
),
isFalse,
);
});
test('choosing default removes the per-repeater override', () async {
final storage = StorageService();
await storage.setRepeaterClockSyncOverride(
'node',
RepeaterClockSyncOverride.on,
);
expect(
await storage.getRepeaterClockSyncOverride('node'),
RepeaterClockSyncOverride.on,
);
await storage.setRepeaterClockSyncOverride(
'node',
RepeaterClockSyncOverride.followDefault,
);
expect(
await storage.getRepeaterClockSyncOverride('node'),
RepeaterClockSyncOverride.followDefault,
);
expect(
PrefsManager.instance.containsKey('repeater_auto_clock_sync_after_login'),
isFalse,
);
});
}
+1 -1
View File
@@ -205,7 +205,7 @@ void main() {
final pick = svc.selectPathForAttempt(
contact,
attemptIndex: attempt,
maxRetries: maxRetries,
directRetries: maxRetries - 1,
recentSelections: used,
context: context,
);
+109
View File
@@ -0,0 +1,109 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/helpers/contact_clipboard.dart';
import 'package:meshcore_open/utils/contact_qr.dart';
void main() {
final validLowerHex = List.generate(
32,
(i) => i.toRadixString(16).padLeft(2, '0'),
).join();
final validUpperHex = validLowerHex.toUpperCase();
group('normalizeContactPublicKeyHex & decodeContactPublicKeyHex', () {
test('accepts lowercase 64-char hex', () {
expect(normalizeContactPublicKeyHex(validLowerHex), validLowerHex);
final bytes = decodeContactPublicKeyHex(validLowerHex);
expect(bytes, isNotNull);
expect(bytes!.length, 32);
expect(bytes[0], 0x00);
expect(bytes[31], 0x1f);
});
test('trims whitespace, strips 0x/0X prefix, and normalizes case', () {
expect(
normalizeContactPublicKeyHex(' 0x$validUpperHex \n\t '),
validLowerHex,
);
expect(normalizeContactPublicKeyHex('0X$validUpperHex'), validLowerHex);
});
test(
'rejects invalid lengths, non-hex characters, and internal spaces',
() {
expect(normalizeContactPublicKeyHex(''), isNull);
expect(normalizeContactPublicKeyHex(' '), isNull);
expect(
normalizeContactPublicKeyHex(validLowerHex.substring(0, 63)),
isNull,
);
expect(normalizeContactPublicKeyHex('${validLowerHex}aa'), isNull);
expect(normalizeContactPublicKeyHex('0x $validLowerHex'), isNull);
expect(normalizeContactPublicKeyHex('zz' * 32), isNull);
expect(decodeContactPublicKeyHex('zz' * 32), isNull);
},
);
});
group('parseContactClipboard', () {
test('parses official meshcore://contact/add URI', () {
final result = parseContactClipboard(
' meshcore://contact/add?name=Alice&public_key=$validLowerHex&type=2 ',
);
expect(result.kind, ContactClipboardKind.contact);
expect(result.contact, isNotNull);
expect(result.contact!.name, 'Alice');
expect(result.contact!.type, 2);
expect(result.contact!.publicKey!.length, 32);
});
test('parses legacy meshcore://<advert> URI', () {
final advertHex = '0a' * 98;
final result = parseContactClipboard('meshcore://$advertHex');
expect(result.kind, ContactClipboardKind.contact);
expect(result.contact!.isAdvertPacket, isTrue);
expect(result.contact!.advertPacket!.length, 98);
});
test('parses contact share token', () {
final result = parseContactClipboard('Bob: <$validUpperHex:3:Bob Node>');
expect(result.kind, ContactClipboardKind.contact);
expect(result.contact!.name, 'Bob Node');
expect(result.contact!.type, 3);
expect(result.contact!.publicKey!.length, 32);
});
test('parses bare 64-char hex key with whitespace, 0x, and uppercase', () {
final result = parseContactClipboard('\n 0x$validUpperHex ');
expect(result.kind, ContactClipboardKind.publicKey);
expect(result.publicKeyHex, validLowerHex);
expect(result.contact, isNull);
});
test('returns empty for null or whitespace-only text', () {
expect(parseContactClipboard(null).kind, ContactClipboardKind.empty);
expect(parseContactClipboard('').kind, ContactClipboardKind.empty);
expect(parseContactClipboard(' \n\t ').kind, ContactClipboardKind.empty);
});
test('returns invalid for malformed URIs, short keys, and random text', () {
expect(
parseContactClipboard('meshcore://not-valid').kind,
ContactClipboardKind.invalid,
);
expect(
parseContactClipboard(
'meshcore://channel/add?name=Public&secret=abcd',
).kind,
ContactClipboardKind.invalid,
);
expect(
parseContactClipboard(validLowerHex.substring(0, 62)).kind,
ContactClipboardKind.invalid,
);
expect(
parseContactClipboard('hello world').kind,
ContactClipboardKind.invalid,
);
});
});
}
+148
View File
@@ -0,0 +1,148 @@
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/connector/meshcore_protocol.dart';
import 'package:meshcore_open/models/contact.dart';
import 'package:meshcore_open/utils/contact_search.dart';
Contact _contact(
String name,
List<int> key, {
int type = advTypeRepeater,
DateTime? lastSeen,
}) {
return Contact(
publicKey: Uint8List.fromList(key),
name: name,
type: type,
pathLength: -1,
path: Uint8List(0),
lastSeen: lastSeen ?? DateTime.fromMillisecondsSinceEpoch(0),
);
}
List<String> _ranked(List<Contact> contacts, String query) {
final matches = contacts.where((c) => matchesContactQuery(c, query)).toList()
..sort((a, b) => compareContactQueryRank(a, b, query));
return matches.map((c) => c.name).toList();
}
void main() {
final contacts = [
_contact('100 Acre', [0x11, 0x22, 0x33, 0x44]),
_contact('Acreage North', [0x33, 0x44, 0x55, 0x66]),
_contact('My Acre Site', [0x55, 0x66, 0x77, 0x88]),
_contact('2E0HQR-R', [0x2E, 0x0A, 0x1B, 0x2C]),
_contact('CR1', [0x60, 0x60, 0xAB, 0xCD]),
_contact('Node 6060', [0x01, 0x02, 0x03, 0x04]),
_contact('6060 Hub', [0x0A, 0x0B, 0x0C, 0x0D]),
];
test('name prefixes rank before other substring matches', () {
expect(_ranked(contacts, 'acre'), [
'Acreage North',
'100 Acre',
'My Acre Site',
]);
});
test('prefix matches stay alphabetical among themselves', () {
final extra = [
_contact('Acreage North', [0x01]),
_contact('Acre Beacon', [0x02]),
];
expect(_ranked(extra, 'acre'), ['Acre Beacon', 'Acreage North']);
});
test('a hop hash matches when the name does not', () {
expect(matchesContactQuery(contacts[4], '6060'), isTrue);
expect(matchesContactQuery(contacts[4], '60'), isTrue);
expect(matchesContactQuery(contacts[4], '6060abcd'), isTrue);
expect(matchesContactQuery(contacts[4], '6061'), isFalse);
expect(_ranked(contacts, '6060'), ['6060 Hub', 'Node 6060', 'CR1']);
});
test('hash search accepts 0x, spaces, and angle brackets', () {
expect(_ranked(contacts, '0x6060'), ['CR1']);
expect(_ranked(contacts, '60 60'), ['CR1']);
expect(_ranked(contacts, '<6060>'), ['CR1']);
});
test('a single hex digit does not match every key', () {
expect(matchesContactQuery(contacts[4], '6'), isFalse);
});
test('an empty query matches every contact and keeps the tie-break', () {
final timed = [
_contact('B', [0x01], lastSeen: DateTime.utc(2024, 1, 2)),
_contact('A', [0x02], lastSeen: DateTime.utc(2024, 1, 3)),
];
timed.sort(
(a, b) => compareContactQueryRank(
a,
b,
'',
(a, b) => b.lastSeen.compareTo(a.lastSeen),
),
);
expect(timed.map((c) => c.name), ['A', 'B']);
});
test('a labeled key uses the same prefix, substring, then hash order', () {
expect(
rankLabeledKeyQuery(
name: 'Review Radio',
publicKeyHex: '6060abcd',
query: 'my',
aliases: ['My contact'],
),
ContactQueryRank.namePrefix,
);
expect(
rankLabeledKeyQuery(
name: 'Review Radio',
publicKeyHex: '6060abcd',
query: 'radio',
aliases: ['My contact'],
),
ContactQueryRank.nameContains,
);
expect(
rankLabeledKeyQuery(
name: 'Review Radio',
publicKeyHex: '6060abcd',
query: '6060',
aliases: ['My contact'],
),
ContactQueryRank.keyPrefix,
);
expect(
rankLabeledKeyQuery(
name: 'Review Radio',
publicKeyHex: '6060abcd',
query: 'zzzz',
aliases: ['My contact'],
),
isNull,
);
});
test('tie-break applies inside a rank, not across ranks', () {
final olderPrefix = _contact('Acre Older', [
0x01,
], lastSeen: DateTime.utc(2020));
final newerSubstring = _contact('My Acre', [
0x02,
], lastSeen: DateTime.utc(2024));
final ranked = [newerSubstring, olderPrefix]
..sort(
(a, b) => compareContactQueryRank(
a,
b,
'acre',
(a, b) => b.lastSeen.compareTo(a.lastSeen),
),
);
expect(ranked.map((c) => c.name), ['Acre Older', 'My Acre']);
});
}
+73
View File
@@ -0,0 +1,73 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/widgets/contact_visuals.dart';
import 'package:meshcore_open/widgets/mesh_ui.dart';
void main() {
group('avatarInitials', () {
test('empty and whitespace-only names have no initials', () {
expect(avatarInitials(''), isNull);
expect(avatarInitials(' '), isNull);
});
test('punctuation-only names have no initials', () {
expect(avatarInitials('-'), isNull);
expect(avatarInitials('(--) [ ]'), isNull);
});
test('punctuation never becomes an initial', () {
expect(avatarInitials('(Base) Node'), 'BN');
expect(avatarInitials('- Relay'), 'RE');
expect(avatarInitials('[AB12] Hilltop'), 'AH');
expect(avatarInitials('Node-1'), 'N1');
});
test('plain names keep the existing two-letter shape', () {
expect(avatarInitials('Alice Smith'), 'AS');
expect(avatarInitials('tower'), 'TO');
expect(avatarInitials('A1B2C3D4'), 'A1');
});
test('Cyrillic names use their letters', () {
expect(avatarInitials('Иван Петров'), 'ИП');
expect(avatarInitials('(ретранслятор)'), 'РЕ');
});
test('CJK names use their characters', () {
expect(avatarInitials('東京 中継'), '東中');
expect(avatarInitials('「大阪」'), '大阪');
});
test('emoji is kept whole and skipped when letters exist', () {
expect(avatarInitials('🔥 Fire Node'), 'FN');
expect(avatarInitials('Fire🔥Node'), 'FN');
expect(avatarInitials('🔥'), '🔥');
expect(avatarInitials('👨‍👩‍👧 -'), '👨‍👩‍👧');
});
test('combining accents stay with their letter', () {
expect(avatarInitials('école'), 'ÉC');
});
});
testWidgets('AvatarCircle shows an icon when the name has no initials', (
tester,
) async {
await tester.pumpWidget(
const MaterialApp(
home: Scaffold(
body: Column(
children: [
AvatarCircle(name: '(--)'),
AvatarCircle(name: '(Base) Node'),
],
),
),
),
);
expect(find.byIcon(Icons.person_outline), findsOneWidget);
expect(find.text('BN'), findsOneWidget);
expect(find.textContaining('('), findsNothing);
});
}
+690
View File
@@ -0,0 +1,690 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:meshcore_open/connector/meshcore_connector.dart';
import 'package:meshcore_open/helpers/gif_helper.dart';
import 'package:meshcore_open/l10n/app_localizations.dart';
import 'package:meshcore_open/models/chat_background.dart';
import 'package:meshcore_open/services/app_settings_service.dart';
import 'package:meshcore_open/services/chat_background_service.dart';
import 'package:meshcore_open/services/chat_background_image_store.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:meshcore_open/theme/mesh_theme.dart';
import 'package:meshcore_open/widgets/byte_count_input.dart';
import 'package:meshcore_open/widgets/chat_background.dart';
import 'package:meshcore_open/widgets/chat_composer.dart';
import 'package:meshcore_open/widgets/connect_sheet.dart';
import 'package:meshcore_open/widgets/gif_message.dart';
import 'package:meshcore_open/widgets/message_translation_button.dart';
final _l10n = lookupAppLocalizations(const Locale('en'));
class _Connector extends MeshCoreConnector {
bool connected = true;
@override
bool get isConnected => connected;
}
class _Harness {
final controller = TextEditingController();
final focusNode = FocusNode();
final connector = _Connector();
late final AppSettingsService settings;
late final ChatBackgroundService backgrounds;
int sends = 0;
final actions = <String>[];
void dispose() {
controller.dispose();
focusNode.dispose();
connector.dispose();
}
}
Future<_Harness> _harness(WidgetTester tester) async {
final h = _Harness();
// A date with no holiday nearby, so no holiday chat background applies.
h.settings = AppSettingsService(clock: () => DateTime(2026, 7, 1));
await tester.runAsync(h.settings.loadSettings);
h.backgrounds = ChatBackgroundService(
h.settings,
imageStore: InMemoryChatBackgroundImageStore(),
);
addTearDown(h.dispose);
return h;
}
Widget _app(
_Harness h, {
int maxBytes = 160,
Widget? replyPreview,
bool disableAnimations = false,
Brightness brightness = Brightness.light,
List<ChatComposerAction>? actions,
}) {
final composer = ChatComposer(
controller: h.controller,
focusNode: h.focusNode,
maxBytes: maxBytes,
onSend: () => h.sends++,
sendTooltip: _l10n.chat_sendMessage,
actionsBuilder: () =>
actions ??
[
ChatComposerAction(
id: 'gif',
icon: Icons.gif_box,
label: _l10n.chat_sendGif,
),
],
onAction: h.actions.add,
replyPreview: replyPreview,
);
return MultiProvider(
providers: [
ChangeNotifierProvider<MeshCoreConnector>.value(value: h.connector),
ChangeNotifierProvider.value(value: h.settings),
ChangeNotifierProvider.value(value: h.backgrounds),
],
child: MaterialApp(
theme: brightness == Brightness.light
? MeshTheme.light()
: MeshTheme.dark(),
locale: const Locale('en'),
localizationsDelegates: const [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: AppLocalizations.supportedLocales,
builder: (context, child) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(disableAnimations: disableAnimations),
child: child!,
),
home: Scaffold(
body: ChatBackdrop(
chatKey: 'contact:test',
footer: composer,
child: const SizedBox.expand(),
),
),
),
);
}
Finder get _plus => find.byTooltip(_l10n.chat_selectSendAction);
Finder get _send => find.byTooltip(_l10n.chat_sendMessage);
Finder get _menu => find.byKey(ChatComposer.actionMenuKey);
Finder get _bubble => find.byKey(ChatComposer.bubbleKey);
Future<void> _type(WidgetTester tester, String text) async {
await tester.enterText(find.byType(TextField), text);
await tester.pumpAndSettle();
}
void main() {
setUp(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
});
testWidgets('right circle is + when empty and Send with text', (
tester,
) async {
final h = await _harness(tester);
await tester.pumpWidget(_app(h));
await tester.pumpAndSettle();
// No separate "+" on the left: one round button only.
expect(_plus, findsOneWidget);
expect(_send, findsNothing);
expect(find.byIcon(Icons.add_circle_outline), findsNothing);
// "+" opens the screen's action menu.
await tester.tap(_plus);
await tester.pumpAndSettle();
await tester.tap(find.text(_l10n.chat_sendGif));
await tester.pumpAndSettle();
expect(h.actions, ['gif']);
// Whitespace doesn't count as text.
await _type(tester, ' ');
expect(_plus, findsOneWidget);
await _type(tester, 'On my way');
expect(_plus, findsNothing);
expect(_send, findsOneWidget);
await tester.tap(_send);
expect(h.sends, 1);
await _type(tester, '');
expect(_plus, findsOneWidget);
expect(_send, findsNothing);
});
testWidgets('round button has a 48dp touch target and sits right of the '
'bubble', (tester) async {
final h = await _harness(tester);
await tester.pumpWidget(_app(h));
await tester.pumpAndSettle();
final plus = find.widgetWithIcon(IconButton, Icons.add);
final size = tester.getSize(plus);
expect(size.width, greaterThanOrEqualTo(48));
expect(size.height, greaterThanOrEqualTo(48));
expect(
tester.getTopLeft(plus).dx,
greaterThanOrEqualTo(tester.getTopRight(_bubble).dx),
);
// Single-line bubble is about one touch target tall.
expect(tester.getSize(_bubble).height, inInclusiveRange(44, 52));
});
testWidgets('swap animates, and is instant with animations disabled', (
tester,
) async {
final h = await _harness(tester);
await tester.pumpWidget(_app(h));
await tester.pumpAndSettle();
await tester.enterText(find.byType(TextField), 'hi');
await tester.pump();
await tester.pump(const Duration(milliseconds: 50));
// Mid-transition both icons are on screen.
expect(_plus, findsOneWidget);
expect(_send, findsOneWidget);
await tester.pumpAndSettle();
expect(_plus, findsNothing);
final reduced = await _harness(tester);
await tester.pumpWidget(_app(reduced, disableAnimations: true));
await tester.pumpAndSettle();
await tester.enterText(find.byType(TextField), 'hi');
await tester.pump();
await tester.pump();
expect(_plus, findsNothing);
expect(_send, findsOneWidget);
});
testWidgets('field grows to 5 lines then scrolls, buttons stay at the '
'bottom', (tester) async {
final h = await _harness(tester);
await tester.pumpWidget(_app(h, maxBytes: 1000));
await tester.pumpAndSettle();
final field = tester.widget<TextField>(find.byType(TextField));
expect(field.minLines, 1);
expect(field.maxLines, kComposerMaxLines);
await _type(tester, 'one');
final oneLine = tester.getSize(find.byType(TextField)).height;
final sendBottom = tester.getBottomLeft(_send).dy;
final bubbleBottom = tester.getBottomLeft(_bubble).dy;
await _type(tester, List.filled(5, 'line').join('\n'));
final fiveLines = tester.getSize(find.byType(TextField)).height;
expect(fiveLines, greaterThan(oneLine * 2));
await _type(tester, List.filled(12, 'line').join('\n'));
expect(tester.getSize(find.byType(TextField)).height, fiveLines);
// The panel grows upwards; the send button keeps its place at the
// bottom of the bubble.
expect(tester.getBottomLeft(_send).dy, sendBottom);
expect(tester.getBottomLeft(_bubble).dy, bubbleBottom);
});
testWidgets('a short window still lets the field wrap onto two lines', (
tester,
) async {
tester.view.physicalSize = const Size(600, 260);
tester.view.devicePixelRatio = 1;
tester.platformDispatcher.textScaleFactorTestValue = 2.0;
addTearDown(tester.view.reset);
addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
final h = await _harness(tester);
await tester.pumpWidget(_app(h, maxBytes: 1000));
await tester.pumpAndSettle();
expect(
tester.widget<TextField>(find.byType(TextField)).maxLines,
greaterThanOrEqualTo(2),
);
});
testWidgets('byte counter shows only past the warning threshold and '
'takes no space before', (tester) async {
final h = await _harness(tester);
await tester.pumpWidget(_app(h, maxBytes: 20));
await tester.pumpAndSettle();
final emptyHeight = tester.getSize(_bubble).height;
await _type(tester, 'a' * 14); // 70 %: not past the threshold
expect(find.text('14 / 20'), findsNothing);
expect(tester.getSize(_bubble).height, emptyHeight);
await _type(tester, 'a' * 15);
final counter = find.text('15 / 20');
expect(counter, findsOneWidget);
expect(find.descendant(of: _bubble, matching: counter), findsOneWidget);
// Bottom-right of the bubble.
expect(
tester.getCenter(counter).dx,
greaterThan(tester.getCenter(_bubble).dx),
);
expect(
tester.getCenter(counter).dy,
greaterThan(tester.getCenter(find.byType(TextField)).dy),
);
// The byte limit itself is unchanged.
await _type(tester, 'a' * 30);
expect(h.controller.text.length, 20);
});
testWidgets('ByteCountedTextField defaults are unchanged for other '
'screens', (tester) async {
final controller = TextEditingController();
addTearDown(controller.dispose);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: ByteCountedTextField(maxBytes: 20, controller: controller),
),
),
);
final field = tester.widget<TextField>(find.byType(TextField));
expect(field.maxLines, isNull);
// The counter row keeps its place while hidden.
expect(find.text('0 / 20'), findsOneWidget);
});
testWidgets('reply preview renders inside the top of the bubble and can '
'be dismissed', (tester) async {
final h = await _harness(tester);
var dismissed = false;
await tester.pumpWidget(
_app(
h,
replyPreview: ChatComposerQuote(
title: _l10n.chat_replyingTo('Bob'),
content: const Text('see you at camp'),
onDismiss: () => dismissed = true,
dismissTooltip: _l10n.chat_cancelReply,
),
),
);
await tester.pumpAndSettle();
final quote = find.byType(ChatComposerQuote);
expect(find.descendant(of: _bubble, matching: quote), findsOneWidget);
expect(find.text(_l10n.chat_replyingTo('Bob')), findsOneWidget);
expect(
tester.getBottomLeft(quote).dy,
lessThanOrEqualTo(tester.getTopLeft(find.byType(TextField)).dy),
);
await tester.tap(find.byTooltip(_l10n.chat_cancelReply));
expect(dismissed, isTrue);
});
testWidgets('GIF preview sits in the bubble, sends on Enter and can be '
'removed', (tester) async {
final h = await _harness(tester);
await tester.pumpWidget(_app(h));
await tester.pumpAndSettle();
h.controller.text = GifHelper.encodeGif('abc123');
await tester.pump();
await tester.pump(const Duration(milliseconds: 200));
expect(
find.descendant(of: _bubble, matching: find.byType(GifMessage)),
findsOneWidget,
);
expect(find.byType(TextField), findsNothing);
expect(_send, findsOneWidget);
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
expect(h.sends, 1);
await tester.tap(find.byTooltip(_l10n.chat_removeGif));
await tester.pump();
await tester.pump(const Duration(milliseconds: 200));
expect(h.controller.text, isEmpty);
expect(find.byType(TextField), findsOneWidget);
expect(_plus, findsOneWidget);
});
testWidgets('translate button sits inside the bubble when enabled', (
tester,
) async {
final h = await _harness(tester);
await tester.runAsync(() => h.settings.setTranslationEnabled(true));
await tester.pumpWidget(_app(h));
await tester.pumpAndSettle();
final translate = find.byType(MessageTranslationButton);
expect(find.descendant(of: _bubble, matching: translate), findsOneWidget);
expect(
tester.getCenter(translate).dx,
greaterThan(tester.getCenter(find.byType(TextField)).dx),
);
expect(
find.descendant(of: translate, matching: find.byType(Tooltip)),
findsOneWidget,
);
});
testWidgets('+ menu opens above the button and grows upward from it', (
tester,
) async {
final h = await _harness(tester);
await tester.pumpWidget(_app(h));
await tester.pumpAndSettle();
final plusTop = tester.getTopLeft(_plus).dy;
final plusRight = tester.getTopRight(_plus).dx;
await tester.tap(_plus);
await tester.pump();
await tester.pump(const Duration(milliseconds: 50));
final early = tester.getRect(_menu);
await tester.pump(const Duration(milliseconds: 50));
final later = tester.getRect(_menu);
expect(later.top, lessThan(early.top));
expect(later.bottom, closeTo(early.bottom, 0.01));
expect(later.height, greaterThan(early.height));
await tester.pumpAndSettle();
final open = tester.getRect(_menu);
expect(open.bottom, closeTo(early.bottom, 0.01));
expect(open.bottom, lessThanOrEqualTo(plusTop));
// Trailing edges line up (the tap target is a little wider than the
// visible button).
expect(open.right, closeTo(plusRight, 3));
expect(open.height, greaterThanOrEqualTo(kMinInteractiveDimension));
// The card hugs a short label instead of filling the width cap.
expect(open.width, lessThan(280));
await tester.tapAt(const Offset(5, 5));
await tester.pump();
await tester.pump(const Duration(milliseconds: 60));
final closing = tester.getRect(_menu);
expect(closing.bottom, closeTo(open.bottom, 0.01));
expect(closing.height, lessThan(open.height));
await tester.pumpAndSettle();
expect(_menu, findsNothing);
});
testWidgets('+ menu opens at once with animations disabled', (tester) async {
final h = await _harness(tester);
await tester.pumpWidget(_app(h, disableAnimations: true));
await tester.pumpAndSettle();
await tester.tap(_plus);
await tester.pump();
await tester.pump();
expect(find.text(_l10n.chat_sendGif), findsOneWidget);
expect(
tester.getRect(_menu).height,
greaterThanOrEqualTo(kMinInteractiveDimension),
);
expect(
tester.getRect(_menu).bottom,
lessThanOrEqualTo(tester.getTopLeft(_plus).dy),
);
});
testWidgets('+ menu keeps focus on the text field', (tester) async {
final h = await _harness(tester);
await tester.pumpWidget(_app(h));
await tester.pumpAndSettle();
h.focusNode.requestFocus();
await tester.pumpAndSettle();
expect(h.focusNode.hasFocus, isTrue);
await tester.tap(_plus);
await tester.pumpAndSettle();
expect(find.text(_l10n.chat_sendGif), findsOneWidget);
expect(h.focusNode.hasFocus, isTrue);
});
testWidgets('tapping outside the + menu closes it without an action', (
tester,
) async {
final h = await _harness(tester);
await tester.pumpWidget(_app(h));
await tester.pumpAndSettle();
await tester.tap(_plus);
await tester.pumpAndSettle();
expect(_menu, findsOneWidget);
await tester.tapAt(const Offset(5, 5));
await tester.pumpAndSettle();
expect(_menu, findsNothing);
expect(h.actions, isEmpty);
});
for (final scale in [1.3, 2.0]) {
testWidgets('+ menu stays above the button at 320dp, ${scale}x text', (
tester,
) async {
tester.view.physicalSize = const Size(320, 568);
tester.view.devicePixelRatio = 1;
tester.platformDispatcher.textScaleFactorTestValue = scale;
addTearDown(tester.view.reset);
addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
final h = await _harness(tester);
await tester.pumpWidget(
_app(
h,
actions: [
for (var i = 0; i < 4; i++)
ChatComposerAction(
id: 'a$i',
icon: Icons.gif_box,
label: 'A rather long action label number $i for the menu',
),
],
),
);
await tester.pumpAndSettle();
await tester.tap(_plus);
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
final menu = tester.getRect(_menu);
expect(menu.bottom, lessThanOrEqualTo(tester.getTopLeft(_plus).dy));
expect(menu.left, greaterThanOrEqualTo(0));
expect(menu.right, lessThanOrEqualTo(320));
expect(menu.top, greaterThanOrEqualTo(0));
await tester.tap(find.textContaining('number 3'));
await tester.pumpAndSettle();
expect(h.actions, ['a3']);
});
}
testWidgets('+ menu re-clamps into the viewport when it shrinks while open', (
tester,
) async {
tester.view.physicalSize = const Size(600, 800);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
final h = await _harness(tester);
await tester.pumpWidget(
_app(
h,
actions: [
for (var i = 0; i < 6; i++)
ChatComposerAction(
id: 'a$i',
icon: Icons.gif_box,
label: 'A rather long action label number $i for the menu',
),
],
),
);
await tester.pumpAndSettle();
await tester.tap(_plus);
await tester.pumpAndSettle();
final before = tester.getRect(_menu);
expect(find.textContaining('number 5'), findsOneWidget);
tester.view.physicalSize = const Size(240, 320);
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
final after = tester.getRect(_menu);
expect(after.width, lessThan(before.width));
expect(after.height, lessThan(before.height));
expect(after.left, greaterThanOrEqualTo(0));
expect(after.right, lessThanOrEqualTo(240));
expect(after.top, greaterThanOrEqualTo(0));
expect(after.bottom, lessThanOrEqualTo(tester.getTopLeft(_plus).dy));
await tester.drag(
find.descendant(of: _menu, matching: find.byType(Scrollable)),
const Offset(0, -1000),
);
await tester.pumpAndSettle();
await tester.tap(find.textContaining('number 5'));
await tester.pumpAndSettle();
expect(h.actions, ['a5']);
});
testWidgets('panel is solid without a chat background and transparent '
'over one', (tester) async {
final h = await _harness(tester);
await tester.pumpWidget(_app(h));
await tester.pumpAndSettle();
final scheme = MeshTheme.light().colorScheme;
Color bubbleColor() =>
((tester.widget<DecoratedBox>(_bubble).decoration as BoxDecoration)
.color)
as Color;
final panelFill = find.ancestor(
of: _bubble,
matching: find.byWidgetPredicate(
(w) => w is ColoredBox && w.color == scheme.surface,
),
);
expect(panelFill, findsOneWidget);
expect(bubbleColor(), scheme.surfaceContainerHigh);
await tester.runAsync(
() => h.backgrounds.setChatBackground(
'contact:test',
const ChatBackground.color(Color(0xFF1E3A8A)),
),
);
await tester.pumpAndSettle();
expect(find.byType(ChatBackgroundLayer), findsOneWidget);
expect(panelFill, findsNothing);
// Incoming-bubble colour keeps the text readable over the background.
expect(bubbleColor(), scheme.surfaceContainerLow);
});
testWidgets('offline bar uses the same bubble and height as the composer', (
tester,
) async {
tester.view.physicalSize = const Size(1200, 600);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
final h = await _harness(tester);
await tester.pumpWidget(_app(h));
await tester.pumpAndSettle();
final composerTop = tester.getTopLeft(_bubble).dy;
final composerHeight = tester.getSize(_bubble).height;
h.connector.connected = false;
h.connector.notifyListeners();
await tester.pumpAndSettle();
expect(find.byType(OfflineComposerBar), findsOneWidget);
expect(find.byType(TextField), findsNothing);
expect(find.byType(ConnectButton), findsOneWidget);
expect(find.text(_l10n.chat_composerOffline), findsOneWidget);
final decoration =
tester.widget<DecoratedBox>(_bubble).decoration as BoxDecoration;
expect(
decoration.borderRadius,
BorderRadius.circular(kComposerBubbleRadius),
);
expect(tester.getSize(_bubble).height, composerHeight);
expect(tester.getTopLeft(_bubble).dy, composerTop);
// The draft survives and comes back with the radio.
h.controller.text = 'draft';
h.connector.connected = true;
h.connector.notifyListeners();
await tester.pumpAndSettle();
expect(
tester.widget<TextField>(find.byType(TextField)).controller?.text,
'draft',
);
});
for (final scale in [1.3, 2.0]) {
for (final brightness in Brightness.values) {
testWidgets('fits 320dp at ${scale}x text (${brightness.name})', (
tester,
) async {
tester.view.physicalSize = const Size(320, 568);
tester.view.devicePixelRatio = 1;
tester.platformDispatcher.textScaleFactorTestValue = scale;
addTearDown(tester.view.reset);
addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
final h = await _harness(tester);
await tester.runAsync(() => h.settings.setTranslationEnabled(true));
await tester.pumpWidget(
_app(
h,
maxBytes: 20,
brightness: brightness,
replyPreview: ChatComposerQuote(
title: _l10n.chat_replyingTo('A very long sender name here'),
content: const Text(
'a long quoted message that must ellipsize',
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
onDismiss: () {},
dismissTooltip: _l10n.chat_cancelReply,
// A long region chip, as a channel reply shows.
trailing: Text(
_l10n.channels_regionSetTo('north-west-valley'),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
),
);
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
expect(find.byTooltip(_l10n.chat_cancelReply), findsOneWidget);
await _type(tester, 'a' * 19);
expect(tester.takeException(), isNull);
// With the keyboard up, a long draft still fits: the field caps its
// lines to the room left.
tester.view.viewInsets = const FakeViewPadding(bottom: 260);
await _type(tester, List.filled(8, 'line').join('\n'));
expect(tester.takeException(), isNull);
tester.view.resetViewInsets();
await tester.pumpAndSettle();
h.connector.connected = false;
h.connector.notifyListeners();
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
});
}
}
}
@@ -0,0 +1,334 @@
import 'dart:async';
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/app_settings.dart';
import 'package:meshcore_open/theme/mesh_theme.dart';
import 'package:meshcore_open/widgets/chat_compression_selector.dart';
final _l10n = lookupAppLocalizations(const Locale('en'));
final _profiles = [
Cyr2LatProfile(id: 'ru', name: 'Russian', charMap: const {'А': 'A'}),
Cyr2LatProfile(id: 'sr', name: 'Serbian', charMap: const {'З': '3'}),
];
/// Stands in for a chat screen: keeps the "saved" state and applies a change
/// only when the test completes the pending write.
class _Host extends StatefulWidget {
final ChatCompressionMode initialMode;
final bool enabled;
final String? initialProfileId;
final List<ChatCompressionMode> modeCalls;
final List<String> profileCalls;
final List<Completer<void>> pending;
const _Host({
this.initialMode = ChatCompressionMode.off,
this.enabled = true,
this.initialProfileId,
required this.modeCalls,
required this.profileCalls,
required this.pending,
});
@override
State<_Host> createState() => _HostState();
}
class _HostState extends State<_Host> {
late ChatCompressionMode _mode = widget.initialMode;
late String? _profileId = widget.initialProfileId;
Future<void> _write(void Function() apply) async {
final completer = Completer<void>();
widget.pending.add(completer);
await completer.future;
if (mounted) setState(apply);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Chat')),
body: Column(
children: [
ChatCompressionSelector(
mode: _mode,
enabled: widget.enabled,
disabledReason: widget.enabled
? null
: _l10n.chatCompression_noStorageId,
profiles: _profiles,
profileId: _profileId,
defaultProfileId: 'ru',
onModeChanged: (mode) {
widget.modeCalls.add(mode);
return _write(() => _mode = mode);
},
onProfileChanged: (id) {
widget.profileCalls.add(id);
return _write(() => _profileId = id);
},
),
const Expanded(child: Placeholder()),
],
),
);
}
}
void main() {
late List<ChatCompressionMode> modeCalls;
late List<String> profileCalls;
late List<Completer<void>> pending;
setUp(() {
modeCalls = [];
profileCalls = [];
pending = [];
});
Future<void> pumpHost(
WidgetTester tester, {
ChatCompressionMode mode = ChatCompressionMode.off,
bool enabled = true,
String? profileId,
Size size = const Size(400, 800),
double textScale = 1.0,
}) async {
tester.view.physicalSize = size;
tester.view.devicePixelRatio = 1.0;
addTearDown(tester.view.reset);
await tester.pumpWidget(
MaterialApp(
theme: MeshTheme.light(),
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
builder: (context, child) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(textScaler: TextScaler.linear(textScale)),
child: child!,
),
home: _Host(
initialMode: mode,
enabled: enabled,
initialProfileId: profileId,
modeCalls: modeCalls,
profileCalls: profileCalls,
pending: pending,
),
),
);
}
Future<void> openSheet(WidgetTester tester) async {
await tester.tap(find.byType(ChatCompressionSelector));
await tester.pumpAndSettle();
}
Finder optionRow(String label) =>
find.ancestor(of: find.text(label), matching: find.byType(ListTile));
bool isSelected(WidgetTester tester, String label) {
final row = optionRow(label);
return find
.descendant(of: row, matching: find.byIcon(Icons.radio_button_checked))
.evaluate()
.isNotEmpty;
}
testWidgets('shows the saved mode and announces it', (tester) async {
final semantics = tester.ensureSemantics();
await pumpHost(tester, mode: ChatCompressionMode.smaz);
expect(find.text(_l10n.chatCompression_label('SMAZ')), findsOneWidget);
expect(
tester.getSemantics(
find.bySemanticsLabel(_l10n.chatCompression_label('SMAZ')),
),
isSemantics(
label: _l10n.chatCompression_label('SMAZ'),
hint: _l10n.chatCompression_changeHint,
isButton: true,
isEnabled: true,
hasTapAction: true,
),
);
expect(
tester.getSize(find.byType(ChatCompressionSelector)).height,
greaterThanOrEqualTo(48),
);
semantics.dispose();
});
testWidgets('one sheet lists the three modes with their explanations', (
tester,
) async {
await pumpHost(tester);
await openSheet(tester);
expect(find.text(_l10n.chatCompression_title), findsOneWidget);
expect(find.text(_l10n.chatCompression_off), findsOneWidget);
expect(find.text(_l10n.chatCompression_smaz), findsOneWidget);
expect(find.text(_l10n.chatCompression_cyr2lat), findsOneWidget);
expect(find.text(_l10n.chatCompression_offDescription), findsOneWidget);
expect(find.text(_l10n.chatCompression_smazDescription), findsOneWidget);
expect(find.text(_l10n.chatCompression_cyr2latDescription), findsOneWidget);
expect(isSelected(tester, _l10n.chatCompression_off), isTrue);
expect(isSelected(tester, _l10n.chatCompression_smaz), isFalse);
// No profile picker unless Cyr2Lat is chosen.
expect(find.text(_l10n.chatCompression_profile), findsNothing);
expect(find.byType(Dialog), findsNothing);
});
testWidgets('a choice shows only after it is saved, then the sheet closes', (
tester,
) async {
await pumpHost(tester);
await openSheet(tester);
await tester.tap(find.text(_l10n.chatCompression_smaz));
await tester.pump();
expect(modeCalls, [ChatCompressionMode.smaz]);
// Still saving: old mode shown, options locked against rapid taps.
expect(isSelected(tester, _l10n.chatCompression_off), isTrue);
expect(
tester.widget<ListTile>(optionRow(_l10n.chatCompression_cyr2lat)).enabled,
isFalse,
);
await tester.tap(find.text(_l10n.chatCompression_cyr2lat));
await tester.pump();
expect(modeCalls, [ChatCompressionMode.smaz]);
pending.single.complete();
await tester.pumpAndSettle();
expect(find.text(_l10n.chatCompression_title), findsNothing);
expect(find.text(_l10n.chatCompression_label('SMAZ')), findsOneWidget);
});
testWidgets('Cyr2Lat keeps the sheet open with its profile picker', (
tester,
) async {
await pumpHost(tester);
await openSheet(tester);
await tester.tap(find.text(_l10n.chatCompression_cyr2lat));
await tester.pump();
pending.removeAt(0).complete();
await tester.pumpAndSettle();
expect(find.text(_l10n.chatCompression_title), findsOneWidget);
expect(isSelected(tester, _l10n.chatCompression_cyr2lat), isTrue);
expect(find.text(_l10n.chatCompression_profile), findsOneWidget);
// No profile saved for the chat: the app-wide one is what sending uses.
expect(find.text('Russian'), findsOneWidget);
await tester.ensureVisible(find.text('Russian'));
await tester.pumpAndSettle();
await tester.tap(find.text('Russian'));
await tester.pumpAndSettle();
await tester.tap(find.text('Serbian').last);
await tester.pump();
expect(profileCalls, ['sr']);
pending.removeAt(0).complete();
await tester.pumpAndSettle();
expect(find.text('Serbian'), findsOneWidget);
expect(find.text(_l10n.chatCompression_label('Cyr2Lat')), findsOneWidget);
});
testWidgets('a failed save keeps the saved mode and says so', (tester) async {
await pumpHost(tester, mode: ChatCompressionMode.smaz);
await openSheet(tester);
await tester.tap(find.text(_l10n.chatCompression_cyr2lat));
await tester.pump();
pending.single.completeError(StateError('disk full'));
await tester.pumpAndSettle();
expect(find.text(_l10n.chatCompression_saveFailed), findsOneWidget);
expect(isSelected(tester, _l10n.chatCompression_smaz), isTrue);
expect(isSelected(tester, _l10n.chatCompression_cyr2lat), isFalse);
expect(
tester.widget<ListTile>(optionRow(_l10n.chatCompression_off)).enabled,
isTrue,
);
await tester.tap(find.byTooltip('Close'));
await tester.pumpAndSettle();
expect(find.text(_l10n.chatCompression_label('SMAZ')), findsOneWidget);
});
testWidgets('a failed profile save shows the saved profile again', (
tester,
) async {
await pumpHost(tester, mode: ChatCompressionMode.cyr2lat, profileId: 'ru');
await openSheet(tester);
await tester.ensureVisible(find.text('Russian'));
await tester.pumpAndSettle();
await tester.tap(find.text('Russian'));
await tester.pumpAndSettle();
await tester.tap(find.text('Serbian').last);
await tester.pump();
expect(profileCalls, ['sr']);
pending.single.completeError(StateError('disk full'));
await tester.pumpAndSettle();
expect(find.text(_l10n.chatCompression_saveFailed), findsOneWidget);
expect(find.text('Russian'), findsOneWidget);
expect(find.text('Serbian'), findsNothing);
});
testWidgets('disabled shows the saved mode, and the sheet says why and '
'allows no change', (tester) async {
final semantics = tester.ensureSemantics();
await pumpHost(tester, mode: ChatCompressionMode.smaz, enabled: false);
final label = _l10n.chatCompression_label('SMAZ');
expect(find.text(label), findsOneWidget);
expect(find.byIcon(Icons.lock_outline), findsOneWidget);
expect(
find.bySemanticsLabel('$label. ${_l10n.chatCompression_noStorageId}'),
findsOneWidget,
);
await openSheet(tester);
expect(find.text(_l10n.chatCompression_noStorageId), findsOneWidget);
expect(isSelected(tester, _l10n.chatCompression_smaz), isTrue);
for (final mode in [
_l10n.chatCompression_off,
_l10n.chatCompression_smaz,
_l10n.chatCompression_cyr2lat,
]) {
expect(tester.widget<ListTile>(optionRow(mode)).enabled, isFalse);
}
await tester.tap(find.text(_l10n.chatCompression_off), warnIfMissed: false);
await tester.pumpAndSettle();
expect(modeCalls, isEmpty);
semantics.dispose();
});
for (final scale in [1.3, 2.0]) {
testWidgets('fits a 320dp phone at ${scale}x text', (tester) async {
await pumpHost(
tester,
mode: ChatCompressionMode.cyr2lat,
enabled: true,
size: const Size(320, 568),
textScale: scale,
);
expect(tester.takeException(), isNull);
await openSheet(tester);
expect(tester.takeException(), isNull);
// The sheet scrolls to its last option and the profile picker.
await tester.scrollUntilVisible(
find.text(_l10n.chatCompression_profile),
200,
scrollable: find.byType(Scrollable).last,
);
expect(tester.takeException(), isNull);
});
}
}
@@ -0,0 +1,584 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/connector/meshcore_connector.dart';
import 'package:meshcore_open/connector/meshcore_protocol.dart';
import 'package:meshcore_open/l10n/app_localizations.dart';
import 'package:meshcore_open/models/channel.dart';
import 'package:meshcore_open/models/channel_message.dart';
import 'package:meshcore_open/models/contact.dart';
import 'package:meshcore_open/models/custom_theme.dart';
import 'package:meshcore_open/models/message.dart';
import 'package:meshcore_open/screens/app_settings_screen.dart';
import 'package:meshcore_open/screens/channel_chat_screen.dart';
import 'package:meshcore_open/screens/chat_screen.dart';
import 'package:meshcore_open/services/app_debug_log_service.dart';
import 'package:meshcore_open/services/app_settings_service.dart';
import 'package:meshcore_open/services/ble_debug_log_service.dart';
import 'package:meshcore_open/services/chat_text_scale_service.dart';
import 'package:meshcore_open/services/image_codec_service.dart';
import 'package:meshcore_open/services/map_tile_cache_service.dart';
import 'package:meshcore_open/services/message_retry_service.dart';
import 'package:meshcore_open/services/network_map/network_map_upload_service.dart';
import 'package:meshcore_open/services/path_history_service.dart';
import 'package:meshcore_open/services/received_image_store.dart';
import 'package:meshcore_open/services/storage_service.dart';
import 'package:meshcore_open/services/timeout_prediction_service.dart';
import 'package:meshcore_open/services/translation_service.dart';
import 'package:meshcore_open/services/ui_view_state_service.dart';
import 'package:meshcore_open/storage/channel_message_store.dart';
import 'package:meshcore_open/storage/channel_store.dart';
import 'package:meshcore_open/storage/contact_store.dart';
import 'package:meshcore_open/storage/history_store.dart';
import 'package:meshcore_open/storage/last_radio_store.dart';
import 'package:meshcore_open/storage/message_store.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:meshcore_open/theme/mesh_theme.dart';
import 'package:meshcore_open/widgets/message_bubble_frame.dart';
import 'package:meshcore_open/widgets/message_status_icon.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
final _radioKey = Uint8List.fromList(List<int>.generate(32, (i) => 0xA0 + i));
final _radioHex = pubKeyToHex(_radioKey);
final _aliceKey = Uint8List.fromList(List<int>.generate(32, (i) => 0x10 + i));
final _psk = Uint8List.fromList(List<int>.generate(16, (i) => 0x40 + i));
final _l10n = lookupAppLocalizations(const Locale('en'));
Future<void> _seedMessages() async {
final alice = Contact(
publicKey: _aliceKey,
name: 'Alice',
type: advTypeChat,
pathLength: 1,
path: Uint8List.fromList([0x22]),
lastSeen: DateTime.fromMillisecondsSinceEpoch(1700000000000),
);
await (ContactStore()..setPublicKeyHex = _radioHex).saveContacts([alice]);
final channel = Channel(index: 0, name: 'Base Camp', psk: _psk);
final channelStore = ChannelStore()..setPublicKeyHex = _radioHex;
await channelStore.saveChannels([channel]);
await channelStore.saveSlotChannelIds({0: channel.storageId!});
await (MessageStore()..setPublicKeyHex = _radioHex)
.saveMessages(alice.publicKeyHex, [
Message(
senderKey: _aliceKey,
text: 'DM incoming compressed',
timestamp: DateTime(2026, 11, 21, 10, 11),
receivedAt: DateTime(2026, 11, 21, 10, 11),
isOutgoing: false,
isSmazCompressed: true,
status: MessageStatus.delivered,
),
Message(
senderKey: _aliceKey,
text: 'DM incoming plain',
timestamp: DateTime(2026, 11, 21, 10, 12),
receivedAt: DateTime(2026, 11, 21, 10, 12),
isOutgoing: false,
isSmazCompressed: false,
status: MessageStatus.delivered,
),
Message(
senderKey: _aliceKey,
text: 'DM outgoing plain',
timestamp: DateTime(2026, 11, 21, 10, 13),
receivedAt: DateTime(2026, 11, 21, 10, 13),
isOutgoing: true,
isSmazCompressed: false,
status: MessageStatus.delivered,
),
Message(
senderKey: _aliceKey,
text: 'DM outgoing compressed',
timestamp: DateTime(2026, 11, 21, 10, 14),
receivedAt: DateTime(2026, 11, 21, 10, 14),
isOutgoing: true,
isSmazCompressed: true,
status: MessageStatus.delivered,
),
]);
await (ChannelMessageStore()..setPublicKeyHex = _radioHex)
.saveChannelMessages(channel.storageId!, [
ChannelMessage(
senderName: 'Bob',
text: 'Channel incoming compressed',
timestamp: DateTime(2026, 11, 21, 11, 11),
receivedAt: DateTime(2026, 11, 21, 11, 11),
isOutgoing: false,
isSmazCompressed: true,
status: ChannelMessageStatus.sent,
channelIndex: 0,
),
ChannelMessage(
senderName: 'Bob',
text: 'Channel incoming plain',
timestamp: DateTime(2026, 11, 21, 11, 12),
receivedAt: DateTime(2026, 11, 21, 11, 12),
isOutgoing: false,
isSmazCompressed: false,
status: ChannelMessageStatus.sent,
channelIndex: 0,
),
ChannelMessage(
senderName: 'Me',
text: 'Channel outgoing plain',
timestamp: DateTime(2026, 11, 21, 11, 13),
receivedAt: DateTime(2026, 11, 21, 11, 13),
isOutgoing: true,
isSmazCompressed: false,
repeatCount: 1,
status: ChannelMessageStatus.sent,
channelIndex: 0,
),
ChannelMessage(
senderName: 'Me',
text: 'Channel outgoing compressed',
timestamp: DateTime(2026, 11, 21, 11, 14),
receivedAt: DateTime(2026, 11, 21, 11, 14),
isOutgoing: true,
isSmazCompressed: true,
repeatCount: 2,
status: ChannelMessageStatus.sent,
channelIndex: 0,
),
]);
await LastRadioStore().save(
LastRadio(
publicKeyHex: _radioHex,
name: 'Base',
transport: LastRadio.transportBle,
bleRemoteId: 'AA:BB:CC:DD:EE:FF',
savedAt: DateTime.fromMillisecondsSinceEpoch(1700000000000),
),
);
}
class _Harness {
final MeshCoreConnector connector;
final AppSettingsService settings;
final List<dynamic> disposables;
_Harness(this.connector, this.settings, this.disposables);
List<ChangeNotifierProvider<ChangeNotifier>> get _unused => const [];
Widget wrap(Widget home, {ThemeData? theme, double textScale = 1.0}) {
final storage = StorageService();
return MultiProvider(
providers: [
ChangeNotifierProvider.value(value: connector),
ChangeNotifierProvider.value(value: settings),
ChangeNotifierProvider.value(
value: disposables[0] as MessageRetryService,
),
ChangeNotifierProvider.value(
value: disposables[1] as PathHistoryService,
),
ChangeNotifierProvider.value(
value: disposables[2] as BleDebugLogService,
),
ChangeNotifierProvider.value(
value: disposables[3] as AppDebugLogService,
),
ChangeNotifierProvider.value(
value: disposables[4] as ChatTextScaleService,
),
ChangeNotifierProvider.value(
value: disposables[5] as TranslationService,
),
ChangeNotifierProvider.value(
value: disposables[6] as UiViewStateService,
),
Provider.value(value: storage),
ChangeNotifierProvider.value(
value: disposables[7] as MapTileCacheService,
),
ChangeNotifierProvider.value(
value: disposables[8] as TimeoutPredictionService,
),
ChangeNotifierProvider.value(
value: disposables[9] as ImageCodecService,
),
ChangeNotifierProvider.value(
value: disposables[10] as ReceivedImageStore,
),
ChangeNotifierProvider.value(
value: disposables[11] as NetworkMapUploadService,
),
],
child: MaterialApp(
theme: theme ?? MeshTheme.light(),
locale: const Locale('en'),
localizationsDelegates: const [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: AppLocalizations.supportedLocales,
builder: (context, child) => MediaQuery(
data: MediaQuery.of(context).copyWith(
textScaler: TextScaler.linear(textScale),
alwaysUse24HourFormat: true,
),
child: child!,
),
home: home,
),
);
}
void dispose() {
assert(_unused.isEmpty);
connector.dispose();
settings.dispose();
for (final d in disposables) {
if (d is ChangeNotifier) d.dispose();
}
}
}
Future<_Harness> _createHarness({bool showIndicator = false}) async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
HistoryStore.reset();
MessageStore().forgetArchive();
ChannelMessageStore().forgetArchive();
await _seedMessages();
final storage = StorageService();
final settings = AppSettingsService();
await settings.loadSettings();
if (showIndicator) {
await settings.setShowCompressionIndicator(true);
}
final connector = MeshCoreConnector();
final retry = MessageRetryService();
final pathHistory = PathHistoryService(storage);
final bleLog = BleDebugLogService();
final appLog = AppDebugLogService();
final textScale = ChatTextScaleService();
final translation = TranslationService(settings);
final uiView = UiViewStateService();
final tileCache = MapTileCacheService(appSettingsService: settings);
final timeoutPred = TimeoutPredictionService(storage);
final imageCodec = ImageCodecService(settings);
final receivedImage = ReceivedImageStore();
final networkMap = NetworkMapUploadService(
connector: connector,
settings: settings,
);
await connector.restoreLastRadio();
return _Harness(connector, settings, [
retry,
pathHistory,
bleLog,
appLog,
textScale,
translation,
uiView,
tileCache,
timeoutPred,
imageCodec,
receivedImage,
networkMap,
]);
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final tempDir = Directory.systemTemp.createTempSync(
'compression_indicator_test',
);
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(
const MethodChannel('plugins.flutter.io/path_provider'),
(call) async => tempDir.path,
);
testWidgets(
'AppSettingsScreen shows Compression indicator switch and toggles',
(tester) async {
late _Harness harness;
await tester.runAsync(() async {
harness = await _createHarness();
await harness.settings.setAutoRouteRotationEnabled(false);
});
addTearDown(harness.dispose);
tester.view.physicalSize = const Size(390, 720);
tester.view.devicePixelRatio = 1.0;
addTearDown(tester.view.reset);
await tester.pumpWidget(harness.wrap(const AppSettingsScreen()));
await tester.pumpAndSettle();
final tileFinder = find.widgetWithText(
SwitchListTile,
_l10n.appSettings_showCompressionIndicator,
);
await tester.scrollUntilVisible(
tileFinder,
60,
scrollable: find.byType(Scrollable).first,
);
await tester.pumpAndSettle();
final tile = tester.widget<SwitchListTile>(tileFinder);
expect(tile.value, isFalse);
expect(
find.descendant(of: tileFinder, matching: find.byIcon(Icons.compress)),
findsOneWidget,
);
await tester.tap(tileFinder);
await tester.pumpAndSettle();
expect(harness.settings.settings.showCompressionIndicator, isTrue);
},
);
testWidgets(
'DM ChatScreen hides icon when off, shows only on compressed when on',
(tester) async {
final semantics = tester.ensureSemantics();
try {
late _Harness harness;
await tester.runAsync(() async {
harness = await _createHarness(showIndicator: false);
});
addTearDown(harness.dispose);
final contact = harness.connector.contacts.first;
await tester.pumpWidget(harness.wrap(ChatScreen(contact: contact)));
await tester.pumpAndSettle();
expect(find.byType(CompressionIndicator), findsNothing);
await tester.runAsync(
() => harness.settings.setShowCompressionIndicator(true),
);
await tester.pumpAndSettle();
// Two compressed messages (1 incoming, 1 outgoing); two plain have none.
expect(find.byType(CompressionIndicator), findsNWidgets(2));
expect(
find.byTooltip(_l10n.messageMeta_smazCompressed),
findsNWidgets(2),
);
expect(
find.bySemanticsLabel(RegExp(_l10n.messageMeta_smazCompressed)),
findsNWidgets(2),
);
// Incoming compressed message: CompressionIndicator sits after timestamp, no ticks.
final incomingBubble = find.ancestor(
of: find.text('DM incoming compressed'),
matching: find.byType(MessageBubbleFrame),
);
final incomingIndicator = find.descendant(
of: incomingBubble,
matching: find.byType(CompressionIndicator),
);
final incomingTime = find.descendant(
of: incomingBubble,
matching: find.text('10:11'),
);
expect(incomingIndicator, findsOneWidget);
expect(
tester.getTopLeft(incomingIndicator).dx,
greaterThan(tester.getTopRight(incomingTime).dx),
);
expect(
find.descendant(
of: incomingBubble,
matching: find.byType(MessageStatusIcon),
),
findsNothing,
);
// Outgoing compressed message: CompressionIndicator sits between timestamp and ticks.
final outgoingBubble = find.ancestor(
of: find.text('DM outgoing compressed'),
matching: find.byType(MessageBubbleFrame),
);
final outgoingIndicator = find.descendant(
of: outgoingBubble,
matching: find.byType(CompressionIndicator),
);
final outgoingTime = find.descendant(
of: outgoingBubble,
matching: find.text('10:14'),
);
final outgoingTicks = find.descendant(
of: outgoingBubble,
matching: find.byType(MessageStatusIcon),
);
expect(outgoingIndicator, findsOneWidget);
expect(
tester.getTopLeft(outgoingIndicator).dx,
greaterThan(tester.getTopRight(outgoingTime).dx),
);
expect(
tester.getTopRight(outgoingIndicator).dx,
lessThanOrEqualTo(tester.getTopLeft(outgoingTicks).dx),
);
// Plain messages never show the icon.
final plainBubble = find.ancestor(
of: find.text('DM outgoing plain'),
matching: find.byType(MessageBubbleFrame),
);
expect(
find.descendant(
of: plainBubble,
matching: find.byType(CompressionIndicator),
),
findsNothing,
);
} finally {
semantics.dispose();
}
},
);
testWidgets(
'ChannelChatScreen hides icon when off, shows between time and ticks when on',
(tester) async {
late _Harness harness;
await tester.runAsync(() async {
harness = await _createHarness(showIndicator: false);
});
addTearDown(harness.dispose);
final channel = harness.connector.channels.first;
await tester.pumpWidget(
harness.wrap(ChannelChatScreen(channel: channel)),
);
await tester.pumpAndSettle();
expect(find.byType(CompressionIndicator), findsNothing);
await tester.runAsync(
() => harness.settings.setShowCompressionIndicator(true),
);
await tester.pumpAndSettle();
expect(find.byType(CompressionIndicator), findsNWidgets(2));
// Outgoing compressed channel message: icon between timestamp and repeat ticks.
final outgoingBubble = find.ancestor(
of: find.text('Channel outgoing compressed'),
matching: find.byType(MessageBubbleFrame),
);
final outgoingIndicator = find.descendant(
of: outgoingBubble,
matching: find.byType(CompressionIndicator),
);
final outgoingTime = find.descendant(
of: outgoingBubble,
matching: find.text('11:14'),
);
final outgoingTicks = find.descendant(
of: outgoingBubble,
matching: find.byType(MessageStatusIcon),
);
expect(outgoingIndicator, findsOneWidget);
expect(
tester.getTopLeft(outgoingIndicator).dx,
greaterThan(tester.getTopRight(outgoingTime).dx),
);
expect(
tester.getTopRight(outgoingIndicator).dx,
lessThanOrEqualTo(tester.getTopLeft(outgoingTicks).dx),
);
// Incoming compressed channel message: icon right after timestamp.
final incomingBubble = find.ancestor(
of: find.text('Channel incoming compressed'),
matching: find.byType(MessageBubbleFrame),
);
final incomingIndicator = find.descendant(
of: incomingBubble,
matching: find.byType(CompressionIndicator),
);
final incomingTime = find.descendant(
of: incomingBubble,
matching: find.text('11:11'),
);
expect(incomingIndicator, findsOneWidget);
expect(
tester.getTopLeft(incomingIndicator).dx,
greaterThan(tester.getTopRight(incomingTime).dx),
);
},
);
testWidgets('No overflow at 320dp width and 2.0x text scale across themes', (
tester,
) async {
late _Harness harness;
await tester.runAsync(() async {
harness = await _createHarness(showIndicator: true);
});
addTearDown(harness.dispose);
tester.view.physicalSize = const Size(320, 568);
tester.view.devicePixelRatio = 1.0;
addTearDown(tester.view.reset);
final overflows = <String>[];
final previous = FlutterError.onError;
FlutterError.onError = (details) {
final text = details.exceptionAsString();
if (text.contains('overflowed')) {
overflows.add(text.split('\n').first);
} else {
previous?.call(details);
}
};
addTearDown(() => FlutterError.onError = previous);
final contact = harness.connector.contacts.first;
final channel = harness.connector.channels.first;
final themes = [
MeshTheme.light(),
MeshTheme.dark(),
MeshTheme.fromCustom(CustomTheme.presets.first),
];
for (final theme in themes) {
await tester.pumpWidget(
harness.wrap(
ChatScreen(contact: contact),
theme: theme,
textScale: 2.0,
),
);
await tester.pumpAndSettle();
expect(find.byType(CompressionIndicator), findsAtLeastNWidgets(1));
await tester.pumpWidget(
harness.wrap(
ChannelChatScreen(channel: channel),
theme: theme,
textScale: 2.0,
),
);
await tester.pumpAndSettle();
expect(find.byType(CompressionIndicator), findsAtLeastNWidgets(1));
}
FlutterError.onError = previous;
expect(overflows, isEmpty, reason: overflows.join('\n'));
});
}
@@ -0,0 +1,228 @@
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/connector/meshcore_protocol.dart';
import 'package:meshcore_open/l10n/app_localizations.dart';
import 'package:meshcore_open/models/contact.dart';
import 'package:meshcore_open/models/contact_group.dart';
import 'package:meshcore_open/storage/contact_group_store.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:meshcore_open/widgets/contact_group_editor_dialog.dart';
import 'package:shared_preferences/shared_preferences.dart';
Contact _contact(int seed, String name) => Contact(
publicKey: Uint8List.fromList(List<int>.filled(32, seed)),
name: name,
type: advTypeChat,
pathLength: -1,
path: Uint8List(0),
lastSeen: DateTime.fromMillisecondsSinceEpoch(0),
);
final _alice = _contact(1, 'Alice');
final _bob = _contact(2, 'Bob');
final _carol = _contact(3, 'Carol');
final _dave = _contact(4, 'Dave');
Finder _member(Contact c) =>
find.byKey(ValueKey('group-member-${c.publicKeyHex}'));
Finder _candidate(Contact c) =>
find.byKey(ValueKey('group-candidate-${c.publicKeyHex}'));
/// The whole IconButton, including its 48dp tap-target padding.
Finder _button(String tooltip) => find.ancestor(
of: find.byTooltip(tooltip),
matching: find.byType(IconButton),
);
/// Opens the editor and returns the groups passed to onSave.
Future<List<ContactGroup>> _open(
WidgetTester tester, {
required List<Contact> contacts,
ContactGroup? group,
double textScale = 1.0,
}) async {
final saved = <ContactGroup>[];
await tester.pumpWidget(
MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
builder: (context, child) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(textScaler: TextScaler.linear(textScale)),
child: child!,
),
home: Builder(
builder: (context) => Scaffold(
body: TextButton(
onPressed: () => showDialog<void>(
context: context,
builder: (_) => ContactGroupEditorDialog(
contacts: contacts,
group: group,
validateName: (name) => name.isEmpty ? 'required' : null,
onSave: (g) async => saved.add(g),
),
),
child: const Text('open'),
),
),
),
),
);
await tester.tap(find.text('open'));
await tester.pumpAndSettle();
return saved;
}
void main() {
final contacts = [_dave, _carol, _bob, _alice];
final group = ContactGroup(
name: 'Team',
memberKeys: [_carol.publicKeyHex, _alice.publicKeyHex],
);
testWidgets('current members are listed first, before the add list', (
tester,
) async {
await _open(tester, contacts: contacts, group: group);
expect(find.text('CURRENT MEMBERS (2)'), findsOneWidget);
final membersHeaderY = tester
.getTopLeft(find.text('CURRENT MEMBERS (2)'))
.dy;
final addHeaderY = tester.getTopLeft(find.text('ADD CONTACTS')).dy;
final aliceY = tester.getTopLeft(_member(_alice)).dy;
final carolY = tester.getTopLeft(_member(_carol)).dy;
expect(membersHeaderY, lessThan(aliceY));
expect(aliceY, lessThan(carolY));
expect(carolY, lessThan(addHeaderY));
expect(tester.getTopLeft(_candidate(_bob)).dy, greaterThan(addHeaderY));
});
testWidgets('members never appear again in the add list', (tester) async {
await _open(tester, contacts: contacts, group: group);
expect(_candidate(_alice), findsNothing);
expect(_candidate(_carol), findsNothing);
expect(_candidate(_bob), findsOneWidget);
expect(_candidate(_dave), findsOneWidget);
expect(find.text('Alice'), findsOneWidget);
});
testWidgets('remove button drops the member and saves the rest', (
tester,
) async {
final saved = await _open(tester, contacts: contacts, group: group);
final remove = _button('Remove Alice from group');
expect(remove, findsOneWidget);
expect(tester.getSize(remove).width, greaterThanOrEqualTo(48));
expect(tester.getSize(remove).height, greaterThanOrEqualTo(48));
await tester.tap(remove);
await tester.pumpAndSettle();
expect(find.text('CURRENT MEMBERS (1)'), findsOneWidget);
expect(_member(_alice), findsNothing);
// Still a contact: it moves back to the add list.
expect(_candidate(_alice), findsOneWidget);
await tester.tap(find.text('Save'));
await tester.pumpAndSettle();
expect(saved.single.name, 'Team');
expect(saved.single.memberKeys, [_carol.publicKeyHex]);
expect(contacts, hasLength(4));
expect(contacts, contains(_alice));
});
testWidgets('search filters the add list and tapping adds a contact', (
tester,
) async {
final saved = await _open(tester, contacts: contacts, group: group);
await tester.enterText(find.byType(TextField).last, 'da');
await tester.pumpAndSettle();
expect(_candidate(_dave), findsOneWidget);
expect(_candidate(_bob), findsNothing);
// Members stay visible while searching.
expect(_member(_alice), findsOneWidget);
await tester.tap(find.text('Dave'));
await tester.pumpAndSettle();
expect(_member(_dave), findsOneWidget);
expect(_candidate(_dave), findsNothing);
expect(find.text('CURRENT MEMBERS (3)'), findsOneWidget);
await tester.tap(find.text('Save'));
await tester.pumpAndSettle();
expect(saved.single.memberKeys, [
_carol.publicKeyHex,
_alice.publicKeyHex,
_dave.publicKeyHex,
]);
expect(saved.single.memberKeys.toSet(), hasLength(3));
});
testWidgets('keys of contacts not on the radio are kept on save', (
tester,
) async {
final stale = 'ff' * 32;
final saved = await _open(
tester,
contacts: contacts,
group: ContactGroup(name: 'Team', memberKeys: [stale]),
);
await tester.tap(find.byTooltip('Add Bob to group'));
await tester.pumpAndSettle();
await tester.tap(find.text('Save'));
await tester.pumpAndSettle();
expect(saved.single.memberKeys, [stale, _bob.publicKeyHex]);
});
testWidgets('edited membership persists through the group store', (
tester,
) async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
final store = ContactGroupStore()..setPublicKeyHex = 'abcdef0123456789';
final saved = await _open(tester, contacts: contacts, group: group);
await tester.tap(find.byTooltip('Remove Carol from group'));
await tester.pumpAndSettle();
await tester.tap(find.text('Save'));
await tester.pumpAndSettle();
await tester.runAsync(() => store.saveGroups(saved));
final loaded = await tester.runAsync(store.loadGroups);
expect(loaded!.single.name, 'Team');
expect(loaded.single.memberKeys, [_alice.publicKeyHex]);
});
for (final scale in [1.3, 2.0]) {
testWidgets('fits a 320dp screen at ${scale}x text', (tester) async {
tester.view.physicalSize = const Size(320, 640);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
await _open(tester, contacts: contacts, group: group, textScale: scale);
expect(tester.takeException(), isNull);
final remove = _button('Remove Alice from group');
expect(remove, findsOneWidget);
expect(tester.getSize(remove).width, greaterThanOrEqualTo(48));
expect(tester.getSize(remove).height, greaterThanOrEqualTo(48));
await tester.tap(remove);
await tester.pumpAndSettle();
expect(_member(_alice), findsNothing);
});
}
}
+73
View File
@@ -0,0 +1,73 @@
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/l10n/app_localizations_en.dart';
import 'package:meshcore_open/models/contact.dart';
import 'package:meshcore_open/widgets/contact_visuals.dart';
Contact _contact(int seed, {required DateTime lastSeen, DateTime? message}) =>
Contact(
publicKey: Uint8List.fromList(List.filled(32, seed)),
name: 'c$seed',
type: 1,
pathLength: -1,
path: Uint8List(0),
lastSeen: lastSeen,
lastMessageAt: message,
);
void main() {
final epoch = DateTime.fromMillisecondsSinceEpoch(0);
final now = DateTime.now();
test('added time orders a contact the radio has no advert time for', () {
final added = now.subtract(const Duration(minutes: 1));
final fromCard = _contact(1, lastSeen: epoch);
final heardHourAgo = _contact(
2,
lastSeen: now.subtract(const Duration(hours: 1)),
);
final addedAt = {fromCard: added};
final sorted = [heardHourAgo, fromCard]
..sort(
(a, b) => resolveContactLastSeen(
b,
addedAt: addedAt[b],
).compareTo(resolveContactLastSeen(a, addedAt: addedAt[a])),
);
expect(resolveContactLastSeen(fromCard, addedAt: added), added);
expect(sorted.first, fromCard);
});
test('a real advert time is never replaced by the added time', () {
final advert = now.subtract(const Duration(days: 30));
final contact = _contact(3, lastSeen: advert);
expect(resolveContactLastSeen(contact, addedAt: now), advert);
});
test('a newer message still wins over the added time', () {
final message = now;
final contact = _contact(4, lastSeen: epoch, message: message);
expect(
resolveContactLastSeen(
contact,
addedAt: now.subtract(const Duration(hours: 1)),
),
message,
);
});
test('a contact never heard shows "not heard yet", not decades ago', () {
final l10n = AppLocalizationsEn();
expect(formatContactLastSeen(l10n, epoch), l10n.contacts_lastSeenNever);
expect(
resolveContactLastSeen(_contact(5, lastSeen: epoch)),
epoch,
reason: 'display label is driven by the advert/message time only',
);
});
}
@@ -0,0 +1,247 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/l10n/app_localizations.dart';
import 'package:meshcore_open/l10n/app_localizations_en.dart';
import 'package:meshcore_open/theme/mesh_theme.dart';
import 'package:meshcore_open/widgets/mesh_ui.dart';
import 'package:meshcore_open/widgets/message_translation_button.dart';
final _l10n = AppLocalizationsEn();
Future<void> _openSheet(
WidgetTester tester, {
Size size = const Size(400, 800),
EdgeInsets padding = const EdgeInsets.only(top: 48, bottom: 34),
EdgeInsets viewPadding = const EdgeInsets.only(top: 48, bottom: 34),
EdgeInsets viewInsets = EdgeInsets.zero,
double textScale = 1.0,
bool initialEnabled = false,
String? initialLanguageCode,
ValueChanged<bool>? onEnabledChanged,
ValueChanged<String?>? onLanguageSelected,
}) async {
tester.view.physicalSize = size;
tester.view.devicePixelRatio = 1.0;
tester.view.padding = FakeViewPadding(
left: padding.left,
top: padding.top,
right: padding.right,
bottom: padding.bottom,
);
tester.view.viewPadding = FakeViewPadding(
left: viewPadding.left,
top: viewPadding.top,
right: viewPadding.right,
bottom: viewPadding.bottom,
);
tester.view.viewInsets = FakeViewPadding(
left: viewInsets.left,
top: viewInsets.top,
right: viewInsets.right,
bottom: viewInsets.bottom,
);
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
addTearDown(tester.view.resetPadding);
addTearDown(tester.view.resetViewPadding);
addTearDown(tester.view.resetViewInsets);
await tester.pumpWidget(
MaterialApp(
theme: MeshTheme.light(),
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
builder: (context, child) {
final media = MediaQuery.of(context);
return MediaQuery(
data: media.copyWith(
size: size,
padding: padding,
viewPadding: viewPadding,
viewInsets: viewInsets,
textScaler: TextScaler.linear(textScale),
),
child: child!,
);
},
home: Builder(
builder: (context) => Scaffold(
body: Center(
child: MessageTranslationButton(
enabled: initialEnabled,
languageCode: initialLanguageCode,
onPressed: () => showMessageTranslationSheet(
context: context,
enabled: initialEnabled,
selectedLanguageCode: initialLanguageCode,
onEnabledChanged: onEnabledChanged ?? (_) {},
onLanguageSelected: onLanguageSelected ?? (_) {},
),
),
),
),
),
),
);
await tester.pumpAndSettle();
await tester.tap(find.byType(MessageTranslationButton));
await tester.pumpAndSettle();
}
void main() {
testWidgets(
'sheet respects top safe area, caps height at <= 85%, and shrinks when filtered',
(tester) async {
const screenSize = Size(400, 800);
await _openSheet(
tester,
size: screenSize,
padding: const EdgeInsets.only(top: 48, bottom: 34),
viewPadding: const EdgeInsets.only(top: 48, bottom: 34),
);
expect(find.byType(BottomSheetHeader), findsOneWidget);
expect(find.text(_l10n.translation_messageTranslation), findsOneWidget);
final sheetFinder = find.byType(BottomSheet);
final sheetRect = tester.getRect(sheetFinder);
final titleTop = tester
.getTopLeft(find.text(_l10n.translation_messageTranslation))
.dy;
// Top edge must stay well below the 48px Android status bar inset.
expect(sheetRect.top, greaterThan(48.0));
expect(sheetRect.top, greaterThanOrEqualTo(screenSize.height * 0.15));
expect(sheetRect.height, lessThanOrEqualTo(screenSize.height * 0.85));
expect(titleTop - sheetRect.top, inInclusiveRange(16.0, 36.0));
final unfilteredHeight = sheetRect.height;
// Filtering down to a single language shrinks the sheet naturally.
await tester.enterText(find.byType(TextField), 'Spanish');
await tester.pumpAndSettle();
final filteredRect = tester.getRect(sheetFinder);
expect(filteredRect.height, lessThan(unfilteredHeight));
expect(filteredRect.top, greaterThan(sheetRect.top));
},
);
testWidgets(
'toggling switch, filtering languages, and selecting target or app language works',
(tester) async {
bool? latestEnabled;
String? latestLanguage = 'fr';
await _openSheet(
tester,
initialEnabled: false,
initialLanguageCode: latestLanguage,
onEnabledChanged: (value) => latestEnabled = value,
onLanguageSelected: (code) => latestLanguage = code,
);
expect(find.text(_l10n.translation_composerDisabledHint), findsOneWidget);
await tester.tap(
find.widgetWithText(
SwitchListTile,
_l10n.translation_translateBeforeSending,
),
);
await tester.pumpAndSettle();
expect(latestEnabled, isTrue);
expect(find.text(_l10n.translation_composerEnabledHint), findsOneWidget);
// Filter by language name and select Spanish ('es').
await tester.enterText(find.byType(TextField), 'Spanish');
await tester.pumpAndSettle();
expect(find.widgetWithText(ListTile, 'Spanish'), findsOneWidget);
expect(find.widgetWithText(ListTile, 'German'), findsNothing);
await tester.tap(find.widgetWithText(ListTile, 'Spanish'));
await tester.pumpAndSettle();
expect(latestLanguage, 'es');
expect(find.byType(BottomSheet), findsNothing);
// Re-open and select "Use app language" (null).
await tester.tap(find.byType(MessageTranslationButton));
await tester.pumpAndSettle();
await tester.tap(
find.widgetWithText(ListTile, _l10n.translation_useAppLanguage),
);
await tester.pumpAndSettle();
expect(latestLanguage, isNull);
expect(find.byType(BottomSheet), findsNothing);
},
);
testWidgets(
'avoids layout overflow at 320dp width with 1.3x and 2.0x text scale and keyboard insets',
(tester) async {
for (final textScale in [1.0, 1.3, 2.0]) {
for (final keyboardInset in [0.0, 300.0]) {
bool? toggled;
String? chosenLanguage;
await _openSheet(
tester,
size: const Size(320, 568),
padding: const EdgeInsets.only(top: 48, bottom: 34),
viewPadding: const EdgeInsets.only(top: 48, bottom: 34),
viewInsets: EdgeInsets.only(bottom: keyboardInset),
textScale: textScale,
onEnabledChanged: (value) => toggled = value,
onLanguageSelected: (code) => chosenLanguage = code,
);
expect(tester.takeException(), isNull);
final sheetRect = tester.getRect(find.byType(BottomSheet));
expect(sheetRect.top, greaterThanOrEqualTo(48.0));
await Scrollable.ensureVisible(
tester.element(find.byType(Switch)),
alignment: 0.5,
);
await tester.pumpAndSettle();
await tester.tap(find.byType(Switch));
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
expect(toggled, isTrue);
await Scrollable.ensureVisible(
tester.element(find.byType(TextField)),
alignment: 0.5,
);
await tester.pumpAndSettle();
await tester.enterText(find.byType(TextField), 'de');
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
final germanTile = find.widgetWithText(
ListTile,
'German',
skipOffstage: false,
);
await Scrollable.ensureVisible(
tester.element(germanTile),
alignment: 0.5,
);
await tester.pumpAndSettle();
await tester.tap(germanTile);
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
expect(chosenLanguage, 'de');
}
}
},
);
}
+831
View File
@@ -0,0 +1,831 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
import 'package:meshcore_open/l10n/app_localizations.dart';
import 'package:meshcore_open/models/image_codec_support.dart';
import 'package:meshcore_open/models/translation_support.dart';
import 'package:meshcore_open/services/app_settings_service.dart';
import 'package:meshcore_open/services/image_codec_service.dart';
import 'package:meshcore_open/services/image_codec_settings_store.dart';
import 'package:meshcore_open/services/translation_file_store.dart';
import 'package:meshcore_open/services/translation_service.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:meshcore_open/theme/mesh_theme.dart';
import 'package:meshcore_open/widgets/image_codec_models_section.dart';
import 'package:meshcore_open/widgets/mesh_nav_tile.dart';
import 'package:meshcore_open/widgets/model_download_list.dart';
import 'package:meshcore_open/widgets/settings_reveal.dart';
import 'package:meshcore_open/widgets/translation_settings_section.dart';
import 'package:provider/provider.dart';
import 'package:provider/single_child_widget.dart';
import 'package:shared_preferences/shared_preferences.dart';
class _MemoryTranslationFileStore extends TranslationFileStore {
final Map<String, int> _files = {};
@override
Future<String> modelDirectoryPath() async => '/memory/translation_models';
@override
Future<List<TranslationModelRecord>> scanDownloadedModels() async => const [];
@override
Future<void> deleteModel(TranslationModelRecord model) async {
_files.remove(model.localPath);
}
@override
Future<void> deleteFile(String path) async {
_files.remove(path);
}
@override
Future<DownloadedModelFile> writeModelBytes({
required String fileName,
required Stream<List<int>> chunks,
}) async {
var total = 0;
await for (final chunk in chunks) {
total += chunk.length;
}
final path = '/memory/translation_models/$fileName';
_files[path] = total;
return DownloadedModelFile(localPath: path, fileSizeBytes: total);
}
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
setUp(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
});
Future<void> pump(
WidgetTester tester,
Widget home, {
List<SingleChildWidget> providers = const [],
double textScale = 1,
Size size = const Size(400, 900),
}) async {
tester.view.physicalSize = size;
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
final app = MaterialApp(
theme: MeshTheme.dark(),
locale: const Locale('en'),
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
builder: (context, child) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(textScaler: TextScaler.linear(textScale)),
child: child!,
),
home: Scaffold(body: SingleChildScrollView(child: home)),
);
await tester.pumpWidget(
providers.isEmpty ? app : MultiProvider(providers: providers, child: app),
);
}
testWidgets('rows share name, size, status and one action', (tester) async {
var downloaded = 0;
var cancelled = 0;
var removed = 0;
var selected = 0;
await pump(
tester,
ModelDownloadList(
items: [
ModelDownloadItem(
id: 'new',
name: 'Preset model',
sizeBytes: 958 * 1024 * 1024,
status: ModelDownloadStatus.notDownloaded,
onDownload: () => downloaded++,
),
ModelDownloadItem(
id: 'busy',
name: 'Preset model',
sizeBytes: 958 * 1024 * 1024,
status: ModelDownloadStatus.downloading,
progress: 0.4,
downloadedBytes: 400 * 1024 * 1024,
totalBytes: 958 * 1024 * 1024,
onCancel: () => cancelled++,
),
ModelDownloadItem(
id: 'ready',
name: 'Installed model',
sizeBytes: 1100 * 1024 * 1024,
status: ModelDownloadStatus.ready,
selected: true,
onDelete: () => removed++,
onSelect: () => selected++,
),
ModelDownloadItem(
id: 'bad',
name: 'Broken model',
status: ModelDownloadStatus.error,
detail: 'HTTP 404',
onDownload: () => downloaded++,
),
],
),
);
expect(find.textContaining('958 MB'), findsWidgets);
expect(find.textContaining('Not downloaded'), findsOneWidget);
expect(find.textContaining('Downloading'), findsOneWidget);
expect(find.textContaining('Ready'), findsOneWidget);
expect(find.textContaining('Active'), findsOneWidget);
expect(find.textContaining("Couldn't download"), findsOneWidget);
expect(find.text('HTTP 404'), findsOneWidget);
expect(find.textContaining('400.0 / 958.0 MB (40%)'), findsOneWidget);
expect(find.byType(LinearProgressIndicator), findsOneWidget);
expect(find.textContaining('http'), findsNothing);
await tester.tap(find.byKey(const ValueKey('model-download-new')));
await tester.tap(find.byKey(const ValueKey('model-cancel-busy')));
await tester.tap(find.byKey(const ValueKey('model-remove-ready')));
await tester.tap(find.text('Installed model'));
expect(downloaded, 1);
expect(cancelled, 1);
expect(removed, 1);
// The ready row is already selected, so onSelect is still wired here and
// the row tap invokes it. Callers omit onSelect once it is active.
expect(selected, 1);
});
testWidgets('a long row wraps at 320dp and text scale 2', (tester) async {
final overflows = <String>[];
final previous = FlutterError.onError;
FlutterError.onError = (details) {
if (details.exceptionAsString().contains('overflowed')) {
overflows.add(details.exceptionAsString().split('\n').first);
return;
}
previous?.call(details);
};
addTearDown(() => FlutterError.onError = previous);
await pump(
tester,
ModelDownloadList(
items: [
ModelDownloadItem(
id: 'long',
name: 'Tencent HY-MT 1.5 1.8B Q4_K_M',
sizeBytes: 1140000000,
status: ModelDownloadStatus.downloading,
progress: 0.2,
downloadedBytes: 200 * 1024 * 1024,
totalBytes: 1140000000,
onCancel: () {},
),
],
),
textScale: 2,
size: const Size(320, 568),
);
expect(overflows, isEmpty);
expect(find.text('Tencent HY-MT 1.5 1.8B Q4_K_M'), findsOneWidget);
});
testWidgets('translation presets and installs share one list', (
tester,
) async {
final settings = AppSettingsService();
await settings.loadSettings();
await settings.setTranslationEnabled(true);
final preset = translationPresetModels.first;
final other = translationPresetModels[1];
await settings.setTranslationDownloadedModels([
TranslationModelRecord(
id: preset.id,
name: preset.name,
sourceUrl: preset.sourceUrl,
localPath: '/tmp/model.gguf',
downloadedAt: DateTime.utc(2026, 1, 1),
fileSizeBytes: 1140000000,
),
TranslationModelRecord(
id: other.id,
name: other.name,
sourceUrl: other.sourceUrl,
localPath: '/tmp/other.gguf',
downloadedAt: DateTime.utc(2026, 1, 2),
fileSizeBytes: 1400 * 1024 * 1024,
),
]);
await settings.setTranslationSelectedModelId(preset.id);
final translation = TranslationService(settings);
await pump(
tester,
const TranslationSettingsSection(),
providers: [
ChangeNotifierProvider<AppSettingsService>.value(value: settings),
ChangeNotifierProvider<TranslationService>.value(value: translation),
],
);
expect(find.text('Tencent HY-MT 1.5 1.8B Q4_K_M'), findsOneWidget);
expect(find.text('Tencent HY-MT 1.5 1.8B Q6_K'), findsOneWidget);
expect(find.textContaining('Ready'), findsNWidgets(2));
expect(find.textContaining('Active'), findsOneWidget);
expect(find.textContaining('Not downloaded'), findsNothing);
expect(find.text('Downloaded model'), findsNothing);
expect(find.text('Preset Hugging Face model'), findsNothing);
expect(find.text('Manual model URL'), findsOneWidget);
expect(find.textContaining('huggingface.co'), findsNothing);
expect(find.textContaining('.gguf'), findsNothing);
await tester.tap(find.text('Tencent HY-MT 1.5 1.8B Q6_K'));
await tester.pump();
expect(settings.settings.translationSelectedModelId, other.id);
await tester.tap(find.byKey(ValueKey('model-remove-${preset.id}')));
await tester.pump();
await tester.pump(const Duration(milliseconds: 50));
expect(
settings.settings.translationDownloadedModels.map((model) => model.id),
[other.id],
);
expect(find.textContaining('Not downloaded'), findsOneWidget);
});
testWidgets('a custom download stays visible after settings is reopened', (
tester,
) async {
final settings = AppSettingsService();
await settings.loadSettings();
await settings.setTranslationEnabled(true);
final translation = TranslationService(settings);
addTearDown(translation.dispose);
// The page that started the download is gone. Only the service still
// knows which file is in flight.
translation.debugSetActiveDownload(
sourceUrl: 'http://127.0.0.1/Tencent-demo.gguf',
fileName: 'Tencent-demo.gguf',
downloadedBytes: 400 * 1024,
totalBytes: 1024 * 1024,
);
final providers = <SingleChildWidget>[
ChangeNotifierProvider<AppSettingsService>.value(value: settings),
ChangeNotifierProvider<TranslationService>.value(value: translation),
];
await pump(
tester,
const TranslationSettingsSection(),
providers: providers,
);
expect(find.text('Tencent-demo'), findsOneWidget);
expect(find.textContaining('Downloading'), findsOneWidget);
expect(find.textContaining('0.4 / 1.0 MB (39%)'), findsOneWidget);
expect(find.byTooltip('Cancel'), findsOneWidget);
await pump(tester, const SizedBox.shrink(), providers: providers);
await pump(
tester,
const TranslationSettingsSection(),
providers: providers,
);
expect(find.text('Tencent-demo'), findsOneWidget);
expect(find.textContaining('Downloading'), findsOneWidget);
expect(find.byTooltip('Cancel'), findsOneWidget);
expect(find.text('Tencent HY-MT 1.5 1.8B Q4_K_M'), findsOneWidget);
final preset = translationPresetModels.first;
translation.debugSetActiveDownload(
sourceUrl: preset.sourceUrl,
fileName: preset.name,
modelId: preset.id,
displayedFileName: 'Merging chunks...',
);
await tester.pump();
expect(find.text('Tencent-demo'), findsNothing);
expect(find.textContaining('Downloading'), findsOneWidget);
expect(find.textContaining('Merging downloaded chunks'), findsOneWidget);
expect(find.byTooltip('Cancel'), findsOneWidget);
});
testWidgets(
'reopening settings during a custom download supports cancel, completion, and failure',
(tester) async {
StreamController<List<int>>? getStream;
final settings = AppSettingsService();
await settings.loadSettings();
await settings.setTranslationEnabled(true);
final translation = TranslationService(
settings,
fileStore: _MemoryTranslationFileStore(),
clientFactory: () => MockClient.streaming((request, _) async {
if (request.method == 'HEAD') {
return http.StreamedResponse(
const Stream<List<int>>.empty(),
200,
contentLength: 1024,
);
}
final controller = StreamController<List<int>>();
getStream = controller;
return http.StreamedResponse(
controller.stream,
200,
contentLength: 1024,
);
}),
);
addTearDown(translation.dispose);
final providers = <SingleChildWidget>[
ChangeNotifierProvider<AppSettingsService>.value(value: settings),
ChangeNotifierProvider<TranslationService>.value(value: translation),
];
Future<void> startCustomDownload(String url) async {
await pump(
tester,
const TranslationSettingsSection(),
providers: providers,
);
await tester.ensureVisible(find.byType(TextField));
await tester.enterText(find.byType(TextField), url);
await tester.pump();
final urlFieldDownload = find.descendant(
of: find.byType(TextField),
matching: find.byTooltip('Download'),
);
await tester.ensureVisible(urlFieldDownload);
await tester.tap(urlFieldDownload);
await tester.pump();
await tester.pump();
}
Future<void> leaveAndReopen() async {
await pump(tester, const SizedBox.shrink(), providers: providers);
await pump(
tester,
const TranslationSettingsSection(),
providers: providers,
);
}
// 1. Cancel after reopen.
await startCustomDownload('https://example.com/Custom-Cancel.gguf');
await tester.pump(Duration.zero);
getStream!.add(List<int>.filled(512, 1));
await tester.pump(Duration.zero);
expect(translation.downloadedBytes, 512);
await leaveAndReopen();
expect(find.text('Custom-Cancel'), findsOneWidget);
expect(find.textContaining('Downloading'), findsOneWidget);
expect(find.byTooltip('Cancel'), findsOneWidget);
expect(
find.byKey(
ValueKey('model-download-${translationPresetModels.first.id}'),
),
findsNothing,
);
expect(
tester
.widget<IconButton>(
find.descendant(
of: find.byType(TextField),
matching: find.byType(IconButton),
),
)
.onPressed,
isNull,
);
await tester.ensureVisible(find.byTooltip('Cancel'));
await tester.tap(find.byTooltip('Cancel'));
await tester.pump();
expect(translation.lastError, 'Download stopped.');
getStream!.add(List<int>.filled(16, 1));
await tester.runAsync(
() => Future<void>.delayed(const Duration(milliseconds: 20)),
);
await tester.pump();
expect(translation.isDownloading, isFalse);
expect(find.text('Custom-Cancel'), findsNothing);
expect(find.text('Download stopped.'), findsNothing);
// 2. Complete after reopen.
await startCustomDownload('https://example.com/Custom-Complete.gguf');
await tester.pump(Duration.zero);
getStream!.add(List<int>.filled(512, 2));
await tester.pump(Duration.zero);
await leaveAndReopen();
expect(find.text('Custom-Complete'), findsOneWidget);
expect(find.textContaining('Downloading'), findsOneWidget);
getStream!.add(List<int>.filled(512, 2));
unawaited(getStream!.close());
await tester.runAsync(
() => Future<void>.delayed(const Duration(milliseconds: 20)),
);
await tester.pump();
expect(find.text('Custom-Complete'), findsOneWidget);
expect(find.textContaining('Ready'), findsOneWidget);
expect(find.textContaining('Active'), findsOneWidget);
// 3. Failure after reopen.
await startCustomDownload('https://example.com/Custom-Fail.gguf');
await tester.pump(Duration.zero);
getStream!.add(List<int>.filled(256, 3));
await tester.pump(Duration.zero);
await leaveAndReopen();
expect(find.text('Custom-Fail'), findsOneWidget);
expect(find.textContaining('Downloading'), findsOneWidget);
getStream!.addError(http.ClientException('Connection reset'));
unawaited(getStream!.close());
await tester.runAsync(
() => Future<void>.delayed(const Duration(milliseconds: 20)),
);
await tester.pump();
expect(find.text('Custom-Fail'), findsOneWidget);
expect(find.textContaining("Couldn't download"), findsOneWidget);
expect(find.textContaining('Connection reset'), findsOneWidget);
// Error is shown in the model row detail, not duplicated below the URL field.
expect(find.text('ClientException: Connection reset'), findsNothing);
expect(
find.byKey(
const ValueKey('model-download-https://example.com/Custom-Fail.gguf'),
),
findsOneWidget,
);
},
);
testWidgets('an installed image bundle is one ready row', (tester) async {
final spec = imageCodecPresetModels.single;
final settings = AppSettingsService();
final store = InMemoryImageCodecSettingsStore(
ImageCodecPreferences(
enabled: true,
selectedModelId: spec.id,
downloadedModels: [
ImageCodecModelRecord(
id: spec.id,
name: spec.fileName,
sourceUrl: spec.graph.sourceUrl,
localPath: '/tmp/${spec.fileName}',
downloadedAt: DateTime.utc(2026, 1, 1),
fileSizeBytes: spec.totalSizeBytes,
assetFileNames: [for (final asset in spec.assets) asset.fileName],
assetRoles: {
for (final asset in spec.assets) asset.fileName: asset.role,
},
bundleVersion: kImageCodecBundleVersion,
),
],
),
);
final codec = ImageCodecService(settings, settingsStore: store);
await pump(
tester,
const ImageCodecModelsSection(),
providers: [
ChangeNotifierProvider<ImageCodecService>.value(value: codec),
],
);
expect(find.text(spec.label), findsOneWidget);
expect(find.textContaining(spec.fileName), findsNothing);
expect(find.textContaining('.onnx'), findsNothing);
expect(find.textContaining('958 MB'), findsOneWidget);
expect(find.textContaining('Ready'), findsOneWidget);
expect(find.textContaining('Active'), findsOneWidget);
expect(find.byTooltip('Remove model'), findsOneWidget);
expect(find.byTooltip('Download'), findsNothing);
});
testWidgets('a partial image bundle stays on the preset row', (tester) async {
final spec = imageCodecPresetModels.single;
final settings = AppSettingsService();
final store = InMemoryImageCodecSettingsStore(
ImageCodecPreferences(
enabled: true,
downloadedModels: [
ImageCodecModelRecord(
id: spec.id,
name: spec.fileName,
sourceUrl: spec.graph.sourceUrl,
localPath: '/tmp/${spec.fileName}',
downloadedAt: DateTime.utc(2026, 1, 1),
fileSizeBytes: spec.graph.sizeBytes,
assetFileNames: [spec.fileName],
bundleVersion: 0,
),
],
),
);
final codec = ImageCodecService(settings, settingsStore: store);
await pump(
tester,
const ImageCodecModelsSection(),
providers: [
ChangeNotifierProvider<ImageCodecService>.value(value: codec),
],
);
expect(find.text(spec.label), findsOneWidget);
expect(find.textContaining(spec.fileName), findsNothing);
expect(find.textContaining('Incomplete'), findsOneWidget);
expect(find.byTooltip('Download'), findsOneWidget);
expect(find.byTooltip('Remove model'), findsOneWidget);
});
testWidgets(
'notDownloaded uses non-download leading icon and aligns icons cleanly',
(tester) async {
await pump(
tester,
ModelDownloadList(
items: [
ModelDownloadItem(
id: 'new',
name: 'Uninstalled model',
sizeBytes: 958 * 1024 * 1024,
status: ModelDownloadStatus.notDownloaded,
onDownload: () {},
),
ModelDownloadItem(
id: 'incomplete',
name: 'Partial model',
sizeBytes: 500 * 1024 * 1024,
status: ModelDownloadStatus.notDownloaded,
statusLabel: 'Incomplete',
onDownload: () {},
onDelete: () {},
),
ModelDownloadItem(
id: 'busy',
name: 'Downloading model',
sizeBytes: 958 * 1024 * 1024,
status: ModelDownloadStatus.downloading,
progress: 0.4,
downloadedBytes: 400 * 1024 * 1024,
totalBytes: 958 * 1024 * 1024,
onCancel: () {},
),
ModelDownloadItem(
id: 'active',
name: 'Active model',
sizeBytes: 1100 * 1024 * 1024,
status: ModelDownloadStatus.ready,
selected: true,
onDelete: () {},
),
ModelDownloadItem(
id: 'bad',
name: 'Failed model',
status: ModelDownloadStatus.error,
detail:
'Download failed because the server closed the connection unexpectedly.',
onDownload: () {},
),
],
),
);
final newRow = find.byKey(const ValueKey('model-row-new'));
final newLeading = find.descendant(
of: newRow,
matching: find.byIcon(Icons.memory_outlined),
);
expect(newLeading, findsOneWidget);
final newTrailingButton = find.byKey(
const ValueKey('model-download-new'),
);
final newTrailingIcon = find.descendant(
of: newTrailingButton,
matching: find.byIcon(Icons.download_outlined),
);
expect(newTrailingIcon, findsOneWidget);
// Leading icon must differ from trailing download icon.
expect(
tester.widget<Icon>(newLeading).icon,
isNot(tester.widget<Icon>(newTrailingIcon).icon),
);
expect(tester.getSize(newLeading), const Size(24, 24));
expect(
tester.getCenter(newLeading).dy,
closeTo(tester.getCenter(newTrailingIcon).dy, 1.0),
);
for (final (rowKey, buttonKey) in [
('model-row-incomplete', 'model-download-incomplete'),
('model-row-busy', 'model-cancel-busy'),
('model-row-active', 'model-remove-active'),
('model-row-bad', 'model-download-bad'),
]) {
final row = find.byKey(ValueKey(rowKey));
final button = find.byKey(ValueKey(buttonKey));
final title = find
.descendant(of: row, matching: find.byType(Text))
.first;
final leading = find
.descendant(of: row, matching: find.byType(Icon))
.first;
final spinner = find.descendant(
of: row,
matching: find.byType(CircularProgressIndicator),
);
final leadingFinder = spinner.evaluate().isNotEmpty ? spinner : leading;
expect(
tester.getRect(leadingFinder).right,
lessThan(tester.getRect(title).left),
);
expect(
tester.getCenter(leadingFinder).dy,
closeTo(tester.getCenter(button).dy, 1.0),
reason: '$rowKey leading indicator and trailing button must center',
);
}
},
);
testWidgets(
'TranslationSettingsSection hides sub-options when off, reveals on enable, and aligns rows',
(tester) async {
final settings = AppSettingsService();
await settings.loadSettings();
final translation = TranslationService(settings);
addTearDown(translation.dispose);
await pump(
tester,
const TranslationSettingsSection(),
providers: [
ChangeNotifierProvider<AppSettingsService>.value(value: settings),
ChangeNotifierProvider<TranslationService>.value(value: translation),
],
);
final context = tester.element(find.byType(TranslationSettingsSection));
final l10n = AppLocalizations.of(context);
expect(find.text(l10n.translation_enableTitle), findsOneWidget);
expect(find.text(l10n.translation_autoIncomingTitle), findsNothing);
expect(find.text(l10n.translation_composerTitle), findsNothing);
expect(find.text(l10n.translation_targetLanguage), findsNothing);
expect(find.text('Tencent HY-MT 1.5 1.8B Q4_K_M'), findsNothing);
expect(find.text(l10n.translation_manualUrlLabel), findsNothing);
await tester.tap(find.text(l10n.translation_enableTitle));
await tester.pump();
await tester.pump(RevealOnEnable.duration);
await tester.pumpAndSettle();
expect(find.text(l10n.translation_autoIncomingTitle), findsOneWidget);
expect(find.text(l10n.translation_composerTitle), findsOneWidget);
expect(find.text(l10n.translation_targetLanguage), findsOneWidget);
expect(find.text('Tencent HY-MT 1.5 1.8B Q4_K_M'), findsOneWidget);
expect(find.text(l10n.translation_manualUrlLabel), findsOneWidget);
final revealFinder = find.byType(SettingsReveal);
expect(revealFinder, findsOneWidget);
final revealMaterial = tester.widget<Material>(
find
.descendant(of: revealFinder, matching: find.byType(Material))
.first,
);
expect(
revealMaterial.color,
Theme.of(context).colorScheme.surfaceContainerHighest,
);
// Switches and Target language row are enabled when visible.
final autoIncomingSwitch = tester.widget<SwitchListTile>(
find.ancestor(
of: find.text(l10n.translation_autoIncomingTitle),
matching: find.byType(SwitchListTile),
),
);
expect(autoIncomingSwitch.onChanged, isNotNull);
// Leading icons, titles, and trailing icons align across Target language
// (MeshNavTile) and revealed ModelDownloadList rows.
final targetTile = find.ancestor(
of: find.text(l10n.translation_targetLanguage),
matching: find.byType(MeshNavTile),
);
final targetIcon = find.descendant(
of: targetTile,
matching: find.byIcon(Icons.language),
);
final targetChevron = find.descendant(
of: targetTile,
matching: find.byIcon(Icons.chevron_right),
);
final firstPreset = translationPresetModels.first;
final modelRow = find.byKey(ValueKey('model-row-${firstPreset.id}'));
final modelLeadingIcon = find.descendant(
of: modelRow,
matching: find.byIcon(Icons.memory_outlined),
);
final modelTitle = find.descendant(
of: modelRow,
matching: find.text('Tencent HY-MT 1.5 1.8B Q4_K_M'),
);
final modelDownloadIcon = find.descendant(
of: find.byKey(ValueKey('model-download-${firstPreset.id}')),
matching: find.byIcon(Icons.download_outlined),
);
expect(modelLeadingIcon, findsOneWidget);
expect(
tester.getRect(modelLeadingIcon).left,
closeTo(tester.getRect(targetIcon).left, 0.5),
);
expect(
tester.getRect(modelTitle).left,
closeTo(
tester.getRect(find.text(l10n.translation_targetLanguage)).left,
0.5,
),
);
expect(
tester.getRect(modelDownloadIcon).right,
closeTo(tester.getRect(targetChevron).right, 0.5),
);
// Toggling off hides sub-options again.
await tester.tap(find.text(l10n.translation_enableTitle));
await tester.pumpAndSettle();
expect(find.text(l10n.translation_autoIncomingTitle), findsNothing);
expect(find.text(l10n.translation_targetLanguage), findsNothing);
expect(find.text(l10n.translation_manualUrlLabel), findsNothing);
},
);
for (final scale in [1.3, 2.0]) {
testWidgets(
'translation section and two-action model rows fit 320dp at ${scale}x',
(tester) async {
final overflows = <String>[];
final previous = FlutterError.onError;
FlutterError.onError = (details) {
if (details.exceptionAsString().contains('overflowed')) {
overflows.add(details.exceptionAsString().split('\n').first);
return;
}
previous?.call(details);
};
addTearDown(() => FlutterError.onError = previous);
final settings = AppSettingsService();
await settings.loadSettings();
await settings.setTranslationEnabled(true);
final translation = TranslationService(settings);
addTearDown(translation.dispose);
await pump(
tester,
Column(
children: [
const TranslationSettingsSection(),
ModelDownloadList(
items: [
ModelDownloadItem(
id: 'incomplete',
name: 'Tencent HY-MT 1.5 1.8B Q4_K_M',
sizeBytes: 958 * 1024 * 1024,
status: ModelDownloadStatus.notDownloaded,
statusLabel: 'Incomplete',
onDownload: () {},
onDelete: () {},
),
],
),
],
),
providers: [
ChangeNotifierProvider<AppSettingsService>.value(value: settings),
ChangeNotifierProvider<TranslationService>.value(
value: translation,
),
],
textScale: scale,
size: const Size(320, 568),
);
expect(overflows, isEmpty);
},
);
}
}
+512
View File
@@ -0,0 +1,512 @@
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/connector/meshcore_protocol.dart';
import 'package:meshcore_open/l10n/app_localizations.dart';
import 'package:meshcore_open/models/contact.dart';
import 'package:meshcore_open/widgets/path_editor_sheet.dart';
Contact _repeater(String name, List<int> prefix) {
final key = Uint8List(32);
for (var i = 0; i < prefix.length; i++) {
key[i] = prefix[i];
}
return Contact(
publicKey: key,
name: name,
type: advTypeRepeater,
pathLength: -1,
path: Uint8List(0),
lastSeen: DateTime.fromMillisecondsSinceEpoch(0),
);
}
final _contacts = [
_repeater('100 Acre', [0x11, 0x22]),
_repeater('Acreage North', [0x33, 0x44]),
_repeater('My Acre Site', [0x55, 0x66]),
_repeater('2E0HQR-R', [0x2E, 0x0A]),
_repeater('CR1', [0x60, 0x60]),
for (var i = 0; i < 24; i++) _repeater('Repeater $i', [0xA0, i]),
];
Future<void> _pumpSheet(
WidgetTester tester, {
Size size = const Size(400, 700),
double keyboard = 0,
double textScale = 1.0,
List<int> initialPath = const [],
}) async {
tester.view.physicalSize = size;
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
await tester.pumpWidget(
MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: MediaQuery(
data: MediaQueryData(
size: size,
viewInsets: EdgeInsets.only(bottom: keyboard),
textScaler: TextScaler.linear(textScale),
),
child: Scaffold(
body: SizedBox(
width: size.width,
height: size.height - keyboard,
child: PathEditorSheet(
key: UniqueKey(),
availableContacts: _contacts,
initialPath: initialPath,
pathHashByteWidth: 2,
),
),
),
),
),
);
await tester.pumpAndSettle();
}
Finder _fallbackScrollable() {
return find.byElementPredicate((element) {
if (element.widget is! Scrollable) return false;
var hasHex = false;
void visit(Element node) {
node.visitChildren((child) {
if (child.widget.key == const Key('path-editor-hex-field')) {
hasHex = true;
}
visit(child);
});
}
visit(element);
return hasHex;
});
}
Future<void> _revealInFallback(
WidgetTester tester,
Finder scrollable,
Finder target,
) async {
final state = tester.state<ScrollableState>(scrollable);
final view = tester.getRect(
find.byKey(const Key('path-editor-scroll-fallback')),
);
final step = (view.height / 2).clamp(2.0, 24.0);
for (var i = 0; i < 400; i++) {
final rect = tester.getRect(target);
if (rect.center.dy >= view.top && rect.center.dy <= view.bottom) return;
final next = (state.position.pixels + step).clamp(
0.0,
state.position.maxScrollExtent,
);
expect(next, greaterThan(state.position.pixels));
state.position.jumpTo(next);
await tester.pump();
}
fail(
'Could not scroll $target into $view (last rect=${tester.getRect(target)}, pixels=${state.position.pixels})',
);
}
List<String> _repeaterNames(WidgetTester tester) {
return tester
.widgetList<Text>(
find.descendant(
of: find.byKey(const Key('path-editor-repeater-list')),
matching: find.byType(Text),
),
)
.map((text) => text.data)
.whereType<String>()
.where((text) => !text.contains('•'))
.toList();
}
void main() {
testWidgets('prefix matches are listed before other substring matches', (
tester,
) async {
await _pumpSheet(tester);
await tester.enterText(
find.byKey(const Key('path-editor-search-field')),
'acre',
);
await tester.pumpAndSettle();
final visible = _repeaterNames(tester);
expect(visible.first, 'Acreage North');
expect(visible[1], '100 Acre');
await tester.scrollUntilVisible(
find.text('My Acre Site'),
80,
scrollable: find.descendant(
of: find.byKey(const Key('path-editor-repeater-list')),
matching: find.byType(Scrollable),
),
);
expect(find.text('My Acre Site'), findsOneWidget);
});
testWidgets('search matches a hop hash the name does not contain', (
tester,
) async {
await _pumpSheet(tester);
await tester.enterText(
find.byKey(const Key('path-editor-search-field')),
'6060',
);
await tester.pumpAndSettle();
expect(find.text('No repeaters or room servers found.'), findsNothing);
expect(_repeaterNames(tester), ['CR1']);
});
testWidgets('hex entry is reachable without scrolling the repeater list', (
tester,
) async {
await _pumpSheet(tester, size: const Size(400, 900));
expect(
find.byKey(const Key('path-editor-hex-field')).hitTestable(),
findsOneWidget,
);
expect(find.text('Hex prefixes'), findsOneWidget);
expect(
find.text('4 hex characters per hop, separated by commas'),
findsOneWidget,
);
});
testWidgets('an added hop stays fully visible with the keyboard open', (
tester,
) async {
await _pumpSheet(
tester,
size: const Size(390, 640),
keyboard: 320,
initialPath: [0x60, 0x60],
);
final tile = find.ancestor(
of: find.byIcon(Icons.remove_circle_outline),
matching: find.byType(ListTile),
);
expect(tile.hitTestable(), findsOneWidget);
final title = tester.getRect(find.text('Build Path'));
final hopRect = tester.getRect(tile);
final sheet = tester.getRect(find.byType(PathEditorSheet));
expect(hopRect.top, greaterThanOrEqualTo(title.bottom));
expect(hopRect.bottom, lessThanOrEqualTo(sheet.bottom));
expect(hopRect.height, greaterThanOrEqualTo(48));
expect(find.text('CR1').hitTestable(), findsWidgets);
expect(find.text('6060').hitTestable(), findsWidgets);
expect(
find.byKey(const Key('path-editor-hex-field')).hitTestable(),
findsOneWidget,
);
expect(find.byKey(const Key('path-editor-scroll-fallback')), findsNothing);
expect(tester.takeException(), isNull);
});
testWidgets('an invalid hex path does not overflow a keyboard-height sheet', (
tester,
) async {
await _pumpSheet(
tester,
size: const Size(390, 640),
keyboard: 320,
initialPath: [0x60, 0x60, 0x11, 0x22],
);
await tester.enterText(
find.byKey(const Key('path-editor-hex-field')),
'ZZ',
);
await tester.pumpAndSettle();
expect(find.textContaining('Invalid'), findsOneWidget);
expect(tester.takeException(), isNull);
expect(
find.byIcon(Icons.remove_circle_outline).hitTestable(),
findsWidgets,
);
final button = tester.getRect(find.text('Use this path'));
final sheet = tester.getRect(find.byType(PathEditorSheet));
expect(button.bottom, lessThanOrEqualTo(sheet.bottom + 1));
});
testWidgets(
'3-line hex error on a 320px keyboard sheet keeps controls scrollable',
(tester) async {
await _pumpSheet(
tester,
size: const Size(390, 640),
keyboard: 320,
initialPath: [0x60, 0x60, 0x11, 0x22],
);
await tester.enterText(
find.byKey(const Key('path-editor-hex-field')),
'AA, BB, CC, DD, EE, FF, GG, HH, II, JJ, KK',
);
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
expect(
find.byKey(const Key('path-editor-scroll-fallback')),
findsOneWidget,
);
expect(
tester
.widget<TextField>(find.byKey(const Key('path-editor-hex-field')))
.focusNode
?.hasFocus,
isTrue,
);
final scrollable = _fallbackScrollable();
await _revealInFallback(
tester,
scrollable,
find.textContaining('Invalid', skipOffstage: false),
);
expect(find.textContaining('Invalid').hitTestable(), findsOneWidget);
await _revealInFallback(
tester,
scrollable,
find.byKey(const Key('path-editor-search-field'), skipOffstage: false),
);
expect(
find.byKey(const Key('path-editor-search-field')).hitTestable(),
findsOneWidget,
);
await _revealInFallback(
tester,
scrollable,
find.text('Acreage North', skipOffstage: false),
);
expect(find.text('Acreage North').hitTestable(), findsOneWidget);
final button = tester.getRect(find.text('Use this path'));
final sheet = tester.getRect(find.byType(PathEditorSheet));
expect(button.bottom, lessThanOrEqualTo(sheet.bottom + 1));
},
);
testWidgets('a landscape keyboard sheet scrolls instead of overflowing', (
tester,
) async {
await _pumpSheet(
tester,
size: const Size(800, 180),
initialPath: [0x60, 0x60, 0x11, 0x22],
);
expect(tester.takeException(), isNull);
expect(
find.byKey(const Key('path-editor-scroll-fallback')),
findsOneWidget,
);
final scrollable = _fallbackScrollable();
await tester.scrollUntilVisible(
find.byKey(const Key('path-editor-hex-field')),
40,
scrollable: scrollable,
);
await tester.enterText(
find.byKey(const Key('path-editor-hex-field')),
'ZZ',
);
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
expect(find.textContaining('Invalid'), findsOneWidget);
await _revealInFallback(
tester,
scrollable,
find.byKey(const Key('path-editor-search-field'), skipOffstage: false),
);
expect(
find.byKey(const Key('path-editor-search-field')).hitTestable(),
findsOneWidget,
);
await _revealInFallback(
tester,
scrollable,
find.text('Acreage North', skipOffstage: false),
);
expect(find.text('Acreage North').hitTestable(), findsOneWidget);
final button = tester.getRect(find.text('Use this path'));
final sheet = tester.getRect(find.byType(PathEditorSheet));
expect(button.bottom, lessThanOrEqualTo(sheet.bottom + 1));
});
testWidgets('an empty landscape keyboard sheet scrolls cleanly at 180px', (
tester,
) async {
for (final size in [const Size(800, 180), const Size(640, 220)]) {
await _pumpSheet(tester, size: size);
expect(tester.takeException(), isNull);
expect(
find.byKey(const Key('path-editor-scroll-fallback')),
findsOneWidget,
);
final scrollable = _fallbackScrollable();
await _revealInFallback(
tester,
scrollable,
find.byKey(const Key('path-editor-hex-field'), skipOffstage: false),
);
expect(
find.byKey(const Key('path-editor-hex-field')).hitTestable(),
findsOneWidget,
);
await _revealInFallback(
tester,
scrollable,
find.byKey(const Key('path-editor-search-field'), skipOffstage: false),
);
expect(
find.byKey(const Key('path-editor-search-field')).hitTestable(),
findsOneWidget,
);
await _revealInFallback(
tester,
scrollable,
find.text('Acreage North', skipOffstage: false),
);
expect(find.text('Acreage North').hitTestable(), findsOneWidget);
final button = tester.getRect(find.text('Use this path'));
final sheet = tester.getRect(find.byType(PathEditorSheet));
expect(button.bottom, lessThanOrEqualTo(sheet.bottom + 1));
}
});
testWidgets('320dp width fits at 1.3x and 2.0x text scale without overflow', (
tester,
) async {
for (final scale in [1.3, 2.0]) {
for (final keyboard in [0.0, 320.0]) {
await _pumpSheet(
tester,
size: const Size(320, 640),
keyboard: keyboard,
textScale: scale,
initialPath: [0x60, 0x60, 0x11, 0x22],
);
expect(tester.takeException(), isNull);
if (find
.byKey(const Key('path-editor-scroll-fallback'))
.evaluate()
.isNotEmpty) {
await _revealInFallback(
tester,
_fallbackScrollable(),
find.byKey(const Key('path-editor-hex-field'), skipOffstage: false),
);
}
await tester.enterText(
find.byKey(const Key('path-editor-hex-field')),
'AA, BB, CC, DD, EE, FF, GG, HH, II, JJ',
);
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
if (find
.byKey(const Key('path-editor-scroll-fallback'))
.evaluate()
.isNotEmpty) {
await _revealInFallback(
tester,
_fallbackScrollable(),
find.textContaining('Invalid', skipOffstage: false),
);
}
expect(find.textContaining('Invalid').hitTestable(), findsOneWidget);
if (find.text('Use this path').evaluate().isEmpty) {
final state = tester.state<ScrollableState>(_fallbackScrollable());
state.position.jumpTo(state.position.maxScrollExtent);
await tester.pumpAndSettle();
}
final button = tester.getRect(find.text('Use this path'));
final sheet = tester.getRect(find.byType(PathEditorSheet));
expect(button.bottom, lessThanOrEqualTo(sheet.bottom + 1));
}
}
});
testWidgets('action buttons stay below the repeater list on a short sheet', (
tester,
) async {
await _pumpSheet(
tester,
size: const Size(400, 560),
initialPath: [0x60, 0x60, 0x11, 0x22],
);
expect(tester.takeException(), isNull);
final button = tester.getRect(find.text('Use this path'));
final list = tester.getRect(
find.byKey(const Key('path-editor-repeater-list')),
);
expect(button.top, greaterThanOrEqualTo(list.bottom - 1));
});
testWidgets('the title sits at the top of the sheet', (tester) async {
tester.view.physicalSize = const Size(400, 800);
tester.view.devicePixelRatio = 1;
// A phone status bar. The sheet may pad for it, and must not add another
// empty band above the handle.
tester.view.padding = const FakeViewPadding(top: 47);
tester.view.viewPadding = const FakeViewPadding(top: 47);
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
addTearDown(tester.view.resetPadding);
addTearDown(tester.view.resetViewPadding);
await tester.pumpWidget(
MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: Builder(
builder: (context) => Scaffold(
body: TextButton(
onPressed: () => PathEditorSheet.show(
context,
availableContacts: _contacts,
pathHashByteWidth: 2,
),
child: const Text('open'),
),
),
),
),
);
await tester.tap(find.text('open'));
await tester.pumpAndSettle();
final sheetTop = tester.getTopLeft(find.byType(BottomSheet)).dy;
final titleTop = tester.getTopLeft(find.text('Build Path')).dy;
// Header only: 8px padding, a 4px handle, and a 10px gap. The status-bar
// inset stays outside the sheet, and there is no extra empty band.
expect(titleTop - sheetTop, inInclusiveRange(16, 36));
});
testWidgets('tapping a repeater adds a visible hop', (tester) async {
await _pumpSheet(tester);
await tester.enterText(
find.byKey(const Key('path-editor-search-field')),
'6060',
);
await tester.pumpAndSettle();
await tester.tap(find.widgetWithText(ListTile, 'CR1'));
await tester.pumpAndSettle();
expect(find.text('1 of 64 hops'), findsOneWidget);
expect(find.byIcon(Icons.remove_circle_outline), findsOneWidget);
expect(find.text('CR1').hitTestable(), findsWidgets);
});
}
@@ -1,8 +1,41 @@
import 'package:flutter/foundation.dart';
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/theme/mesh_theme.dart';
import 'package:meshcore_open/widgets/path_map_scaffold.dart';
import 'package:meshcore_open/widgets/path_map_ui.dart';
Widget _panel(PathPlaybackController playback) => PathMapBottomPanel(
header: const Text('3 hops (2.00 km)'),
combined: false,
showInferredLegend: true,
collapsed: false,
onToggleCollapsed: () {},
playback: playback,
selected: null,
animationEnabled: true,
onToggleAnimation: () {},
followEnabled: false,
onToggleFollow: () {},
showNoSelfGpsNote: false,
pathCount: 1,
hopRowCount: 1,
summary: null,
hopList: const SizedBox.shrink(),
);
BoxDecoration _boxDecorationAbove(WidgetTester tester, Finder finder) {
return tester
.widget<DecoratedBox>(
find
.ancestor(of: finder, matching: find.byType(DecoratedBox))
.first,
)
.decoration
as BoxDecoration;
}
void main() {
for (final scenario in [
@@ -141,4 +174,111 @@ void main() {
},
);
}
for (final theme in [
(name: 'light', data: MeshTheme.light()),
(name: 'dark', data: MeshTheme.dark()),
]) {
testWidgets('map chrome follows the ${theme.name} theme', (tester) async {
final playback = PathPlaybackController(const TestVSync());
addTearDown(playback.dispose);
final scheme = theme.data.colorScheme;
await tester.pumpWidget(
MaterialApp(
theme: theme.data,
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: Scaffold(
body: Stack(
children: [
PathMapDesktopControls(
onZoomIn: () {},
onZoomOut: () {},
onReset: () {},
),
_panel(playback),
],
),
),
),
);
final panelBox = tester.widget<Container>(
find
.descendant(
of: find.byType(PathMapBottomPanel),
matching: find.byType(Container),
)
.first,
);
final panelDecoration = panelBox.decoration! as BoxDecoration;
expect(
panelDecoration.color,
scheme.surfaceContainerLow.withValues(alpha: 0.96),
);
expect(panelDecoration.border, Border.all(color: scheme.outlineVariant));
final controlsDecoration = _boxDecorationAbove(
tester,
find.widgetWithIcon(IconButton, Icons.add),
);
expect(
controlsDecoration.color,
scheme.surfaceContainerLow.withValues(alpha: 0.94),
);
final zoomIn = tester.widget<IconButton>(
find.widgetWithIcon(IconButton, Icons.add),
);
expect(zoomIn.color, scheme.onSurface);
});
}
testWidgets('top overlays clear the desktop zoom controls', (tester) async {
debugDefaultTargetPlatformOverride = TargetPlatform.linux;
addTearDown(() => debugDefaultTargetPlatformOverride = null);
tester.view.physicalSize = const Size(320, 640);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
const selectorKey = ValueKey('selector');
await tester.pumpWidget(
MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: Scaffold(
body: Stack(
children: [
PathMapDesktopControls(
onZoomIn: () {},
onZoomOut: () {},
onReset: () {},
),
PathViewModeToggle(mode: PathViewMode.single, onChanged: (_) {}),
Positioned(
left: pathMapTopOverlayInset(),
right: 16,
top: 60,
child: const SizedBox(key: selectorKey, height: 120),
),
],
),
),
),
);
expect(tester.takeException(), isNull);
final controls = tester
.getRect(find.widgetWithIcon(IconButton, Icons.add))
.expandToInclude(
tester.getRect(find.widgetWithIcon(IconButton, Icons.my_location)),
);
final toggle = tester.getRect(find.byType(SegmentedButton<PathViewMode>));
final selector = tester.getRect(find.byKey(selectorKey));
expect(controls.overlaps(toggle), isFalse);
expect(controls.overlaps(selector), isFalse);
expect(pathMapTopOverlayInset(TargetPlatform.android), 16);
debugDefaultTargetPlatformOverride = null;
});
}
+256
View File
@@ -0,0 +1,256 @@
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/models/image_codec_support.dart';
import 'package:meshcore_open/screens/app_settings_screen.dart';
import 'package:meshcore_open/services/app_settings_service.dart';
import 'package:meshcore_open/services/image_codec_service.dart';
import 'package:meshcore_open/services/image_codec_settings_store.dart';
import 'package:meshcore_open/services/network_map/network_map_upload_service.dart';
import 'package:meshcore_open/services/translation_service.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:meshcore_open/theme/mesh_theme.dart';
import 'package:meshcore_open/widgets/image_codec_models_section.dart';
import 'package:meshcore_open/widgets/settings_reveal.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
setUp(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
});
testWidgets('SettingsReveal hides children when off and reveals with tint', (
tester,
) async {
var visible = false;
late StateSetter setHostState;
await tester.pumpWidget(
MaterialApp(
theme: MeshTheme.dark(),
home: Scaffold(
body: StatefulBuilder(
builder: (context, setState) {
setHostState = setState;
return SettingsReveal(
visible: visible,
children: const [Text('Nested option')],
);
},
),
),
),
);
expect(find.text('Nested option'), findsNothing);
setHostState(() => visible = true);
await tester.pump();
await tester.pump(RevealOnEnable.duration);
await tester.pumpAndSettle();
expect(find.text('Nested option'), findsOneWidget);
final context = tester.element(find.byType(SettingsReveal));
final material = tester.widget<Material>(
find
.descendant(
of: find.byType(SettingsReveal),
matching: find.byType(Material),
)
.first,
);
expect(
material.color,
Theme.of(context).colorScheme.surfaceContainerHighest,
);
final padding = tester.widget<Padding>(
find
.descendant(
of: find.byType(SettingsReveal),
matching: find.byType(Padding),
)
.first,
);
expect(padding.padding, const EdgeInsets.only(left: 16));
setHostState(() => visible = false);
await tester.pumpAndSettle();
expect(find.text('Nested option'), findsNothing);
});
testWidgets(
'AppSettingsScreen hides Image Messages sub-options until enabled and uses SettingsReveal',
(tester) async {
final settings = AppSettingsService();
await settings.loadSettings();
await settings.setAutoRouteRotationEnabled(false);
final connector = MeshCoreConnector();
final translation = TranslationService(settings);
final codec = ImageCodecService(
settings,
settingsStore: InMemoryImageCodecSettingsStore(
const ImageCodecPreferences(),
),
);
final uploads = NetworkMapUploadService(
connector: connector,
settings: settings,
);
addTearDown(connector.dispose);
addTearDown(translation.dispose);
addTearDown(codec.dispose);
addTearDown(uploads.dispose);
tester.view.physicalSize = const Size(400, 900);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
await tester.pumpWidget(
MultiProvider(
providers: [
ChangeNotifierProvider.value(value: settings),
ChangeNotifierProvider.value(value: connector),
ChangeNotifierProvider.value(value: translation),
ChangeNotifierProvider.value(value: codec),
ChangeNotifierProvider.value(value: uploads),
],
child: MaterialApp(
theme: MeshTheme.dark(),
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: const AppSettingsScreen(),
),
),
);
await tester.pumpAndSettle();
final context = tester.element(find.byType(AppSettingsScreen));
final l10n = AppLocalizations.of(context);
final spec = imageCodecPresetModels.single;
await tester.scrollUntilVisible(
find.text(l10n.imageMessages_enableTitle),
300,
scrollable: find.byType(Scrollable).first,
);
await tester.pumpAndSettle();
expect(find.text(l10n.imageMessages_enableTitle), findsOneWidget);
expect(find.text(l10n.imageMessages_autoProcessTitle), findsNothing);
expect(find.text(l10n.imageMessages_modelSectionTitle), findsNothing);
expect(find.text(spec.label), findsNothing);
await tester.tap(find.text(l10n.imageMessages_enableTitle));
await tester.pump();
await tester.pump(RevealOnEnable.duration);
await tester.pumpAndSettle();
await tester.scrollUntilVisible(
find.text(spec.label),
200,
scrollable: find.byType(Scrollable).first,
);
await tester.pumpAndSettle();
expect(find.text(l10n.imageMessages_autoProcessTitle), findsOneWidget);
expect(find.text(l10n.imageMessages_modelSectionTitle), findsOneWidget);
expect(find.text(spec.label), findsOneWidget);
expect(
find.descendant(
of: find.byType(ImageCodecModelsSection),
matching: find.byIcon(Icons.memory_outlined),
),
findsOneWidget,
);
final imageReveal = find.ancestor(
of: find.byType(ImageCodecModelsSection),
matching: find.byType(SettingsReveal),
);
expect(imageReveal, findsOneWidget);
await tester.ensureVisible(find.text(l10n.imageMessages_enableTitle));
await tester.pumpAndSettle();
await tester.tap(find.text(l10n.imageMessages_enableTitle));
await tester.pumpAndSettle();
expect(find.text(l10n.imageMessages_autoProcessTitle), findsNothing);
expect(find.text(spec.label), findsNothing);
},
);
for (final scale in [1.3, 2.0]) {
testWidgets(
'AppSettingsScreen with Image Messages and Translation expanded fits 320dp at ${scale}x',
(tester) async {
final overflows = <String>[];
final previous = FlutterError.onError;
FlutterError.onError = (details) {
if (details.exceptionAsString().contains('overflowed')) {
overflows.add(details.exceptionAsString().split('\n').first);
return;
}
previous?.call(details);
};
addTearDown(() => FlutterError.onError = previous);
final settings = AppSettingsService();
await settings.loadSettings();
await settings.setImageMessagesEnabled(true);
await settings.setTranslationEnabled(true);
final connector = MeshCoreConnector();
final translation = TranslationService(settings);
final codec = ImageCodecService(
settings,
settingsStore: InMemoryImageCodecSettingsStore(
const ImageCodecPreferences(enabled: true),
),
);
final uploads = NetworkMapUploadService(
connector: connector,
settings: settings,
);
addTearDown(connector.dispose);
addTearDown(translation.dispose);
addTearDown(codec.dispose);
addTearDown(uploads.dispose);
tester.view.physicalSize = const Size(320, 568);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
await tester.pumpWidget(
MultiProvider(
providers: [
ChangeNotifierProvider.value(value: settings),
ChangeNotifierProvider.value(value: connector),
ChangeNotifierProvider.value(value: translation),
ChangeNotifierProvider.value(value: codec),
ChangeNotifierProvider.value(value: uploads),
],
child: MaterialApp(
theme: MeshTheme.light(),
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
builder: (context, child) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(textScaler: TextScaler.linear(scale)),
child: child!,
),
home: const AppSettingsScreen(),
),
),
);
await tester.pumpAndSettle();
expect(overflows, isEmpty);
},
);
}
}
@@ -1,16 +1,23 @@
import 'package:flutter/material.dart';
import 'package:flutter_linkify/flutter_linkify.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/helpers/link_handler.dart';
import 'package:meshcore_open/models/custom_theme.dart';
import 'package:meshcore_open/theme/mesh_theme.dart';
import 'package:meshcore_open/widgets/mesh_ui.dart';
import 'package:meshcore_open/widgets/message_bubble_frame.dart';
import 'package:meshcore_open/widgets/translated_message_content.dart';
double _renderedScaleFactor(WidgetTester tester) {
final linkify = find.byType(Linkify);
if (linkify.evaluate().isNotEmpty) {
return tester.widget<Linkify>(linkify.first).textScaleFactor;
}
List<double> _renderedScaleFactors(WidgetTester tester) {
final editables = tester
.stateList<EditableTextState>(find.byType(EditableText))
.map((s) => s.renderEditable.textScaler.scale(16) / 16)
.toList();
if (editables.isNotEmpty) return editables;
return tester
.widget<SelectableLinkify>(find.byType(SelectableLinkify).first)
.textScaleFactor;
.renderObjectList<RenderParagraph>(find.byType(RichText))
.map((p) => p.textScaler.scale(16) / 16)
.toList();
}
Future<void> _pump(WidgetTester tester, TextScaler scaler) {
@@ -20,7 +27,7 @@ Future<void> _pump(WidgetTester tester, TextScaler scaler) {
data: MediaQueryData(textScaler: scaler),
child: const Scaffold(
body: TranslatedMessageContent(
displayText: 'hello https://example.com',
displayText: 'hello https://example.com at 37.7749, -122.4194',
originalText: 'bonjour',
style: TextStyle(fontSize: 16),
),
@@ -33,23 +40,62 @@ Future<void> _pump(WidgetTester tester, TextScaler scaler) {
void main() {
testWidgets('message body follows the system text scale', (tester) async {
await _pump(tester, TextScaler.noScaling);
expect(_renderedScaleFactor(tester), 1.0);
expect(_renderedScaleFactors(tester), everyElement(1.0));
await _pump(tester, const TextScaler.linear(2));
expect(_renderedScaleFactor(tester), 2.0);
expect(_renderedScaleFactors(tester), everyElement(2.0));
});
testWidgets('original and translated text both scale', (tester) async {
await _pump(tester, const TextScaler.linear(1.5));
final factors = [
...tester
.widgetList<Linkify>(find.byType(Linkify))
.map((w) => w.textScaleFactor),
...tester
.widgetList<SelectableLinkify>(find.byType(SelectableLinkify))
.map((w) => w.textScaleFactor),
];
final factors = _renderedScaleFactors(tester);
expect(factors, hasLength(2));
expect(factors, everyElement(1.5));
});
testWidgets(
'coordinate style meets WCAG AA contrast across light, dark, and custom themes',
(tester) async {
final customForest = CustomTheme(
id: 'forest',
name: 'Forest',
background: const Color(0xFF0E1A13),
accent: const Color(0xFF4ADE80),
);
final themes = [
MeshTheme.light(),
MeshTheme.dark(),
MeshTheme.fromCustom(customForest),
];
for (final theme in themes) {
for (final isOutgoing in [false, true]) {
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Builder(
builder: (context) {
final colors = MessageBubbleColors.of(
context,
isOutgoing: isOutgoing,
);
final coordStyle = LinkHandler.defaultCoordinateStyle(
context,
TextStyle(color: colors.text, fontSize: 14),
backgroundColor: colors.background,
);
expect(coordStyle.decoration, TextDecoration.underline);
expect(
meshContrastRatio(coordStyle.color!, colors.background),
greaterThanOrEqualTo(4.5),
);
return const SizedBox.shrink();
},
),
),
);
}
}
},
);
}