Files
swiftcontrol/test/models/remembered_device_test.dart
Jonas Bark 0c91cc7465 feat(home): setup-chain model and remembered devices
The home screen is being rebuilt as the setup chain: one card per link,
each carrying the same status light and the same tick-off checklist. This
lands the parts that decide *what* the screen says, ahead of the widgets
that draw it.

chain_state.dart is pure data with no Flutter, no BLE and no `core`, and
steps carry ids rather than sentences, so "which step is done or pending"
is unit-testable without a locale or a radio. chain_builder.dart turns a
plain ChainInputs snapshot into cards; deriveBanner reads the cards back,
so the banner can never contradict what is under it.

Remembered devices fix a real gap: a controller that is switched off or
out of range disappeared from the app entirely, so riders could not see
what they owned or edit a mapping away from the bike. We now store the
advertisement a device connected with — exactly the fields
BluetoothDevice.fromScanResult reads — and rebuild it into a real device
object of the right subclass, kept out of the connect queue. Trainers are
remembered as data only, since their card needs a name, not a contour.

Tracking which ids connected this session is what separates a red "lost
connection" from an amber "out of range"; a fresh launch with the
controller in a drawer must not paint the screen red.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-11 10:38:19 +02:00

213 lines
8.1 KiB
Dart
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import 'dart:convert';
import 'dart:typed_data';
import 'package:bike_control/models/remembered_device.dart';
import 'package:bike_control/repositories/remembered_devices_repository.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:universal_ble/universal_ble.dart';
final _now = DateTime.utc(2026, 8, 11, 8, 30);
RememberedDevice remembered({
String deviceId = 'AA:BB:CC',
String? name = 'Zwift Click',
RememberedDeviceKind kind = RememberedDeviceKind.controller,
List<String> services = const ['0000fc82-0000-1000-8000-00805f9b34fb'],
List<ManufacturerData> manufacturerData = const [],
DateTime? lastConnected,
}) {
return RememberedDevice(
deviceId: deviceId,
name: name,
kind: kind,
lastConnected: lastConnected ?? _now,
services: services,
manufacturerData: manufacturerData,
);
}
void main() {
group('RememberedDevice serialization', () {
test('round-trips every field', () {
final original = remembered(
manufacturerData: [
ManufacturerData(0x0651, Uint8List.fromList([0x03, 0x11, 0xFF])),
],
);
final restored = RememberedDevice.tryFromJson(jsonDecode(jsonEncode(original.toJson())));
expect(restored, isNotNull);
expect(restored!.deviceId, original.deviceId);
expect(restored.name, original.name);
expect(restored.kind, original.kind);
expect(restored.lastConnected, original.lastConnected);
expect(restored.services, original.services);
expect(restored.manufacturerData.single.companyId, 0x0651);
expect(restored.manufacturerData.single.payload, [0x03, 0x11, 0xFF]);
});
test('rebuilds the scan result the device factory reads', () {
final scanResult = remembered(
manufacturerData: [
ManufacturerData(0x0651, Uint8List.fromList([0x09])),
],
).toScanResult();
expect(scanResult.deviceId, 'AA:BB:CC');
expect(scanResult.name, 'Zwift Click');
expect(scanResult.services, ['0000fc82-0000-1000-8000-00805f9b34fb']);
expect(scanResult.manufacturerDataList.single.companyId, 0x0651);
// We have not heard from it this session, so it must not claim a signal.
expect(scanResult.rssi, isNull);
});
test('captures a live advertisement, keeping the raw name', () {
final device = RememberedDevice.fromScanResult(
BleDevice(deviceId: 'X', name: 'Zwift Click', services: const ['abcd']),
kind: RememberedDeviceKind.trainer,
lastConnected: _now,
);
expect(device.name, 'Zwift Click');
expect(device.kind, RememberedDeviceKind.trainer);
// Sanitization happens once, in BleDevice, when it is rebuilt.
expect(device.toScanResult().name, 'Zwift Click');
});
test('drops entries with no usable id instead of throwing', () {
expect(RememberedDevice.tryFromJson({'name': 'ghost'}), isNull);
expect(RememberedDevice.tryFromJson({'deviceId': '', 'name': 'ghost'}), isNull);
});
test('survives an unknown kind and a missing timestamp', () {
final device = RememberedDevice.tryFromJson({'deviceId': 'A', 'kind': 'spaceship'});
expect(device, isNotNull);
expect(device!.kind, RememberedDeviceKind.controller);
expect(device.lastConnected, DateTime.fromMillisecondsSinceEpoch(0));
});
test('skips malformed manufacturer data without losing the device', () {
final device = RememberedDevice.tryFromJson({
'deviceId': 'A',
'manufacturerData': [
{'companyId': 'not-an-int', 'payload': 'AA=='},
{'companyId': 1, 'payload': 'AQ=='},
],
});
expect(device!.manufacturerData, hasLength(1));
expect(device.manufacturerData.single.companyId, 1);
});
test('identity is id plus kind, so a device is never listed twice', () {
expect(remembered(), equals(remembered(name: 'renamed')));
expect(remembered(), isNot(equals(remembered(kind: RememberedDeviceKind.trainer))));
});
});
group('RememberedDevicesRepository', () {
late RememberedDevicesRepository repo;
setUp(() async {
SharedPreferences.setMockInitialValues({});
repo = RememberedDevicesRepository(await SharedPreferences.getInstance());
});
test('starts empty and round-trips through storage', () async {
expect(repo.load(), isEmpty);
await repo.remember(remembered());
expect(repo.load().single.deviceId, 'AA:BB:CC');
});
test('keeps the most recently connected device first', () async {
await repo.remember(remembered(deviceId: 'first'));
await repo.remember(remembered(deviceId: 'second'));
expect(repo.load().map((d) => d.deviceId), ['second', 'first']);
});
test('re-connecting refreshes an entry instead of duplicating it', () async {
await repo.remember(remembered(deviceId: 'a'));
await repo.remember(remembered(deviceId: 'b'));
await repo.remember(remembered(deviceId: 'a', lastConnected: _now.add(const Duration(hours: 1))));
final devices = repo.load();
expect(devices, hasLength(2));
expect(devices.first.deviceId, 'a');
expect(devices.first.lastConnected, _now.add(const Duration(hours: 1)));
});
test('a controller and a trainer sharing an id are separate entries', () async {
await repo.remember(remembered(deviceId: 'same'));
await repo.remember(remembered(deviceId: 'same', kind: RememberedDeviceKind.trainer));
expect(repo.load(), hasLength(2));
});
test('caps the list, dropping the oldest', () async {
for (var i = 0; i < RememberedDevicesRepository.maxEntries + 3; i++) {
await repo.remember(remembered(deviceId: 'device-$i'));
}
final devices = repo.load();
expect(devices, hasLength(RememberedDevicesRepository.maxEntries));
expect(devices.first.deviceId, 'device-10');
expect(devices.map((d) => d.deviceId), isNot(contains('device-0')));
});
test('forget reports the index it removed, for Undo', () async {
await repo.remember(remembered(deviceId: 'c'));
await repo.remember(remembered(deviceId: 'b'));
await repo.remember(remembered(deviceId: 'a'));
expect(await repo.forget('b'), 1);
expect(repo.load().map((d) => d.deviceId), ['a', 'c']);
});
test('forgetting something that is not there is a no-op', () async {
await repo.remember(remembered(deviceId: 'a'));
expect(await repo.forget('nope'), isNull);
expect(repo.load(), hasLength(1));
});
test('restore puts the entry back where it was', () async {
final device = remembered(deviceId: 'b');
await repo.remember(remembered(deviceId: 'c'));
await repo.remember(device);
await repo.remember(remembered(deviceId: 'a'));
final index = await repo.forget('b');
await repo.restore(device, atIndex: index);
expect(repo.load().map((d) => d.deviceId), ['a', 'b', 'c']);
});
test('restore clamps when the list shrank in the meantime', () async {
final device = remembered(deviceId: 'b');
await repo.restore(device, atIndex: 7);
expect(repo.load().map((d) => d.deviceId), ['b']);
});
test('restore does not duplicate a device that came back on its own', () async {
final device = remembered(deviceId: 'b');
await repo.remember(device);
await repo.restore(device, atIndex: 0);
expect(repo.load(), hasLength(1));
});
test('a corrupt blob yields an empty list rather than throwing', () async {
SharedPreferences.setMockInitialValues({'remembered_devices': 'not json at all'});
final broken = RememberedDevicesRepository(await SharedPreferences.getInstance());
expect(broken.load(), isEmpty);
});
test('one bad entry does not discard the good ones', () async {
SharedPreferences.setMockInitialValues({
'remembered_devices': jsonEncode([
{'name': 'no id here'},
{'deviceId': 'good', 'kind': 'controller'},
]),
});
final mixed = RememberedDevicesRepository(await SharedPreferences.getInstance());
expect(mixed.load().map((d) => d.deviceId), ['good']);
});
});
}