Restructure step 3: your server, Invite, version gate, AppGraph

- One server per app run (loopback, no password); Invite attaches an
  all-interfaces listener to the same server and Stop sharing detaches
  it (guests told with 4016); members, media and Up next never reset.
  No solo mode: you're home on your own server unless in a friend's.
- Navigation: none / yours / friend; a join passes a version gate on
  /health first (clear "they/you need to update", update offer).
- Invite as a value (host, port, name, password flag, version, fp
  reserved); addresses filtered (loopback, link-local, 198.18/15,
  bridges) and ranked; Sharing chip, Copy invite, Stop sharing.
- Alone looks like a plain player (alone replaces solo).
- AppGraph builds and disposes systems; widgets use AppScope;
  SessionState deleted; a test caps the remaining singletons.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
foxyzandClaude Opus 5.5 committed 2026-10-15 22:52:52 +03:00
1 parent 629be0d9ed
commit 4d00b7455e
86 files changed
+2993 -2071

No files matched your search

+14 -8
View File
@@ -3,17 +3,23 @@ import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:sync_relay_core/core.dart';
import 'package:starsync/src/shell/app_shell.dart';
import 'package:starsync/src/state/session_state.dart';
import 'package:starsync/src/update/update_controller.dart';
import 'package:starsync/src/widgets/app_keys.dart';
import 'package:starsync/src/widgets/text_focus.dart';
import 'package:starsync/src/session/navigation.dart' show Place;
import 'test_graph.dart';
/// This file's composition root (see test_graph.dart).
final _graph = testGraph();
void main() {
final session = SessionState.instance;
final session = _graph;
final coord = session.coordinator;
tearDown(() {
session.route.value = AppRoute.home;
session.navigation.place.value = Place.none;
coord.serverState.value = null;
});
@@ -24,7 +30,7 @@ void main() {
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
var readies = 0;
await tester.pumpWidget(MaterialApp(
await tester.pumpWidget(scoped(_graph, MaterialApp(
theme: ThemeData.dark(),
shortcuts: appShortcuts,
home: AppKeys(
@@ -36,7 +42,7 @@ void main() {
videoBuilder: (context, controls) => const SizedBox(),
),
),
));
)));
coord.serverState.value = StateBroadcast(
eventId: 1,
transport: 'held',
@@ -45,7 +51,7 @@ void main() {
mediaId: 0,
members: [MemberView(id: 'a', name: 'Alex', ready: false, inSet: false, buffered: 0)],
);
session.route.value = AppRoute.session;
session.navigation.place.value = Place.friend;
await tester.pumpAndSettle();
final panel = find.byKey(const ValueKey('chat-panel'));
@@ -67,11 +73,11 @@ void main() {
});
testWidgets('Ctrl+Shift+B opens Mark a problem; Esc closes it unmarked', (tester) async {
await tester.pumpWidget(MaterialApp(
await tester.pumpWidget(scoped(_graph, MaterialApp(
theme: ThemeData.dark(),
shortcuts: appShortcuts,
home: const AppKeys(child: Scaffold(body: SizedBox())),
));
)));
final card = find.byKey(const ValueKey('mark-problem-card'));
await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);
await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft);
+10 -6
View File
@@ -7,9 +7,13 @@ import 'package:starsync/src/controls/model/controls_model.dart';
import 'package:starsync/src/controls/model/controls_prefs.dart';
import 'package:starsync/src/controls/session_controls.dart';
import 'package:starsync/src/playback/media_marks.dart';
import 'package:starsync/src/state/session_state.dart';
import 'package:starsync/src/state/settings.dart';
import 'test_graph.dart';
/// This file's composition root (see test_graph.dart).
final _graph = testGraph();
// The controls model and its layout spec: which controls the bar has, in
// which order, what goes to ⚙; and both skins drawing the same order.
@@ -64,7 +68,7 @@ void main() {
final all = menuActions(const ControlsSnapshot(hasChapters: true, hasDuration: true, hasLink: true), none);
expect(all.first, ControlAction.chapters);
expect(all, containsAllInOrder([ControlAction.skipForward, ControlAction.copyLink]));
expect(menuActions(const ControlsSnapshot(solo: true), none), isNot(contains(ControlAction.markAllReady)),
expect(menuActions(const ControlsSnapshot(alone: true), none), isNot(contains(ControlAction.markAllReady)),
reason: 'nobody to mark ready');
});
@@ -74,7 +78,7 @@ void main() {
expect(controlIcon(BarControl.playPause, const ControlsSnapshot(play: PlayState.waiting)), Icons.check_rounded);
expect(controlTooltip(BarControl.playPause, const ControlsSnapshot(play: PlayState.playing)),
'Pause for everyone (Space)');
expect(controlTooltip(BarControl.playPause, const ControlsSnapshot(solo: true)), 'Play (Space)');
expect(controlTooltip(BarControl.playPause, const ControlsSnapshot(alone: true)), 'Play (Space)');
});
test('episode buttons: the label and the keys', () {
@@ -98,7 +102,7 @@ void main() {
group('both skins draw the model', () {
final s = AppSettings.instance;
final coord = SessionState.instance.coordinator;
final coord = _graph.coordinator;
tearDown(() {
s.controlsSkin.value = ControlsSkin.standard;
@@ -131,13 +135,13 @@ void main() {
shown.dispose();
hold.dispose();
});
await tester.pumpWidget(MaterialApp(
await tester.pumpWidget(scoped(_graph, MaterialApp(
theme: ThemeData.dark(),
home: Scaffold(
backgroundColor: Colors.black,
body: SessionControls(model: model, shown: shown, hold: hold, onDoubleClick: () {}),
),
));
)));
await tester.pump();
return model;
}
+18 -9
View File
@@ -18,9 +18,13 @@ import 'package:starsync/src/session/identity.dart';
import 'package:starsync/src/session/notifier.dart';
import 'package:starsync/src/session/session_coordinator.dart';
import 'package:starsync/src/sfx/sfx.dart';
import 'package:starsync/src/state/session_state.dart';
import 'package:starsync/src/sync/sync_client.dart';
import 'test_graph.dart';
/// This file's composition root (see test_graph.dart).
final _graph = testGraph();
final _tmp = Platform.environment['WT_TEST_TMP'] ?? Directory.systemTemp.path;
Future<void> _poll(
@@ -376,22 +380,27 @@ void main() {
}
});
test('cancelling a host setup releases the port', timeout: const Timeout(Duration(minutes: 1)), () async {
test('stop sharing releases the port; stopping your server frees its own', timeout: const Timeout(Duration(minutes: 1)),
() async {
Hive.init('$_tmp/hive_coord_test');
final probe = await ServerSocket.bind(InternetAddress.anyIPv4, 0);
final port = probe.port;
await probe.close();
final session = SessionState.instance;
final yours = _graph.yourServer;
_graph.forms.form
..hostPort = '$port'
..hostSecret = '';
try {
final pending = session.host(ConnectParams(host: '', port: port, secret: '', name: 'host'), ConnectForm());
await session.cancelPending();
await expectLater(pending, throwsA(isA<ConnectCancelled>()));
expect(session.route.peek(), isNot(AppRoute.session));
final own = await yours.start(name: 'me');
expect((await yours.invite()).port, port);
await yours.stopSharing();
final rebind = await ServerSocket.bind(InternetAddress.anyIPv4, port);
await rebind.close();
await yours.stop();
final again = await ServerSocket.bind(InternetAddress.loopbackIPv4, own);
await again.close();
} finally {
await session.coordinator.leave(silent: true);
await session.stopServer();
await yours.stop();
}
});
+7 -2
View File
@@ -7,6 +7,11 @@ import 'package:sync_relay_core/core.dart';
import 'package:starsync/src/session/delivery.dart';
import 'package:starsync/src/shell/delivery_line.dart';
import 'test_graph.dart';
/// This file's composition root (see test_graph.dart).
final _graph = testGraph();
MemberView _m(String id, String name, {double buffered = 30, bool host = false, int rate = 0}) =>
MemberView(id: id, name: name, ready: true, inSet: true, buffered: buffered, host: host, rate: rate);
@@ -134,7 +139,7 @@ void main() {
final r = _state(
_relayed(const MediaRelay(source: 'm1', live: true, rate: 1200000, need: 2300000)), [foxyz, bob, ann]);
final d = deliveryOf(r, selfId: 'm2')!;
await tester.pumpWidget(MaterialApp(
await tester.pumpWidget(scoped(_graph, MaterialApp(
theme: ThemeData.dark(),
home: Scaffold(
body: Center(
@@ -147,7 +152,7 @@ void main() {
),
),
),
));
)));
await tester.pumpAndSettle();
expect(find.text("Foxyz's upload is slower than the video"), findsOneWidget);
expect(find.byKey(const ValueKey('headroom-bar')), findsOneWidget);
+11 -6
View File
@@ -13,6 +13,11 @@ import 'package:starsync/src/files/thumbnails.dart';
import 'package:starsync/src/files/ui/file_tiles.dart';
import 'package:starsync/src/files/ui/files_page.dart';
import 'test_graph.dart';
/// This file's composition root (see test_graph.dart).
final _graph = testGraph();
// The Files page over a real (tiny) folder tree: the scan runs in-line
// instead of in an isolate and thumbnails come from a fake loader, so
// nothing here decodes video.
@@ -46,7 +51,7 @@ Future<void> frames(WidgetTester tester, [int n = 10]) async {
Future<void> pumpPage(
WidgetTester tester, {
Size size = const Size(1280, 800),
bool solo = false,
bool alone = false,
bool relayed = false,
Future<String?> Function(String path)? onPlay,
ThumbnailLoader? thumbnails,
@@ -55,10 +60,10 @@ Future<void> pumpPage(
tester.view.physicalSize = size;
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
await tester.pumpWidget(MaterialApp(
await tester.pumpWidget(scoped(_graph, MaterialApp(
home: Scaffold(
body: FilesPage(
solo: solo,
alone: alone,
relayed: relayed,
onPlay: onPlay ?? (_) async => null,
thumbnails: thumbnails ?? fakeThumb,
@@ -67,7 +72,7 @@ Future<void> pumpPage(
pickFolder: pickFolder,
),
),
));
)));
await frames(tester);
}
@@ -242,7 +247,7 @@ void main() {
tester.view.physicalSize = const Size(1280, 800);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
await tester.pumpWidget(MaterialApp(
await tester.pumpWidget(scoped(_graph, MaterialApp(
home: Scaffold(
body: FilesPage(
relayed: false,
@@ -253,7 +258,7 @@ void main() {
store: store,
),
),
));
)));
await frames(tester);
await openFolder(tester, 'anime');
await openSeries(tester);
+111 -46
View File
@@ -1,7 +1,5 @@
// restructure: rewrite in step 3 (Your server): hosted recents and the host
// card; the rest stays.
import 'dart:convert';
import 'dart:io' show Platform;
import 'dart:io' show Platform, SocketException;
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
@@ -12,13 +10,22 @@ import 'package:starsync/src/screens/home/health_probe.dart';
import 'package:starsync/src/screens/home/media_picker.dart';
import 'package:starsync/src/screens/home/update_indicator.dart';
import 'package:starsync/src/shell/app_shell.dart';
import 'package:starsync/src/shell/library_link.dart' show soloPlayHint;
import 'package:starsync/src/state/session_state.dart';
import 'package:starsync/src/shell/library_link.dart' show alonePlayHint;
import 'package:starsync/src/state/connect_prefs.dart';
import 'package:starsync/src/state/settings.dart';
import 'package:starsync/src/update/update_controller.dart';
import 'package:starsync/src/session/connection.dart' show ConnClosed;
import 'package:starsync/src/session/navigation.dart' show JoinFailed, Place;
import 'package:starsync/src/session/session_coordinator.dart' show ConnectParams;
import 'test_graph.dart';
/// This file's composition root (see test_graph.dart).
final _graph = testGraph();
RecentServer join(String host, String port, [String secret = '']) =>
RecentServer(hosted: false, host: host, port: port, secret: secret);
RecentServer(host: host, port: port, secret: secret);
void main() {
group('recent servers', () {
@@ -35,21 +42,12 @@ void main() {
expect(list.where((r) => r.host == '10.0.0.4').length, 1);
});
test('hosted entries are one per port, separate from joins', () {
var list = <RecentServer>[];
list = pushRecent(list, const RecentServer(hosted: true, host: '', port: '8080'));
list = pushRecent(list, join('127.0.0.1', '8080'));
list = pushRecent(list, const RecentServer(hosted: true, host: '', port: '8080', secret: 'x'));
expect(list.length, 2);
expect(list.first.secret, 'x');
});
test('round-trips and tolerates junk', () {
final list = [join('a.example', '9000', 's'), const RecentServer(hosted: true, host: '', port: '8080')];
test('round-trips and tolerates junk; hosted entries of older versions are dropped', () {
final list = [join('a.example', '9000', 's'), join('b.example', '8080')];
final back = decodeRecents(encodeRecents(list));
expect(back.map((r) => r.key), list.map((r) => r.key));
expect(back.first.secret, 's');
expect(back.last.hosted, isTrue);
expect(decodeRecents('[{"hosted":true,"host":"","port":"8080"},{"host":"h","port":"1"}]').single.host, 'h');
expect(decodeRecents('not json'), isEmpty);
expect(decodeRecents(42), isEmpty);
expect(decodeRecents('[{"host":1},{"host":"h","port":"1"}]').single.host, 'h');
@@ -79,8 +77,15 @@ void main() {
});
test('health parse: online, junk and protocol mismatch', () {
final ok = ServerHealth.parse(jsonEncode(
{'ok': true, 'name': 'Den', 'proto': RelayConstants.protoVersion, 'viewers': 2, 'version': '1.3.0'}));
final ok = ServerHealth.parse(jsonEncode({
'ok': true,
'name': 'Den',
'proto': RelayConstants.protoMax,
'protoMin': RelayConstants.protoMin,
'protoMax': RelayConstants.protoMax,
'viewers': 2,
'version': '1.3.0'
}));
expect(ok.online, isTrue);
expect(ok.name, 'Den');
expect(ok.version, '1.3.0');
@@ -93,6 +98,73 @@ void main() {
expect(healthUri('::1', '8080').toString(), 'http://[::1]:8080/health');
});
group('version gate (/health)', () {
String body({required int min, required int max, String version = '', String name = ''}) =>
jsonEncode({'ok': true, 'name': name, 'proto': max, 'protoMin': min, 'protoMax': max, 'version': version});
const own = RelayConstants.protoMin;
test('older, newer, compatible', () {
final older = ServerHealth.parse(body(min: own - 2, max: own - 1, version: '1.2.1', name: "Bob's server"));
expect(older.fit, VersionFit.theyUpdate);
expect(versionGateText(older), "Bob's server runs Starsync 1.2.1 — they need to update");
final newer = ServerHealth.parse(body(min: RelayConstants.protoMax + 1, max: RelayConstants.protoMax + 2, version: '2.0.0'));
expect(newer.fit, VersionFit.youUpdate);
expect(versionGateText(newer), 'The server runs Starsync 2.0.0 — you need to update');
final overlap = ServerHealth.parse(body(min: own - 1, max: RelayConstants.protoMax + 3));
expect(overlap.fit, VersionFit.ok, reason: 'ranges that meet are fine');
// A proto 15 server says only `proto`.
final old = ServerHealth.parse('{"ok":true,"proto":15,"name":"server"}');
expect(old.fit, VersionFit.theyUpdate);
expect(versionGateText(old), 'The server runs an older Starsync — they need to update');
expect(ServerHealth.parse('{"ok":true}').fit, isNull, reason: 'unknown: let the hello decide');
});
test('a join stops at the gate, still at home, before connecting', () async {
final graph = testGraph(healthGet: (uri) async => body(min: own - 2, max: own - 1, version: '1.2.1'));
await expectLater(
graph.navigation.join(const ConnectParams(host: 'old.example', port: 8080, secret: '', name: 'Me')),
throwsA(isA<VersionGateRefused>()
.having((e) => e.youUpdate, 'youUpdate', isFalse)
.having((e) => e.message, 'message', contains('they need to update'))));
expect(graph.connection.state.peek(), isA<ConnClosed>(), reason: 'never dialled');
final newer = testGraph(
healthGet: (uri) async => body(min: RelayConstants.protoMax + 1, max: RelayConstants.protoMax + 1));
await expectLater(newer.navigation.join(const ConnectParams(host: 'new.example', port: 8080, secret: '', name: 'Me')),
throwsA(isA<VersionGateRefused>().having((e) => e.youUpdate, 'youUpdate', isTrue)));
final offline = testGraph(healthGet: (uri) async => throw const SocketException('refused'));
await expectLater(offline.navigation.join(const ConnectParams(host: 'gone.example', port: 8080, secret: '', name: 'Me')),
throwsA(isA<JoinFailed>()));
});
testWidgets('the Join card says who has to update and offers the updater when it is you', (tester) async {
final graph = testGraph(
healthGet: (uri) async => body(min: RelayConstants.protoMax + 1, max: RelayConstants.protoMax + 1, version: '2.0.0'));
graph.forms.form.name = 'Me';
tester.view.physicalSize = const Size(1280, 800);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
await tester.pumpWidget(scoped(
graph,
MaterialApp(
theme: ThemeData.dark(),
home: AppShell(
updates: UpdateController(currentVersion: '0.0.0-dev'),
autoUpdateCheck: false,
windowControls: false,
healthGet: graph.navigation.healthGet,
),
)));
await tester.pump();
await tester.tap(find.byKey(const ValueKey('strip-join')));
await tester.pumpAndSettle();
await tester.enterText(find.byKey(const ValueKey('join-address')), 'new.example');
await tester.tap(find.widgetWithText(FilledButton, 'Join').last);
await tester.pumpAndSettle();
expect(find.textContaining('you need to update'), findsOneWidget);
expect(find.byKey(const ValueKey('join-update')), findsOneWidget);
});
});
test('pasting sorts links and paths into the right source', () {
final c = MediaPickerController();
expect(c.source, MediaKind.jellyfin);
@@ -118,7 +190,7 @@ void main() {
tester.view.physicalSize = size;
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
await tester.pumpWidget(MaterialApp(
await tester.pumpWidget(scoped(_graph, MaterialApp(
theme: ThemeData.dark(),
home: AppShell(
updates: UpdateController(currentVersion: '0.0.0-dev'),
@@ -126,7 +198,7 @@ void main() {
windowControls: false,
healthGet: health ?? fakeHealth(const {}),
),
));
)));
await tester.pump();
}
@@ -136,8 +208,8 @@ void main() {
}
setUp(() {
SessionState.instance.recents.value = const [];
SessionState.instance.route.value = AppRoute.home;
_graph.forms.recents.value = const [];
_graph.navigation.place.value = Place.none;
});
testWidgets('tabs and settings pages switch the body', (tester) async {
@@ -178,7 +250,7 @@ void main() {
});
testWidgets('Enter in the join card submits; errors show under it', (tester) async {
SessionState.instance.lastForm.name = '';
_graph.forms.form.name = '';
await pumpShell(tester, const Size(1280, 720));
await openCard(tester, 'strip-join');
await tester.enterText(find.byKey(const ValueKey('join-address')), 'friend.example');
@@ -201,11 +273,10 @@ void main() {
});
testWidgets('recent rows show live status from /health', (tester) async {
SessionState.instance.recents.value = [
_graph.forms.recents.value = [
join('alpha.example', '8080'),
join('beta.example', '9000', 'pw'),
join('gamma.example', '7000'),
const RecentServer(hosted: true, host: '', port: '8181'),
];
await pumpShell(tester, const Size(1280, 900),
health: fakeHealth({
@@ -226,8 +297,6 @@ void main() {
expect(inRow('beta.example:9000', find.text('○ offline')), findsOneWidget);
expect(inRow('beta.example:9000', find.text('beta.example')), findsOneWidget);
expect(inRow('gamma.example:7000', find.text('needs update')), findsOneWidget);
// Hosted entries live on the Host card, not in the join list.
expect(find.byKey(const ValueKey('recent-host:8181')), findsNothing);
// x forgets.
await tester.tap(inRow('beta.example:9000', find.byTooltip('Forget')));
await tester.pump();
@@ -242,13 +311,15 @@ void main() {
expect(find.byKey(const ValueKey('join-row')), findsOneWidget);
});
testWidgets('library offline: welcome band, sources that need nothing, Jellyfin optional', (tester) async {
testWidgets('library at home: welcome band, sources that need nothing, Jellyfin optional', (tester) async {
await pumpShell(tester, const Size(1280, 900));
// The three ways in, Join first; none needs Jellyfin.
expect(find.byKey(const ValueKey('welcome-band')), findsOneWidget);
expect(find.text('Watch together, in sync'), findsOneWidget);
final join = tester.getTopLeft(find.byKey(const ValueKey('way-join')));
expect(join.dx, lessThan(tester.getTopLeft(find.byKey(const ValueKey('way-solo'))).dx));
expect(join.dx, lessThan(tester.getTopLeft(find.byKey(const ValueKey('way-invite'))).dx));
expect(find.text('Watch on your own'), findsOneWidget);
expect(find.text('Host'), findsNothing, reason: 'no Host: your server is always there');
// No linked server: Files and Link first, Jellyfin as an optional card.
expect(find.text('Pick something to watch'), findsOneWidget);
expect(find.text('Add a Jellyfin server'), findsNothing);
@@ -262,25 +333,19 @@ void main() {
await tester.pumpAndSettle();
expect(find.text('Watch from a link'), findsOneWidget);
// Alone: Play, no relay modes.
expect(find.text(soloPlayHint), findsOneWidget);
expect(find.text(alonePlayHint), findsOneWidget);
expect(find.text('How the others get it'), findsNothing);
expect(tester.takeException(), isNull);
});
testWidgets('host without a name errors in the host card', (tester) async {
SessionState.instance.lastForm.name = '';
SessionState.instance.recents.value = [const RecentServer(hosted: true, host: '', port: '8181', secret: 's')];
testWidgets('pasting an invite into the address fills the port', (tester) async {
await pumpShell(tester, const Size(1280, 900));
await openCard(tester, 'strip-host');
expect(find.text('No password — anyone can join'), findsOneWidget);
expect(find.text('You pick what to watch afterwards, in the library.'), findsOneWidget);
// A hosted port refills the fields.
await tester.tap(find.byKey(const ValueKey('recent-host:8181')));
await openCard(tester, 'strip-join');
await tester.enterText(find.byKey(const ValueKey('join-address')),
'Join me on Starsync: 192.168.1.20:9123 (ask me for the password) · Starsync 1.3.0');
await tester.pump();
expect(find.text('No password — anyone can join'), findsNothing);
await tester.tap(find.widgetWithText(FilledButton, 'Host').last);
await tester.pumpAndSettle();
expect(find.textContaining('display name', findRichText: true), findsOneWidget);
expect(tester.widget<TextField>(find.byKey(const ValueKey('join-address'))).controller!.text, '192.168.1.20');
expect(tester.widget<TextField>(find.byKey(const ValueKey('join-port'))).controller!.text, '9123');
});
testWidgets('narrow window: strip, cards and library fit', (tester) async {
@@ -310,8 +375,8 @@ void main() {
executablePath: '/nowhere/watch_together',
restart: (_, _) async {});
c.status.value = s;
await tester.pumpWidget(MaterialApp(
home: Scaffold(body: Column(children: [UpdateBar(controller: c)]))));
await tester.pumpWidget(scoped(_graph, MaterialApp(
home: Scaffold(body: Column(children: [UpdateBar(controller: c)])))));
return c;
}
+13 -8
View File
@@ -12,9 +12,14 @@ import 'package:starsync/src/jellyfin/browse_scope.dart';
import 'package:starsync/src/jellyfin/picker_source.dart';
import 'package:starsync/src/state/settings.dart';
import 'test_graph.dart';
import 'jellyfin_accounts_test.dart'
show FakeJellyfin, arifuretaId, fixtureServerId, linkedAccounts, season2Id;
/// This file's composition root (see test_graph.dart).
final _graph = testGraph();
Future<void> setSize(WidgetTester tester, Size size) async {
tester.view.physicalSize = size;
tester.view.devicePixelRatio = 1;
@@ -55,7 +60,7 @@ Future<(Picks, JellyfinAccounts, FakeJellyfin, BrowseController)> pumpBrowser(
final controller = BrowseController(accounts, now: () => fixtureNow);
addTearDown(controller.dispose);
final picks = Picks();
await tester.pumpWidget(app(StatefulBuilder(
await tester.pumpWidget(scoped(_graph, app(StatefulBuilder(
builder: (context, setState) => JellyfinBrowser(
accounts: accounts,
controller: controller,
@@ -63,7 +68,7 @@ Future<(Picks, JellyfinAccounts, FakeJellyfin, BrowseController)> pumpBrowser(
onSelect: (s) => setState(() => picks.selected.add(s)),
onPutUp: picks.putUp.add,
),
)));
))));
await settle(tester);
return (picks, accounts, fake, controller);
}
@@ -154,8 +159,8 @@ void main() {
addTearDown(controller.dispose);
AppSettings.instance.hideReReleases.value = true;
addTearDown(() => AppSettings.instance.hideReReleases.value = true);
await tester.pumpWidget(app(JellyfinBrowser(
accounts: accounts, controller: controller, onSelect: (_) {}, onPutUp: (_) {})));
await tester.pumpWidget(scoped(_graph, app(JellyfinBrowser(
accounts: accounts, controller: controller, onSelect: (_) {}, onPutUp: (_) {}))));
await settle(tester);
expect(find.text('Fresh Show'), findsWidgets);
expect(find.text('S1E1'), findsWidgets);
@@ -298,9 +303,9 @@ void main() {
final accounts = JellyfinAccounts(
store: MemoryJellyfinStore(), httpFactory: () => fake, deviceName: 'Test');
await accounts.ensureLoaded(validate: false);
await tester.pumpWidget(app(SingleChildScrollView(
await tester.pumpWidget(scoped(_graph, app(SingleChildScrollView(
child: JellyfinAccountsPanel(
accounts: accounts, pollInterval: const Duration(milliseconds: 100)))));
accounts: accounts, pollInterval: const Duration(milliseconds: 100))))));
await tester.tap(find.byKey(const ValueKey('jf-add-server')));
await tester.pump();
await tester.enterText(find.byKey(const ValueKey('jf-address')), 'example.invalid');
@@ -351,8 +356,8 @@ void main() {
await setSize(tester, const Size(1200, 900));
final accounts = JellyfinAccounts(store: MemoryJellyfinStore(), httpFactory: () => FakeJellyfin());
await accounts.ensureLoaded(validate: false);
await tester.pumpWidget(app(JellyfinPickerSource(
accounts: accounts, onSelect: (_) {}, onPutUp: (_) {}, onOpenIntegrations: () {})));
await tester.pumpWidget(scoped(_graph, app(JellyfinPickerSource(
accounts: accounts, onSelect: (_) {}, onPutUp: (_) {}, onOpenIntegrations: () {}))));
await tester.pump();
expect(find.byKey(const ValueKey('jf-sign-in')), findsOneWidget);
expect(find.text('Open Integrations'), findsOneWidget);
+13 -8
View File
@@ -21,6 +21,11 @@ import 'package:starsync/src/shell/library_tab.dart' show putUpJellyfinMedia;
import 'jellyfin_accounts_test.dart';
import 'jellyfin_browser_test.dart' show app, setSize, settle;
import 'test_graph.dart';
/// This file's composition root (see test_graph.dart).
final _graph = testGraph();
const episodeId = 'b18826be994070a79f9b52bc0f66f052'; // Black Summoner S1E6
const nextEpisodeId = '74c50bdbf83e8fef231dd7710058e197'; // S1E7
const seriesId = 'e9aec9c14a1fcab775111844112b4cf7';
@@ -485,7 +490,7 @@ void main() {
SeriesRoute(const JellyfinItem(id: arifuretaId, name: 'Arifureta', type: 'Series'),
seasonId: season2Id),
]));
await tester.pumpWidget(app(JellyfinBrowser(accounts: accounts, onSelect: (_) {}, onPutUp: (_) {})));
await tester.pumpWidget(scoped(_graph, app(JellyfinBrowser(accounts: accounts, onSelect: (_) {}, onPutUp: (_) {}))));
await settle(tester);
final s2 = tester.widget<ChoiceChip>(find.byKey(const ValueKey('season-$season2Id')));
expect(s2.selected, isTrue);
@@ -506,18 +511,18 @@ void main() {
testWidgets('end card: Next prompt, countdown with Cancel', (tester) async {
var play = 0, cancel = 0;
await tester.pumpWidget(app(EndOfEpisodeCard(
next: next, countdown: null, onPlayNow: () => play++, onCancel: () => cancel++)));
await tester.pumpWidget(scoped(_graph, app(EndOfEpisodeCard(
next: next, countdown: null, onPlayNow: () => play++, onCancel: () => cancel++))));
expect(find.text('Next: S1E7 Battle with the Heroes'), findsOneWidget);
expect(find.byKey(const ValueKey('auto-advance-cancel')), findsNothing);
await tester.tap(find.byKey(const ValueKey('play-next')));
expect(play, 1);
await tester.pumpWidget(app(EndOfEpisodeCard(
await tester.pumpWidget(scoped(_graph, app(EndOfEpisodeCard(
next: next,
countdown: AutoAdvance(mediaId: 3, secondsLeft: 7, next: next, swapper: false),
onPlayNow: () => play++,
onCancel: () => cancel++)));
onCancel: () => cancel++))));
expect(find.text('Next episode in 7 s'), findsOneWidget);
await tester.tap(find.byKey(const ValueKey('auto-advance-cancel')));
expect(cancel, 1);
@@ -525,7 +530,7 @@ void main() {
testWidgets('next-episode pill: faint at rest, lit on hover, click puts it up', (tester) async {
var pressed = 0;
await tester.pumpWidget(app(Align(child: NextEpisodePill(episode: next, onPressed: () => pressed++))));
await tester.pumpWidget(scoped(_graph, app(Align(child: NextEpisodePill(episode: next, onPressed: () => pressed++)))));
double opacity() => tester.widget<AnimatedOpacity>(find.descendant(
of: find.byType(NextEpisodePill), matching: find.byType(AnimatedOpacity))).opacity;
expect(opacity(), lessThan(0.5));
@@ -541,10 +546,10 @@ void main() {
testWidgets('blocked card offers to link an account', (tester) async {
var link = 0;
await tester.pumpWidget(app(JellyfinBlockedCard(
await tester.pumpWidget(scoped(_graph, app(JellyfinBlockedCard(
blocked: const BlockedPlay(serverId: fixtureServerId, serverName: 'Example Server'),
onLinkAccount: () => link++,
onRetry: () {})));
onRetry: () {}))));
expect(find.text('No Jellyfin account here for Example Server, and nobody is passing it on'),
findsOneWidget);
await tester.tap(find.byKey(const ValueKey('link-jellyfin-account')));
+1 -1
View File
@@ -226,7 +226,7 @@ void main() {
final refused = await previewLink('https://cdn.example/b.mp4',
probe: (url) async => LinkProbe.page(Uri.parse(url), ytDlpError: 'odd', status: 403));
expect((refused!.title, refused.problem), ('b.mp4', 'Not allowed (403)'));
expect(await previewLink('not a link'), isNull);
expect(await previewLink('not a link', probe: (url) async => throw StateError('no probe')), isNull);
});
test('ago text', () {
+21 -18
View File
@@ -1,5 +1,3 @@
// restructure: rewrite in step 3 (Your server): the "solo" and "hosting"
// tests (D9: no solo mode); the rest stays.
import 'dart:convert';
import 'package:flutter/material.dart';
@@ -16,6 +14,11 @@ import 'jellyfin_accounts_test.dart'
show FakeJellyfin, arifuretaId, fixtureServerId, jellyfinFixture, linkedAccounts, season2Id;
import 'jellyfin_browser_test.dart' show fixtureNow, settle;
import 'test_graph.dart';
/// This file's composition root (see test_graph.dart).
final _graph = testGraph();
const bsSeries = 'e9aec9c14a1fcab775111844112b4cf7';
const bsEpisode = 'b18826be994070a79f9b52bc0f66f052';
const bsSeason = 'fb0b77cfda15445f9319ed9d753dba23';
@@ -50,13 +53,13 @@ FakeJellyfin libraryFake() {
}
class FilesStub extends StatelessWidget {
final bool solo, relayed;
final bool alone, relayed;
final Future<String?> Function(String path) onPlay;
const FilesStub({super.key, required this.solo, required this.relayed, required this.onPlay});
const FilesStub({super.key, required this.alone, required this.relayed, required this.onPlay});
@override
Widget build(BuildContext context) => Column(children: [
Text('files solo=$solo relayed=$relayed'),
Text('files alone=$alone relayed=$relayed'),
TextButton(
key: const ValueKey('stub-play'),
onPressed: () => onPlay('/v/a.mkv'),
@@ -77,7 +80,7 @@ class Harness {
Future<Harness> pumpLibrary(
WidgetTester tester,
Size size, {
bool solo = false,
bool alone = false,
bool isHost = false,
MediaKind source = MediaKind.jellyfin,
Harness? reuse,
@@ -97,7 +100,7 @@ Future<Harness> pumpLibrary(
addTearDown(c.dispose);
h = Harness(c, accounts, fake);
}
await tester.pumpWidget(MaterialApp(
await tester.pumpWidget(scoped(_graph, MaterialApp(
theme: ThemeData.dark(),
home: Scaffold(
body: LibraryTab(
@@ -105,7 +108,7 @@ Future<Harness> pumpLibrary(
key: UniqueKey(),
controller: h.controller,
accounts: h.accounts,
solo: solo,
alone: alone,
isHost: isHost,
jellyfinStart: start,
recentLinks: h.recents,
@@ -115,15 +118,15 @@ Future<Harness> pumpLibrary(
: url.contains('bilibili')
? LinkProbe.page(Uri.parse(url), ytDlpError: 'HTTP Error 412: Precondition Failed')
: LinkProbe.page(Uri.parse(url), info: const YtDlpInfo(title: 'A video', uploader: 'Chan')),
filesBuilder: (context, {required solo, required relayed, required onPlay, nowPlayingPath}) =>
FilesStub(solo: solo, relayed: relayed, onPlay: onPlay),
filesBuilder: (context, {required alone, required relayed, required onPlay, nowPlayingPath}) =>
FilesStub(alone: alone, relayed: relayed, onPlay: onPlay),
onPutUp: (m) async {
h.put.add(m);
return null;
},
),
),
));
)));
await settle(tester, 10);
return h;
}
@@ -156,7 +159,7 @@ void main() {
await tester.tap(find.text('Files'));
await settle(tester, 10);
expect(find.text('files solo=false relayed=true'), findsOneWidget);
expect(find.text('files alone=false relayed=true'), findsOneWidget);
await tester.tap(find.byKey(const ValueKey('stub-play')));
await settle(tester);
expect(h.put, [const FileMedia('/v/a.mkv')]);
@@ -251,8 +254,8 @@ void main() {
expect(tester.takeException(), isNull);
});
testWidgets('solo: buttons say Play and put up; a link goes direct, no relay modes', (tester) async {
final h = await pumpLibrary(tester, const Size(1600, 1000), solo: true);
testWidgets('nobody else in the server (D9): buttons say Play and put up; a link goes direct, no relay modes', (tester) async {
final h = await pumpLibrary(tester, const Size(1600, 1000), alone: true);
await tester.tap(arifuretaCard());
await settle(tester, 10);
final go = find.byKey(const ValueKey('details-put-up'));
@@ -267,7 +270,7 @@ void main() {
await tester.enterText(find.byKey(const ValueKey('link-field')), 'https://cdn.example/a.mkv');
await settle(tester, 10);
expect(find.text('How the others get it'), findsNothing);
expect(find.text(soloPlayHint), findsOneWidget);
expect(find.text(alonePlayHint), findsOneWidget);
await tester.tap(find.byKey(const ValueKey('link-put-up')));
await settle(tester, 10);
expect(h.put.last, const LinkMedia('https://cdn.example/a.mkv'));
@@ -324,9 +327,9 @@ void main() {
expect(tester.takeException(), isNull);
});
testWidgets('hosting: files stream from here; now-playing file passes through', (tester) async {
testWidgets('your server: files stream from here; now-playing file passes through', (tester) async {
await pumpLibrary(tester, const Size(1400, 900), source: MediaKind.file, isHost: true);
expect(find.text('files solo=false relayed=false'), findsOneWidget);
expect(find.text('files alone=false relayed=false'), findsOneWidget);
});
testWidgets('the last pick comes back selected; "Change video" opens on its series', (tester) async {
@@ -344,7 +347,7 @@ void main() {
expect(c.selected!.itemId, bsEpisode);
expect(c.source, MediaKind.jellyfin);
final h = Harness(c, accounts, FakeJellyfin());
await pumpLibrary(tester, const Size(1600, 1000), reuse: h, solo: true);
await pumpLibrary(tester, const Size(1600, 1000), reuse: h, alone: true);
expect(find.byKey(const ValueKey('jf-details')), findsOneWidget);
expect(find.text('Black Summoner'), findsWidgets);
+31 -26
View File
@@ -12,6 +12,11 @@ import 'package:starsync/src/state/settings.dart';
import 'package:starsync/src/update/update_controller.dart';
import 'package:starsync/src/widgets/app_menu.dart';
import 'test_graph.dart';
/// This file's composition root (see test_graph.dart).
final _graph = testGraph();
// The Minimal skin's pieces and the shared controls frame (never the
// session screen or a media_kit `Video`).
@@ -81,8 +86,8 @@ void main() {
group('timeline', () {
testWidgets('played part, elapsed left, remaining right, cache label', (tester) async {
await tester.pumpWidget(host(MinimalTimeline(
position: m(6), duration: m(24), buffered: m(6, 30), chapters: chapters, onSeek: (_) {})));
await tester.pumpWidget(scoped(_graph, host(MinimalTimeline(
position: m(6), duration: m(24), buffered: m(6, 30), chapters: chapters, onSeek: (_) {}))));
final bar = tester.getRect(find.byKey(const ValueKey('minimal-timeline')));
expect(bar.width, 800);
expect(bar.height, MinimalTimelineSpec.size);
@@ -98,16 +103,16 @@ void main() {
});
testWidgets('the total instead of the time left', (tester) async {
await tester.pumpWidget(host(MinimalTimeline(
position: m(6), duration: m(24), remaining: false, onSeek: (_) {})));
await tester.pumpWidget(scoped(_graph, host(MinimalTimeline(
position: m(6), duration: m(24), remaining: false, onSeek: (_) {}))));
expect(painter(tester).right, '24:00');
});
testWidgets('a press on the right-hand time switches it, no seek', (tester) async {
final seeks = <Duration>[];
var toggled = 0;
await tester.pumpWidget(host(MinimalTimeline(
position: m(6), duration: m(24), onSeek: seeks.add, onToggleTime: () => toggled++)));
await tester.pumpWidget(scoped(_graph, host(MinimalTimeline(
position: m(6), duration: m(24), onSeek: seeks.add, onToggleTime: () => toggled++))));
final bar = tester.getRect(find.byKey(const ValueKey('minimal-timeline')));
await tester.tapAt(Offset(bar.right - 20, bar.center.dy));
expect(toggled, 1);
@@ -115,12 +120,12 @@ void main() {
});
testWidgets('a mark at each chapter start', (tester) async {
await tester.pumpWidget(host(MinimalTimeline(position: m(1), duration: m(24), chapters: chapters, onSeek: (_) {})));
await tester.pumpWidget(scoped(_graph, host(MinimalTimeline(position: m(1), duration: m(24), chapters: chapters, onSeek: (_) {}))));
expect(painter(tester).chapters, [for (final c in chapters) c.start.inSeconds / m(24).inSeconds]);
});
testWidgets('hover: chapter title over the time, above the band', (tester) async {
await tester.pumpWidget(host(MinimalTimeline(position: m(1), duration: m(24), chapters: chapters, onSeek: (_) {})));
await tester.pumpWidget(scoped(_graph, host(MinimalTimeline(position: m(1), duration: m(24), chapters: chapters, onSeek: (_) {}))));
final bar = tester.getRect(find.byKey(const ValueKey('minimal-timeline')));
final mouse = await mouseAt(tester, Offset.zero);
// 1:51 of 24:00: inside "Opening".
@@ -143,7 +148,7 @@ void main() {
testWidgets('a press on a hovered chapter mark jumps to its chapter', (tester) async {
final seeks = <Duration>[];
await tester.pumpWidget(host(MinimalTimeline(position: m(1), duration: m(24), chapters: chapters, onSeek: seeks.add)));
await tester.pumpWidget(scoped(_graph, host(MinimalTimeline(position: m(1), duration: m(24), chapters: chapters, onSeek: seeks.add))));
final bar = tester.getRect(find.byKey(const ValueKey('minimal-timeline')));
final at = Offset(bar.left + bar.width * 2 / 24 + 3, bar.top + 2);
final mouse = await mouseAt(tester, at);
@@ -159,8 +164,8 @@ void main() {
testWidgets('hidden controls: the progress line, no text, no input', (tester) async {
final seeks = <Duration>[];
await tester.pumpWidget(host(MinimalTimeline(
position: m(12), duration: m(24), buffered: m(14), chapters: chapters, expanded: false, onSeek: seeks.add)));
await tester.pumpWidget(scoped(_graph, host(MinimalTimeline(
position: m(12), duration: m(24), buffered: m(14), chapters: chapters, expanded: false, onSeek: seeks.add))));
final bar = tester.getRect(find.byKey(const ValueKey('minimal-timeline')));
expect(bar.height, MinimalTimeline.collapsedHeight);
final p = painter(tester);
@@ -177,7 +182,7 @@ void main() {
testWidgets('press seeks, every drag move seeks, release holds the target', (tester) async {
final seeks = <Duration>[];
await tester.pumpWidget(host(MinimalTimeline(position: m(1), duration: m(24), chapters: chapters, onSeek: seeks.add)));
await tester.pumpWidget(scoped(_graph, host(MinimalTimeline(position: m(1), duration: m(24), chapters: chapters, onSeek: seeks.add))));
final bar = tester.getRect(find.byKey(const ValueKey('minimal-timeline')));
final g0 = await tester.startGesture(Offset(bar.left + bar.width / 4, bar.center.dy), kind: PointerDeviceKind.mouse);
expect(seeks, [m(6)], reason: 'the press seeks');
@@ -220,7 +225,7 @@ void main() {
bool up(WidgetTester tester) => tester.state<ControlsFrameState>(find.byType(ControlsFrame)).visible;
testWidgets('hide after the delay, mouse brings them back', (tester) async {
await tester.pumpWidget(frame());
await tester.pumpWidget(scoped(_graph, frame()));
expect(up(tester), isTrue);
await tester.pump(const Duration(seconds: 4));
await tester.pumpAndSettle();
@@ -237,7 +242,7 @@ void main() {
});
testWidgets('a long drag on the timeline keeps the controls up', (tester) async {
await tester.pumpWidget(frame());
await tester.pumpWidget(scoped(_graph, frame()));
final bar = tester.getRect(find.byKey(const ValueKey('minimal-timeline')));
final g = await tester.startGesture(Offset(bar.left + 100, bar.center.dy), kind: PointerDeviceKind.mouse);
for (var i = 0; i < 10; i++) {
@@ -254,7 +259,7 @@ void main() {
});
testWidgets('an open app menu keeps the controls up', (tester) async {
await tester.pumpWidget(frame(
await tester.pumpWidget(scoped(_graph, frame(
child: Builder(
builder: (context) => TextButton(
key: const ValueKey('open'),
@@ -262,7 +267,7 @@ void main() {
child: const Text('open'),
),
),
));
)));
await tester.tap(find.byKey(const ValueKey('open')));
await tester.pumpAndSettle();
expect(find.text('One'), findsOneWidget);
@@ -277,13 +282,13 @@ void main() {
testWidgets('double-click on the picture, not on the bars', (tester) async {
var doubles = 0;
await tester.pumpWidget(MaterialApp(
await tester.pumpWidget(scoped(_graph, MaterialApp(
home: ControlsFrame(
onDoubleClick: () => doubles++,
barBottom: 100,
builder: (context, visible) => const SizedBox.expand(),
),
));
)));
Future<void> twice(Offset at) async {
await tester.tapAt(at, kind: PointerDeviceKind.mouse);
await tester.pump(const Duration(milliseconds: 100));
@@ -300,10 +305,10 @@ void main() {
group('buttons', () {
testWidgets('count badge in the accent; tooltip on the app glass', (tester) async {
await tester.pumpWidget(host(const Row(children: [
await tester.pumpWidget(scoped(_graph, host(const Row(children: [
MinimalButton(key: ValueKey('subs'), icon: Icons.subtitles_outlined, tooltip: 'Subtitles', badge: 2, onPressed: null),
MinimalButton(key: ValueKey('plain'), icon: Icons.menu, tooltip: 'Menu', onPressed: null),
])));
]))));
expect(
find.descendant(of: find.byKey(const ValueKey('subs')), matching: find.byKey(const ValueKey('minimal-badge'))),
findsOneWidget);
@@ -320,7 +325,7 @@ void main() {
final got = <double>[];
var volume = 80.0;
var before = 80.0;
await tester.pumpWidget(host(StatefulBuilder(
await tester.pumpWidget(scoped(_graph, host(StatefulBuilder(
builder: (context, setState) => Row(children: [
VolumeControl(
volume: volume,
@@ -337,7 +342,7 @@ void main() {
MinimalButton(key: const ValueKey('speaker'), icon: icon, tooltip: tip, onPressed: onPressed),
),
]),
)));
))));
await tester.tap(find.byKey(const ValueKey('speaker')));
await tester.pump();
await tester.tap(find.byKey(const ValueKey('speaker')));
@@ -361,7 +366,7 @@ void main() {
final steps = <int>[];
final list = ScrollController();
addTearDown(list.dispose);
await tester.pumpWidget(MaterialApp(
await tester.pumpWidget(scoped(_graph, MaterialApp(
home: VolumeWheel(
onStep: steps.add,
child: Stack(children: [
@@ -375,7 +380,7 @@ void main() {
),
]),
),
));
)));
Future<void> wheel(Offset at, Offset delta) =>
tester.sendEventToBinding(PointerScrollEvent(kind: PointerDeviceKind.mouse, position: at, scrollDelta: delta));
await wheel(const Offset(100, 400), const Offset(0, -60));
@@ -407,7 +412,7 @@ void main() {
tester.view.physicalSize = const Size(1280, 2400);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
await tester.pumpWidget(MaterialApp(
await tester.pumpWidget(scoped(_graph, MaterialApp(
theme: ThemeData.dark(),
home: Scaffold(
body: SettingsTab(
@@ -416,7 +421,7 @@ void main() {
updates: UpdateController(currentVersion: '0.0.0-dev'),
),
),
));
)));
final design = find.byKey(const ValueKey('player-design'));
expect(find.text('Player design'), findsOneWidget);
expect(tester.widget<AppSelect<ControlsSkin>>(design).value, ControlsSkin.standard);
+16 -11
View File
@@ -8,6 +8,11 @@ import 'package:starsync/src/jellyfin/track_prefs.dart';
import 'package:starsync/src/playback/media_marks.dart';
import 'package:starsync/src/screens/session/player_controls.dart';
import 'test_graph.dart';
/// This file's composition root (see test_graph.dart).
final _graph = testGraph();
// The control-bar pieces alone (never the session screen or a `Video`):
// the Standard seek bar, the skip pill and the shared track / chapter
// lists.
@@ -38,8 +43,8 @@ Widget host(Widget child, {double width = 960}) => MaterialApp(
void main() {
group('seek bar', () {
testWidgets('a mark at each chapter start but the first, placed by time', (tester) async {
await tester.pumpWidget(host(ChapterSeekBar(
position: m(1), duration: m(24), chapters: chapters, onSeek: (_) {})));
await tester.pumpWidget(scoped(_graph, host(ChapterSeekBar(
position: m(1), duration: m(24), chapters: chapters, onSeek: (_) {}))));
expect(find.byKey(const ValueKey('chapter-mark-0')), findsNothing, reason: 'starts at 0');
final bar = tester.getRect(find.byKey(const ValueKey('seek-bar')));
for (final c in chapters.skip(1)) {
@@ -51,16 +56,16 @@ void main() {
});
testWidgets('no marks without a duration or chapters', (tester) async {
await tester.pumpWidget(host(ChapterSeekBar(
position: Duration.zero, duration: Duration.zero, chapters: chapters, onSeek: (_) {})));
await tester.pumpWidget(scoped(_graph, host(ChapterSeekBar(
position: Duration.zero, duration: Duration.zero, chapters: chapters, onSeek: (_) {}))));
expect(find.byKey(const ValueKey('chapter-mark-1')), findsNothing);
await tester.pumpWidget(host(ChapterSeekBar(position: Duration.zero, duration: m(24), onSeek: (_) {})));
await tester.pumpWidget(scoped(_graph, host(ChapterSeekBar(position: Duration.zero, duration: m(24), onSeek: (_) {}))));
expect(find.byKey(const ValueKey('chapter-mark-1')), findsNothing);
});
testWidgets('hover shows the chapter title above the time', (tester) async {
await tester.pumpWidget(host(ChapterSeekBar(
position: m(1), duration: m(24), chapters: chapters, onSeek: (_) {})));
await tester.pumpWidget(scoped(_graph, host(ChapterSeekBar(
position: m(1), duration: m(24), chapters: chapters, onSeek: (_) {}))));
final bar = tester.getRect(find.byKey(const ValueKey('seek-bar')));
final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
await mouse.addPointer(location: Offset.zero);
@@ -84,7 +89,7 @@ void main() {
});
testWidgets('no chapters: the hover shows only the time', (tester) async {
await tester.pumpWidget(host(ChapterSeekBar(position: m(1), duration: m(24), onSeek: (_) {})));
await tester.pumpWidget(scoped(_graph, host(ChapterSeekBar(position: m(1), duration: m(24), onSeek: (_) {}))));
final bar = tester.getRect(find.byKey(const ValueKey('seek-bar')));
final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
await mouse.addPointer(location: Offset.zero);
@@ -97,8 +102,8 @@ void main() {
testWidgets('drag seeks on every move and on release', (tester) async {
final seeks = <Duration>[];
await tester.pumpWidget(host(ChapterSeekBar(
position: m(1), duration: m(24), chapters: chapters, onSeek: seeks.add)));
await tester.pumpWidget(scoped(_graph, host(ChapterSeekBar(
position: m(1), duration: m(24), chapters: chapters, onSeek: seeks.add))));
final bar = tester.getRect(find.byKey(const ValueKey('seek-bar')));
final g = await tester.startGesture(Offset(bar.left + bar.width / 4, bar.center.dy),
kind: PointerDeviceKind.mouse);
@@ -120,7 +125,7 @@ void main() {
(SkipKind.ending, 'Skip ED'),
(SkipKind.fixed, 'Skip 1:30'),
]) {
await tester.pumpWidget(host(Align(child: SkipPill(offer: SkipOffer(kind, m(2)), onPressed: () => pressed++))));
await tester.pumpWidget(scoped(_graph, host(Align(child: SkipPill(offer: SkipOffer(kind, m(2)), onPressed: () => pressed++)))));
expect(find.text(label), findsOneWidget);
}
double opacity() => tester.widget<AnimatedOpacity>(
+79 -42
View File
@@ -1,5 +1,3 @@
// restructure: rewrite in step 3 (Your server): invite addresses (P24) and
// the hosting invite; the settings cards stay.
import 'dart:io';
import 'package:flutter/material.dart';
@@ -15,10 +13,18 @@ import 'package:starsync/src/shaders/shader_presets.dart';
import 'package:starsync/src/shell/avatar.dart';
import 'package:starsync/src/shell/party_strip.dart';
import 'package:starsync/src/shell/settings_tab.dart';
import 'package:starsync/src/state/session_state.dart';
import 'package:starsync/src/state/settings.dart';
import 'package:starsync/src/update/update_controller.dart';
import 'package:starsync/src/session/invite.dart';
import 'package:starsync/src/session/navigation.dart' show Place;
import 'package:starsync/src/state/connect_prefs.dart' show RecentServer;
import 'test_graph.dart';
/// This file's composition root (see test_graph.dart).
final _graph = testGraph();
// The player settings card (both skins, never a media_kit `Video`), the
// Settings pages, the host flag in the party UI and invite addresses.
@@ -39,7 +45,7 @@ Future<void> pick(WidgetTester tester, String key, String item) async {
void main() {
final s = AppSettings.instance;
final coord = SessionState.instance.coordinator;
final coord = _graph.coordinator;
tearDown(() {
s.controlsSkin.value = ControlsSkin.standard;
@@ -54,8 +60,8 @@ void main() {
coord.playback.tracks.value = const [];
coord.serverState.value = null;
coord.hostFile = null;
SessionState.instance.route.value = AppRoute.home;
SessionState.instance.recents.value = const [];
_graph.navigation.place.value = Place.none;
_graph.forms.recents.value = const [];
});
Widget opener() => Builder(
@@ -73,7 +79,7 @@ void main() {
MpvTrack(id: 1, type: JellyfinStreamType.audio, language: 'jpn', codec: 'eac3', channels: 2, selected: true),
MpvTrack(id: 1, type: JellyfinStreamType.subtitle, language: 'eng', codec: 'ass', title: 'Full'),
];
await tester.pumpWidget(app(Align(alignment: Alignment.bottomRight, child: opener())));
await tester.pumpWidget(scoped(_graph, app(Align(alignment: Alignment.bottomRight, child: opener()))));
await tester.tap(find.byKey(const ValueKey('open-settings')));
await tester.pumpAndSettle();
final card = find.byKey(const ValueKey('player-settings-card'));
@@ -113,10 +119,10 @@ void main() {
testWidgets('keeps the controls up while open', (tester) async {
bigWindow(tester);
await tester.pumpWidget(app(ControlsFrame(
await tester.pumpWidget(scoped(_graph, app(ControlsFrame(
hideAfter: const Duration(seconds: 1),
builder: (context, visible) => Align(alignment: Alignment.bottomRight, child: opener()),
)));
))));
final controls = tester.state<ControlsFrameState>(find.byType(ControlsFrame));
await tester.tap(find.byKey(const ValueKey('open-settings')));
await tester.pumpAndSettle();
@@ -135,12 +141,12 @@ void main() {
Future<void> pumpSettings(WidgetTester tester, SettingsSection section,
{Future<AnimeFlowMe> Function()? me, Size size = const Size(1280, 1400)}) async {
bigWindow(tester, size);
await tester.pumpWidget(app(SettingsTab(
await tester.pumpWidget(scoped(_graph, app(SettingsTab(
section: section,
onSection: (_) {},
updates: UpdateController(currentVersion: '0.0.0-dev'),
animeFlowMe: me ?? () async => throw const AnimeFlowException(401, AnimeFlowErrorCode.missingToken, 'x'),
)));
))));
await tester.pumpAndSettle();
}
@@ -196,26 +202,27 @@ void main() {
expect(s.hiddenControls.value, isEmpty);
});
testWidgets('Party & network: host defaults and recent servers with remove', (tester) async {
SessionState.instance.recents.value = const [
RecentServer(hosted: false, host: 'vps.example', port: '8080', secret: 'pw'),
RecentServer(hosted: true, host: '127.0.0.1', port: '9000'),
testWidgets('Party & network: your server\'s port and password, recent servers with remove', (tester) async {
_graph.forms.recents.value = const [
RecentServer(host: 'vps.example', port: '8080', secret: 'pw'),
RecentServer(host: 'friend.example', port: '9000'),
];
await pumpSettings(tester, SettingsSection.network);
expect(find.text('Default port'), findsOneWidget);
expect(find.text('Your server'), findsOneWidget);
expect(find.text('Port'), findsOneWidget);
expect(find.text('vps.example:8080'), findsOneWidget);
expect(find.text('Hosted on port 9000'), findsOneWidget);
expect(find.text('friend.example:9000'), findsOneWidget);
await tester.enterText(find.byKey(const ValueKey('host-port')), '70000');
await tester.pump();
expect(find.text('A number from 1 to 65535'), findsOneWidget);
await tester.enterText(find.byKey(const ValueKey('host-port')), '9100');
await tester.pump();
expect(SessionState.instance.lastForm.hostPort, '9100');
expect(_graph.forms.form.hostPort, '9100');
await tester.tap(find.descendant(
of: find.byKey(const ValueKey('recent-vps.example:8080')), matching: find.byTooltip('Remove')));
await tester.pumpAndSettle();
expect(find.text('vps.example:8080'), findsNothing);
SessionState.instance.lastForm.hostPort = '8080';
_graph.forms.form.hostPort = '8080';
});
testWidgets('Integrations: AnimeFlow says who you are connected as, or why not', (tester) async {
@@ -224,7 +231,7 @@ void main() {
userId: 'u1', name: 'foxyz', scopes: {AnimeFlowScope.view, AnimeFlowScope.request}));
expect(find.text('connected as foxyz · can view, request'), findsOneWidget);
// A fresh tree: the card keeps its first answer otherwise.
await tester.pumpWidget(const SizedBox());
await tester.pumpWidget(scoped(_graph, const SizedBox()));
await pumpSettings(tester, SettingsSection.integrations,
me: () async => throw const AnimeFlowException(
401, AnimeFlowErrorCode.missingToken, 'No linked Jellyfin account for AnimeFlow'));
@@ -239,23 +246,43 @@ void main() {
final chip = tester.widget<ChoiceChip>(find.byKey(const ValueKey('settings-network')));
expect(chip.selected, isTrue);
expect((chip.avatar! as Icon).icon, Icons.hub_outlined);
expect(find.text('Default port'), findsOneWidget);
expect(find.text('Port'), findsOneWidget);
});
});
group('party', () {
test('invite addresses: LAN IPv4 with the port, private first, no loopback', () {
test('invite addresses: home network first; no proxy fake-IP, link-local, loopback or container bridge', () {
({String name, InternetAddress address}) at(String name, String ip) => (name: name, address: InternetAddress(ip));
final list = inviteAddresses([
InternetAddress('127.0.0.1'),
InternetAddress('100.64.1.2'),
InternetAddress('192.168.1.20'),
InternetAddress('169.254.3.4'),
InternetAddress('::1'),
InternetAddress('10.0.0.5'),
InternetAddress('192.168.1.20'),
], '8080');
expect(list, ['192.168.1.20:8080', '10.0.0.5:8080', '100.64.1.2:8080']);
expect(inviteAddresses(const [], '8080'), isEmpty);
at('lo', '127.0.0.1'),
at('Meta', '198.18.0.1'), // a TUN proxy's fake-IP range (198.18.0.0/15)
at('utun', '198.19.255.2'),
at('tailscale0', '100.64.1.2'),
at('docker0', '172.17.0.1'),
at('br-3f2a', '172.18.0.1'),
at('virbr0', '192.168.122.1'),
at('eth1', '10.0.0.5'),
at('wlan0', '169.254.3.4'),
at('eth0', '192.168.1.20'),
at('eth0', '192.168.1.20'),
at('eth0', '::1'),
at('wan', '203.0.113.7'),
]);
expect(list, ['192.168.1.20', '10.0.0.5', '100.64.1.2', '203.0.113.7']);
expect(inviteAddresses(const []), isEmpty);
expect(isFakeIp(InternetAddress('198.19.1.1').rawAddress), isTrue);
expect(isFakeIp(InternetAddress('198.20.1.1').rawAddress), isFalse);
});
test('an invite: the address, whether to ask for a password, the version; pasted back', () {
const invite = Invite(host: '192.168.1.20', port: 8080, password: true, version: '1.3.0');
expect(invite.address, '192.168.1.20:8080');
expect(invite.text, 'Join me on Starsync: 192.168.1.20:8080 (ask me for the password) · Starsync 1.3.0');
expect(invite.fp, isNull, reason: 'reserved for pinned certificates');
expect(addressIn(invite.text), (host: '192.168.1.20', port: '8080'));
expect(addressIn('vps.example.com:9000'), (host: 'vps.example.com', port: '9000'));
expect(addressIn('[fe80::1]:8080'), (host: 'fe80::1', port: '8080'));
expect(addressIn('just a host'), isNull);
});
void online(List<MemberView> members) {
@@ -267,7 +294,7 @@ void main() {
mediaId: 0,
members: members,
);
SessionState.instance.route.value = AppRoute.session;
_graph.navigation.place.value = Place.friend;
}
testWidgets('the state\'s host flag crowns that member for everyone', (tester) async {
@@ -279,7 +306,7 @@ void main() {
expect(avatars['Hana']!.host, isTrue);
expect(avatars['Bob']!.host, isFalse);
bigWindow(tester);
await tester.pumpWidget(app(const Center(child: MembersCard())));
await tester.pumpWidget(scoped(_graph, app(const Center(child: MembersCard()))));
await tester.pumpAndSettle();
expect(find.descendant(of: find.byKey(const ValueKey('member-m1')), matching: find.text('host')),
findsOneWidget);
@@ -291,18 +318,28 @@ void main() {
expect(find.text('Sit out'), findsOneWidget);
});
testWidgets('hosting: Copy invite address lists this machine\'s addresses', (tester) async {
testWidgets('your server, not shared: only you, Invite; shared: the invite and Stop sharing', (tester) async {
online(const [MemberView(id: 'm1', name: 'Me', ready: false, inSet: false, buffered: 0)]);
coord.hostFile = (_) async => null;
SessionState.instance.lastForm.hostPort = '8080';
_graph.navigation.place.value = Place.yours;
final yours = _graph.yourServer;
yours.port.value = 40000; // as if it runs
addTearDown(() {
yours.port.value = null;
yours.shared.value = null;
});
bigWindow(tester);
await tester.pumpWidget(app(Center(
child: MembersCard(lanAddresses: (port) async => ['192.168.1.20:$port', '10.0.0.5:$port']),
)));
await tester.pumpWidget(scoped(_graph, app(const Center(child: MembersCard()))));
await tester.pumpAndSettle();
expect(find.text('Your server'), findsOneWidget);
expect(find.textContaining('Only you can reach it'), findsOneWidget);
expect(find.widgetWithText(TextButton, 'Invite'), findsOneWidget);
expect(find.byKey(const ValueKey('stop-sharing')), findsNothing);
yours.shared.value = const Invite(host: '192.168.1.20', port: 8080, version: '1.3.0');
await tester.pumpAndSettle();
expect(find.text('Copy invite address'), findsOneWidget);
expect(find.text('192.168.1.20:8080'), findsOneWidget);
expect(find.text('10.0.0.5:8080'), findsOneWidget);
expect(find.text('Copy invite'), findsOneWidget);
expect(find.byKey(const ValueKey('stop-sharing')), findsOneWidget);
expect(find.textContaining('port 8080 forwarded'), findsOneWidget);
expect(find.textContaining('VPS'), findsOneWidget);
});
+12 -8
View File
@@ -14,7 +14,11 @@ import 'package:starsync/src/session/now_playing.dart';
import 'package:starsync/src/shell/now_playing_title.dart';
import 'package:starsync/src/shell/session_player.dart';
import 'package:starsync/src/shell/start_banner.dart';
import 'package:starsync/src/state/session_state.dart';
import 'test_graph.dart';
/// This file's composition root (see test_graph.dart).
final _graph = testGraph();
// The one computed status (each input → text and level), the player's
// title block, start card and status pill (never a media_kit `Video`).
@@ -78,7 +82,7 @@ StatusLine? line(StateBroadcast? state, {MemberView? self, ConnState conn = cons
st(state, self: self, conn: conn, playerError: playerError).line;
void main() {
final coord = SessionState.instance.coordinator;
final coord = _graph.coordinator;
tearDown(() {
debugArtBytes = null;
@@ -265,7 +269,7 @@ void main() {
const now = NowPlaying(title: 'Frieren', episode: 'S1 E4 · The Land Where Souls Rest', posterHash: 'p');
testWidgets('title, episode and a placeholder cover without art', (tester) async {
await tester.pumpWidget(host(const NowPlayingBlock(now: now)));
await tester.pumpWidget(scoped(_graph, host(const NowPlayingBlock(now: now))));
expect(find.text('Frieren'), findsOneWidget);
expect(find.text('S1 E4 · The Land Where Souls Rest'), findsOneWidget);
expect(find.byIcon(Icons.movie_outlined), findsOneWidget);
@@ -276,16 +280,16 @@ void main() {
testWidgets('the cover image once its bytes are here', (tester) async {
debugArtBytes = (hash) => hash == 'p' ? png : null;
await tester.pumpWidget(host(const NowPlayingBlock(now: now)));
await tester.pumpWidget(scoped(_graph, host(const NowPlayingBlock(now: now))));
final image = tester.widget<Image>(find.byType(Image));
expect((image.image as MemoryImage).bytes, png);
expect(image.gaplessPlayback, isTrue);
});
testWidgets('no cover, no episode: just the title; long titles ellipsize', (tester) async {
await tester.pumpWidget(host(
await tester.pumpWidget(scoped(_graph, host(
NowPlayingBlock(now: NowPlaying(title: 'A very long title ' * 10), cover: false, compact: true),
width: 200));
width: 200)));
expect(find.byType(ArtCover), findsNothing);
expect(find.byKey(const ValueKey('now-playing-episode')), findsNothing);
expect(tester.takeException(), isNull);
@@ -293,7 +297,7 @@ void main() {
});
testWidgets('start banner: up before playback, fades on play, never back for that media', (tester) async {
await tester.pumpWidget(const MaterialApp(home: SizedBox(width: 1280, height: 720, child: StartBanner())));
await tester.pumpWidget(scoped(_graph, const MaterialApp(home: SizedBox(width: 1280, height: 720, child: StartBanner()))));
final card = find.byKey(const ValueKey('start-card-title'));
expect(card, findsNothing);
coord.serverState.value = held([mv('a', 'Alex')]);
@@ -332,7 +336,7 @@ void main() {
tester.view.physicalSize = size;
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
await tester.pumpWidget(MaterialApp(theme: ThemeData.dark(), home: Scaffold(body: child)));
await tester.pumpWidget(scoped(_graph, MaterialApp(theme: ThemeData.dark(), home: Scaffold(body: child))));
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
}
+7 -2
View File
@@ -6,12 +6,17 @@ import 'package:starsync/src/session/session_coordinator.dart';
import 'package:starsync/src/shell/library_link.dart' show LinkPreview;
import 'package:starsync/src/widgets/text_focus.dart';
import 'test_graph.dart';
/// This file's composition root (see test_graph.dart).
final _graph = testGraph();
void main() {
testWidgets('Up next popover: holds the keys, Ctrl+V adds with a preview row, + Add link opens a field',
(tester) async {
final coord = SessionCoordinator();
var clip = (files: const <String>[], text: 'look https://example.com/v' as String?);
await tester.pumpWidget(MaterialApp(
await tester.pumpWidget(scoped(_graph, MaterialApp(
theme: ThemeData.dark(),
home: Scaffold(
body: Center(
@@ -23,7 +28,7 @@ void main() {
),
),
),
));
)));
await tester.pump();
expect(textInputFocused(), isTrue, reason: 'the player keys rest while it is open');
expect(find.byKey(const ValueKey('queue-add-field')), findsNothing);
+12 -10
View File
@@ -1,5 +1,3 @@
// restructure: rewrite in step 3 (Your server): "solo: the button says
// Play"; the rest stays.
import 'dart:convert';
import 'dart:io';
@@ -16,6 +14,11 @@ import 'package:starsync/src/screens/home/picked_media.dart';
import 'schedule_fake_server.dart';
import 'test_graph.dart';
/// This file's composition root (see test_graph.dart).
final _graph = testGraph();
/// Serves [snap] without any network; [animeFlow] is a real client (over
/// the fake server) for the page's actions.
class FakeRepo extends ScheduleRepository {
@@ -234,7 +237,7 @@ void main() {
WidgetTester tester, {
Size size = const Size(2560, 1080),
ScheduleSnapshot Function()? snap,
bool solo = false,
bool alone = false,
JellyfinAccounts? accounts,
}) async {
toasts.clear();
@@ -243,12 +246,12 @@ void main() {
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
final repo = FakeRepo(snap ?? snapshot, animeFlow: flow);
await tester.pumpWidget(
await tester.pumpWidget(scoped(_graph,
MaterialApp(
theme: ThemeData.dark(),
home: Scaffold(
body: SchedulePage(
solo: solo,
alone: alone,
repository: repo,
accounts: accounts,
onToast: toasts.add,
@@ -258,8 +261,7 @@ void main() {
},
),
),
),
);
)));
await tester.pump();
await tester.pump();
await io(tester, rounds: 4);
@@ -269,7 +271,7 @@ void main() {
/// Unmounts the page and lets the HttpClient's idle keep-alive timers
/// (made in the fake clock) run out.
Future<void> done(WidgetTester tester) async {
await tester.pumpWidget(const SizedBox());
await tester.pumpWidget(scoped(_graph, const SizedBox()));
await tester.pump(const Duration(seconds: 20));
}
@@ -482,8 +484,8 @@ void main() {
await done(tester);
});
testWidgets('solo: the button says Play and works', (tester) async {
await pumpPage(tester, solo: true);
testWidgets('nobody else in the server (D9): the button says Play and works', (tester) async {
await pumpPage(tester, alone: true);
expect(find.text('Put it up'), findsNothing);
final b = widgetOf<ButtonStyleButton>(tester, action(111, 3));
expect(b.onPressed, isNotNull);
+172 -143
View File
@@ -1,5 +1,5 @@
// restructure: rewrite in step 3 (Your server): one hub with listeners
// attached, nothing restarts, no solo mode.
// Your server: one hub for the app's life, a network listener attached
// by Invite and detached by Stop sharing, nothing restarts.
import 'dart:async';
import 'dart:convert';
import 'dart:io';
@@ -9,11 +9,15 @@ import 'package:flutter_test/flutter_test.dart';
import 'package:hive_ce/hive.dart';
import 'package:media_kit/media_kit.dart';
import 'package:sync_relay_core/core.dart';
import 'package:starsync/src/jellyfin/accounts.dart';
import 'package:starsync/src/screens/home/picked_media.dart';
import 'package:starsync/src/session/session_coordinator.dart';
import 'package:starsync/src/state/server_isolate.dart';
import 'package:starsync/src/state/session_state.dart';
import 'package:sync_relay_server/server.dart' show SyncServer;
import 'package:starsync/src/session/navigation.dart' show Place;
import 'test_graph.dart';
Future<void> _poll(
FutureOr<bool> Function() cond,
@@ -33,11 +37,14 @@ class _Raw {
final WebSocket ws;
final msgs = <Map<String, Object?>>[];
_Raw(this.ws) {
ws.listen((m) => msgs.add(Map<String, Object?>.from(jsonDecode('$m') as Map)));
ws.listen((m) => msgs.add(Map<String, Object?>.from(jsonDecode('$m') as Map)),
onDone: () => done.complete(ws.closeCode), onError: (_) {});
}
static Future<_Raw> join(int port, String name, {String secret = ''}) async {
final r = _Raw(await WebSocket.connect('ws://127.0.0.1:$port/sync'));
final done = Completer<int?>();
static Future<_Raw> join(int port, String name, {String secret = '', String host = '127.0.0.1'}) async {
final r = _Raw(await WebSocket.connect('ws://$host:$port/sync'));
r.ws.add(jsonEncode(HelloMessage(secret: secret, user: HelloUser(name: name)).toJson()));
await r.next('welcome');
return r;
@@ -66,6 +73,23 @@ Future<int> _freePort() async {
return port;
}
/// This machine's first LAN address (the invite's); loopback when none.
Future<String> _lanHost() async {
for (final i in await NetworkInterface.list(type: InternetAddressType.IPv4)) {
for (final a in i.addresses) {
if (!a.isLoopback) return a.address;
}
}
return '127.0.0.1';
}
List<Map> _members(Map<String, Object?> state) => (state['members'] as List).cast<Map>();
void _hive(String name) {
MediaKit.ensureInitialized();
Hive.init('${Platform.environment['WT_TEST_TMP'] ?? Directory.systemTemp.path}/$name');
}
void main() {
test('server isolate: logs, raw join, crash reported, stop frees port',
timeout: const Timeout(Duration(minutes: 1)), () async {
@@ -108,153 +132,158 @@ void main() {
}
});
test('host path: isolate server, host sat out and nudging, crash leaves the session',
test('your server: Invite attaches the network listener and Stop sharing detaches it; '
'members and Up next never reset; a crash brings a new one home',
timeout: const Timeout(Duration(minutes: 2)), () async {
MediaKit.ensureInitialized();
Hive.init(
'${Platform.environment['WT_TEST_TMP'] ?? Directory.systemTemp.path}/hive_isolate_test');
final session = SessionState.instance;
final port = await _freePort();
_Raw? friend;
try {
await session.host(
ConnectParams(host: '', port: port, secret: 'pw', name: 'host'),
ConnectForm());
expect(session.route.peek(), AppRoute.session);
await session.coordinator.playback.player.setVolume(0);
friend = await _Raw.join(port, 'friend', secret: 'pw');
final state = await friend.next('state',
where: (m) => (m['members'] as List).any((x) => (x as Map)['name'] == 'host'));
final hostId = ((state['members'] as List)
.cast<Map>()
.firstWhere((m) => m['name'] == 'host'))['id'];
// Anyone may sit the host out; its player unloads, the server serves on.
friend.ws.add(jsonEncode(PresenceIntent(target: '$hostId', state: Presence.away).toJson()));
await _poll(() => session.coordinator.selfAway.peek(), 'host sat out');
// The host nudges the friend: only the friend hears it.
final friendId = ((state['members'] as List)
.cast<Map>()
.firstWhere((m) => m['name'] == 'friend'))['id'];
session.coordinator.nudgeMember('$friendId');
expect((await friend.next('nudge'))['name'], 'host');
session.hostedServer!.isolate.kill(priority: Isolate.immediate);
await _poll(() => session.route.peek() == AppRoute.home, 'leave after crash');
expect(session.serverCrash.peek(), startsWith('server crashed'));
expect(session.hostedServer, isNull);
// The killed isolate's socket stays bound in-process; hosting again on
// the same port must still work.
session.serverCrash.value = null;
await session.host(
ConnectParams(host: '', port: port, secret: 'pw', name: 'host'),
ConnectForm());
expect(session.route.peek(), AppRoute.session);
final again = await _Raw.join(port, 'again', secret: 'pw');
await again.ws.close();
await session.leave();
expect(session.hostedServer, isNull);
} finally {
await friend?.ws.close();
await session.coordinator.leave(silent: true);
await session.stopServer();
}
});
test('host path: a Jellyfin pick goes up as a ref with the host relay; File swap',
timeout: const Timeout(Duration(minutes: 2)), () async {
MediaKit.ensureInitialized();
_hive('hive_your_server_test');
final graph = testGraph();
final coord = graph.coordinator;
final yours = graph.yourServer;
final tmp = Platform.environment['WT_TEST_TMP'] ?? Directory.systemTemp.path;
Hive.init('$tmp/hive_isolate_jf_test');
const sid = 'abcdefabcdefabcdefabcdefabcdef12';
final accounts = JellyfinAccounts.instance;
await accounts.ensureLoaded(validate: false);
// An unreachable Jellyfin: only the wire and the relay flag matter here.
await accounts.link(
baseUrl: 'http://127.0.0.1:9',
server: const JellyfinServerInfo(id: sid, name: 'J', version: '10.11.11'),
auth: const JellyfinAuthResult(
accessToken: 'HOSTTOKEN', user: JellyfinUser(id: 'u', name: 'u'), serverId: sid));
final session = SessionState.instance;
final file = File('$tmp/your server file.mkv')..writeAsBytesSync(List.filled(4096, 7));
final port = await _freePort();
_Raw? friend;
final file = File('$tmp/host file swap.mkv')..writeAsBytesSync(List.filled(4096, 7));
try {
await session.host(
ConnectParams(
host: '',
port: port,
secret: '',
name: 'host',
media: const HelloMedia(
name: 'Pilot',
size: 0,
duration: 0,
jellyfin: JellyfinRef(serverId: sid, itemId: 'e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1', title: 'Pilot'))),
ConnectForm());
await session.coordinator.playback.player.setVolume(0);
friend = await _Raw.join(port, 'friend');
final state = await friend.next('state', where: (m) => m['media'] != null);
final media = state['media'] as Map;
expect(media['jellyfin'], isA<Map>());
expect(media.containsKey('url'), isFalse);
expect(state['relay'], isTrue, reason: "the host's own sign-in relays for guests");
expect(jsonEncode(state), isNot(contains('HOSTTOKEN')));
expect(await session.coordinator.swapFile(file.path), isNull);
final swapped = await friend.next('state',
where: (m) => (m['media'] as Map?)?['name'] == 'host file swap.mkv');
expect((swapped['media'] as Map)['jellyfin'], isNull);
expect(swapped['relay'], isNull);
expect(await session.coordinator.swapFile('$tmp/missing.mkv'), contains('not found'));
} finally {
await friend?.ws.close();
await session.coordinator.leave(silent: true);
await session.stopServer();
await accounts.signOut(sid);
if (file.existsSync()) file.deleteSync();
}
});
test('solo: loopback-only server; inviting friends hosts the same media',
timeout: const Timeout(Duration(minutes: 2)), () async {
MediaKit.ensureInitialized();
final tmp = Platform.environment['WT_TEST_TMP'] ?? Directory.systemTemp.path;
Hive.init('$tmp/hive_isolate_solo_test');
final session = SessionState.instance;
final port = await _freePort();
_Raw? friend;
final file = File('$tmp/solo carry.mkv')..writeAsBytesSync(List.filled(4096, 7));
session.route.value = AppRoute.home; // the tests above leave it set
try {
await session.startSolo(const ConnectParams(host: '127.0.0.1', port: 0, secret: '', name: 'me'));
expect(session.route.peek(), AppRoute.session);
expect(session.solo.peek(), isTrue);
await session.coordinator.playback.player.setVolume(0);
final soloPort = session.hostedServer!.port;
// Reachable on loopback only: a LAN address of this machine is refused.
final lan = [
for (final i in await NetworkInterface.list(type: InternetAddressType.IPv4))
for (final a in i.addresses)
if (!a.isLoopback) a,
];
if (lan.isNotEmpty) {
await expectLater(Socket.connect(lan.first, soloPort, timeout: const Duration(seconds: 3)),
expect(await graph.navigation.goHome(), isTrue);
expect(graph.navigation.place.peek(), Place.yours);
await coord.playback.player.setVolume(0);
final ownPort = yours.port.peek()!;
final me = coord.connection.memberId;
expect(me, isNotEmpty);
// Only this app can reach it: a LAN address of this machine is refused.
final lan = await _lanHost();
if (lan != '127.0.0.1') {
await expectLater(Socket.connect(lan, ownPort, timeout: const Duration(seconds: 3)),
throwsA(isA<SocketException>()));
}
expect(await session.coordinator.swapPicked(FileMedia(file.path)), isNull);
await _poll(() => session.coordinator.serverState.peek()?.media?['name'] == 'solo carry.mkv', 'solo media');
expect(coord.alone.peek(), isTrue);
expect(await coord.swapPicked(FileMedia(file.path)), isNull);
await _poll(() => coord.serverState.peek()?.media?['name'] == 'your server file.mkv', 'media up');
await session.host(ConnectParams(host: '', port: port, secret: 'pw', name: 'me'), ConnectForm());
expect(session.solo.peek(), isFalse);
expect(session.route.peek(), AppRoute.session);
friend = await _Raw.join(port, 'friend', secret: 'pw');
await friend.next('state', where: (m) => (m['media'] as Map?)?['name'] == 'solo carry.mkv');
graph.forms.form
..hostPort = '$port'
..hostSecret = 'pw';
final invite = await yours.invite();
expect(invite.port, port);
expect(invite.password, isTrue);
expect(yours.shared.peek(), invite);
expect(identical(await yours.invite(), invite), isTrue, reason: 'already shared: the same invite');
friend = await _Raw.join(port, 'friend', secret: 'pw', host: lan);
final state = await friend.next('state', where: (m) => _members(m).length == 2 && m['media'] != null);
expect(_members(state).firstWhere((m) => m['id'] == me)['host'], isTrue);
friend.ws.add(jsonEncode({
't': 'queue',
'op': 'add',
'item': {
'media': {'name': 'b', 'size': 0, 'duration': 0, 'url': 'http://example.com/b.mp4'},
'how': 'direct',
'title': 'B',
},
}));
await _poll(() => coord.queue.items.peek().length == 1, 'queued by the friend');
expect(coord.alone.peek(), isFalse);
// Anyone may sit the host out; its player unloads, the server serves on.
friend.ws.add(jsonEncode(PresenceIntent(target: me, state: Presence.away).toJson()));
await _poll(() => coord.selfAway.peek(), 'host sat out');
final friendId = _members(state).firstWhere((m) => m['name'] == 'friend')['id'];
coord.nudgeMember('$friendId');
expect((await friend.next('nudge'))['name'], isNotEmpty);
coord.joinBack();
await yours.stopSharing();
expect(await friend.done.future.timeout(const Duration(seconds: 5)), CloseCodes.closed,
reason: 'told: their app does not retry');
await _poll(() => coord.alone.peek(), 'alone again');
expect(coord.connection.memberId, me, reason: 'the same member, never reconnected');
expect(coord.restarts.peek(), 0);
expect(coord.queue.items.peek(), hasLength(1), reason: 'Up next stays');
expect(coord.serverState.peek()?.media?['name'], 'your server file.mkv');
expect(yours.port.peek(), ownPort, reason: 'nothing restarted');
final freed = await ServerSocket.bind(InternetAddress.anyIPv4, port);
await freed.close();
// A crash: said, and home again on a new server.
yours.server!.isolate.kill(priority: Isolate.immediate);
await _poll(() => yours.crash.peek() != null, 'crash reported');
await _poll(() => graph.navigation.place.peek() == Place.yours && yours.port.peek() != null, 'home again');
expect(yours.crash.peek(), startsWith('server crashed'));
} finally {
await friend?.ws.close();
await session.leave();
await graph.navigation.leave();
await yours.stop();
if (file.existsSync()) file.deleteSync();
}
});
test('a friend\'s server and back: yours keeps what plays and Up next', timeout: const Timeout(Duration(minutes: 2)),
() async {
_hive('hive_your_server_switch_test');
final graph = testGraph();
final coord = graph.coordinator;
final yours = graph.yourServer;
final theirs = SyncServer(const AppConfig(port: 0, secret: '', name: "Bob's server"));
await theirs.start();
try {
expect(await graph.navigation.goHome(), isTrue);
await coord.playback.player.setVolume(0);
final ownPort = yours.port.peek();
coord.connection.sendSwap(const HelloMedia(name: 'mine', size: 0, duration: 0, url: 'http://127.0.0.1:9/mine.mp4'));
expect(await coord.queue.add(const LinkMedia('http://127.0.0.1:9/next.mp4', relay: LinkRelay.direct, anyway: true)), isNull);
await _poll(() => coord.serverState.peek()?.media?['name'] == 'mine' && coord.queue.items.peek().length == 1,
'media and Up next on your server');
await graph.navigation.join(ConnectParams(host: '127.0.0.1', port: theirs.boundPort, secret: '', name: 'me'));
expect(graph.navigation.place.peek(), Place.friend);
expect(graph.navigation.serverLabel.peek(), "Bob's server");
expect(coord.hostFile, isNull, reason: 'not your server');
await _poll(() => theirs.hub.engine.members.length == 1, 'in their server');
expect(yours.port.peek(), ownPort, reason: 'yours stays up, quiet');
expect(graph.forms.recents.peek().first.port, '${theirs.boundPort}');
expect(await graph.navigation.leaveFriend(), isTrue);
expect(graph.navigation.place.peek(), Place.yours);
await _poll(() => coord.serverState.peek()?.media?['name'] == 'mine', 'your media again');
expect(coord.queue.items.peek(), hasLength(1));
expect(yours.port.peek(), ownPort);
await _poll(() => theirs.hub.engine.members.isEmpty, 'left theirs with bye');
} finally {
await graph.navigation.leave();
await yours.stop();
await theirs.stop();
}
});
test('a friend stops sharing: told, and you are back home on yours', timeout: const Timeout(Duration(minutes: 2)),
() async {
_hive('hive_your_server_closed_test');
final me = testGraph();
final bob = testGraph();
final port = await _freePort();
try {
expect(await bob.navigation.goHome(), isTrue);
await bob.coordinator.playback.player.setVolume(0);
bob.forms.form
..hostPort = '$port'
..hostSecret = '';
final invite = await bob.yourServer.invite();
expect(await me.navigation.goHome(), isTrue);
await me.coordinator.playback.player.setVolume(0);
final mine = me.yourServer.port.peek();
await me.navigation.join(ConnectParams(host: '127.0.0.1', port: invite.port, secret: '', name: 'me'));
expect(me.navigation.place.peek(), Place.friend);
await _poll(() => !bob.coordinator.alone.peek(), 'bob sees me');
await bob.yourServer.stopSharing();
await _poll(() => me.navigation.place.peek() == Place.yours, 'back home');
expect(me.yourServer.port.peek(), mine, reason: 'the same server as before');
await _poll(() => me.notifier.toasts.peek().any((t) => t.text.contains('stopped sharing')), 'told why');
await _poll(() => bob.coordinator.alone.peek(), 'bob alone again');
} finally {
await me.navigation.leave();
await bob.navigation.leave();
await me.yourServer.stop();
await bob.yourServer.stop();
}
});
}
+70 -49
View File
@@ -1,5 +1,3 @@
// restructure: rewrite in step 3 (Your server): the solo strip and Invite
// friends.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
@@ -19,10 +17,17 @@ import 'package:starsync/src/shell/session_player.dart';
import 'package:starsync/src/shell/settings_tab.dart' show SettingsTab;
import 'package:starsync/src/shell/toasts.dart';
import 'package:starsync/src/session/session_coordinator.dart' show ToastItem;
import 'package:starsync/src/state/session_state.dart';
import 'package:starsync/src/state/settings.dart';
import 'package:starsync/src/update/update_controller.dart';
import 'package:starsync/src/session/invite.dart' show Invite;
import 'package:starsync/src/session/navigation.dart' show Place;
import 'test_graph.dart';
/// This file's composition root (see test_graph.dart).
final _graph = testGraph();
/// Stands in for media_kit's `Video` (which hangs flutter_test) and
/// counts how often one is created.
class FakeVideo extends StatefulWidget {
@@ -55,7 +60,7 @@ MemberView member(String id, String name, {bool ready = false, bool gone = false
presence: gone ? Presence.gone : Presence.watching);
void main() {
final session = SessionState.instance;
final session = _graph;
final coord = session.coordinator;
void online(List<MemberView> members, {bool media = true}) {
@@ -68,16 +73,16 @@ void main() {
media: media ? {'name': 'Movie.mkv', 'size': 1, 'duration': 0} : null,
members: members,
);
session.route.value = AppRoute.session;
session.navigation.place.value = Place.friend;
}
setUp(() {
FakeVideo.created = 0;
session.recents.value = const [];
session.forms.recents.value = const [];
});
tearDown(() {
session.route.value = AppRoute.home;
session.navigation.place.value = Place.none;
coord.serverState.value = null;
coord.playback.alive.value = false;
session.notifier.clear();
@@ -87,7 +92,7 @@ void main() {
tester.view.physicalSize = size;
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
await tester.pumpWidget(MaterialApp(
await tester.pumpWidget(scoped(_graph, MaterialApp(
theme: ThemeData.dark(),
home: AppShell(
updates: updates ?? UpdateController(currentVersion: '0.0.0-dev'),
@@ -97,7 +102,7 @@ void main() {
// A real probe (network, yt-dlp) never answers on the test clock.
linkProbe: (url) async => LinkProbe.file(Uri.parse(url), 1000),
),
));
)));
await tester.pumpAndSettle();
}
@@ -148,14 +153,53 @@ void main() {
});
group('party strip', () {
testWidgets('offline: Join and Host, no party', (tester) async {
testWidgets('home, alone: a plain player\'s strip, Join a friend and Invite (once your server runs)',
(tester) async {
await pumpShell(tester, const Size(1280, 800));
expect(find.byKey(const ValueKey('strip-join')), findsOneWidget);
expect(find.byKey(const ValueKey('strip-host')), findsOneWidget);
expect(find.text('Offline'), findsOneWidget);
expect(find.byKey(const ValueKey('strip-host')), findsNothing, reason: 'no Host: your server is always there');
expect(find.byKey(const ValueKey('party-avatars')), findsNothing);
expect(find.byKey(const ValueKey('strip-leave')), findsNothing);
expect(find.byKey(const ValueKey('strip-chat')), findsNothing);
expect(tester.getSize(find.byType(PartyStrip)).height, partyStripHeight);
ButtonStyleButton invite() => tester.widget<ButtonStyleButton>(find.byKey(const ValueKey('strip-invite')));
expect(invite().onPressed, isNull, reason: 'your server is not up yet');
final yours = session.yourServer;
yours.port.value = 40000;
addTearDown(() {
yours.port.value = null;
yours.shared.value = null;
});
// On your own server with only you in it: still the plain strip.
session.navigation.place.value = Place.yours;
coord.serverState.value = StateBroadcast(
eventId: 1, transport: 'held', position: 0, serverTime: DateTime.now().toUtc(), mediaId: 0,
members: [member('', 'Me')]);
await tester.pumpAndSettle();
expect(invite().onPressed, isNotNull);
expect(find.byKey(const ValueKey('party-avatars')), findsNothing);
expect(find.byKey(const ValueKey('strip-chat')), findsNothing);
expect(find.byKey(const ValueKey('sharing-chip')), findsNothing);
// Shared, nobody came yet: the chip says so (and opens the invite).
yours.shared.value = const Invite(host: '192.168.1.20', port: 8080);
await tester.pumpAndSettle();
expect(find.byKey(const ValueKey('sharing-chip')), findsOneWidget);
expect(find.text('port 8080'), findsOneWidget);
await tester.tap(find.byKey(const ValueKey('sharing-chip')));
await tester.pumpAndSettle();
expect(find.byKey(const ValueKey('stop-sharing')), findsOneWidget);
await tester.tapAt(const Offset(40, 700));
await tester.pumpAndSettle();
// A friend came: the party, with Invite and no Leave (it is yours).
coord.serverState.value = StateBroadcast(
eventId: 2, transport: 'held', position: 0, serverTime: DateTime.now().toUtc(), mediaId: 0,
members: [member('', 'Me'), member('b', 'Bob')]);
await tester.pumpAndSettle();
expect(find.byKey(const ValueKey('party-avatars')), findsOneWidget);
expect(find.byKey(const ValueKey('strip-chat')), findsOneWidget);
expect(find.byKey(const ValueKey('strip-invite')), findsOneWidget);
expect(find.byKey(const ValueKey('strip-leave')), findsNothing);
expect(find.text('Your server'), findsOneWidget);
});
testWidgets('online: avatars, server and readiness, chat, Leave', (tester) async {
@@ -179,30 +223,7 @@ void main() {
expect(find.text('Leave server?'), findsOneWidget);
await tester.tap(find.text('Cancel'));
await tester.pumpAndSettle();
expect(session.route.value, AppRoute.session);
});
testWidgets('solo: just you, Invite friends opens the host card, Stop asks nothing', (tester) async {
await pumpShell(tester, const Size(1280, 800));
session.solo.value = true;
addTearDown(() => session.solo.value = false);
online([member('me', 'Me')], media: false);
await tester.pumpAndSettle();
expect(find.byKey(const ValueKey('solo-chip')), findsOneWidget);
expect(find.byKey(const ValueKey('party-avatars')), findsNothing);
expect(find.byKey(const ValueKey('strip-chat')), findsNothing);
expect(find.byKey(const ValueKey('welcome-band')), findsNothing);
await tester.tap(find.byKey(const ValueKey('strip-invite')));
await tester.pumpAndSettle();
expect(find.text('Invite friends'), findsWidgets);
expect(find.text('Start hosting'), findsOneWidget);
await tester.tapAt(const Offset(5, 790));
await tester.pumpAndSettle();
await tester.tap(find.byKey(const ValueKey('strip-leave')));
await tester.pumpAndSettle();
expect(find.text('Leave server?'), findsNothing);
expect(session.route.value, AppRoute.home);
expect(session.solo.value, isFalse);
expect(session.navigation.place.value, Place.friend);
});
testWidgets('compact below 1100 px: 3 avatars, no server text', (tester) async {
@@ -221,8 +242,8 @@ void main() {
group('popovers', () {
testWidgets('members card opens from the avatars and closes outside', (tester) async {
await pumpShell(tester, const Size(1280, 800));
session.serverVersion.value = '1.3.0-dev.1';
addTearDown(() => session.serverVersion.value = '');
session.navigation.serverVersion.value = '1.3.0-dev.1';
addTearDown(() => session.navigation.serverVersion.value = '');
online([member('a', 'Alex', ready: true, app: '1.3.0-dev.1'), ...party.skip(1)], media: false);
await tester.pumpAndSettle();
await tester.tap(find.byKey(const ValueKey('avatar-stack')));
@@ -255,7 +276,7 @@ void main() {
await tester.tap(find.byKey(const ValueKey('strip-profile')));
await tester.pumpAndSettle();
expect(find.byType(ProfileCard), findsOneWidget);
expect(find.text('offline'), findsOneWidget);
expect(find.text('just you'), findsOneWidget);
await tester.tap(find.text('About'));
await tester.pumpAndSettle();
expect(find.byType(ProfileCard), findsNothing);
@@ -263,7 +284,7 @@ void main() {
});
testWidgets('showPopover fades and scales in, Esc closes it', (tester) async {
await tester.pumpWidget(MaterialApp(
await tester.pumpWidget(scoped(_graph, MaterialApp(
home: Builder(
builder: (context) => Center(
child: TextButton(
@@ -272,7 +293,7 @@ void main() {
),
),
),
));
)));
await tester.tap(find.text('open'));
await tester.pump();
await tester.pump(easeTime ~/ 2);
@@ -303,7 +324,7 @@ void main() {
await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft);
await tester.pumpAndSettle();
expect(find.byKey(const ValueKey('handoff-card')), findsOneWidget);
expect(find.text('Open in Link'), findsOneWidget); // offline
expect(find.text('Open in Link'), findsOneWidget); // alone
await tester.tap(find.byKey(const ValueKey('handoff-openLink')));
await tester.pumpAndSettle();
expect(find.byKey(const ValueKey('handoff-card')), findsNothing);
@@ -318,15 +339,15 @@ void main() {
final before = p.push;
p.push = ({String? name, String? avatar}) => pushed.add(name);
addTearDown(() => p.push = before);
session.lastForm.name = 'Old';
session.forms.form.name = 'Old';
p.name.value = 'Old';
await tester.pumpWidget(MaterialApp(
await tester.pumpWidget(scoped(_graph, MaterialApp(
home: Scaffold(body: Center(child: ProfileCard(onOpenSettings: (_) {}))),
));
)));
await tester.enterText(find.byKey(const ValueKey('profile-name')), 'Neo');
await tester.pump();
expect(p.name.value, 'Neo');
expect(session.lastForm.name, 'Neo');
expect(session.forms.form.name, 'Neo');
// Typing settles before it is sent, once.
expect(pushed, isEmpty);
await tester.pump(const Duration(milliseconds: 700));
@@ -391,7 +412,7 @@ void main() {
// Never rebuilt from scratch on the way.
expect(FakeVideo.created, 1);
// Offline: no player at all.
session.route.value = AppRoute.home;
session.navigation.place.value = Place.none;
await tester.pumpAndSettle();
expect(videos, findsNothing);
expect(tester.takeException(), isNull);
@@ -439,7 +460,7 @@ void main() {
});
testWidgets("toasts slide in and leave when the Notifier's time is up", (tester) async {
await tester.pumpWidget(const MaterialApp(home: Scaffold(body: PartyToasts())));
await tester.pumpWidget(scoped(_graph, const MaterialApp(home: Scaffold(body: PartyToasts()))));
session.notifier.notify(const Copied('Shaders off'));
await tester.pump();
await tester.pump();
@@ -484,7 +505,7 @@ void main() {
final down = tester.getRect(find.byType(ToastCard));
expect(down.bottom, closeTo(body.bottom - AppShellState.toastInset, 1));
expect(down.bottom, greaterThan(up.bottom));
session.route.value = AppRoute.home;
session.navigation.place.value = Place.none;
await tester.pump(const Duration(seconds: 6));
await tester.pumpAndSettle();
});
+47
View File
@@ -0,0 +1,47 @@
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
/// The app's own `.instance` singletons and how often `lib` reaches for
/// each. Systems get their dependencies through the composition root
/// (`AppGraph`, widgets through `AppScope`); this list may only shrink.
/// Lower a number when a use goes; never raise one or add a class.
const baseline = {
'AppSettings': 55,
'JellyfinAccounts': 10,
'UpdateController': 8,
'Profile': 8,
'FolderStore': 6,
'AppYtDlp': 4,
'RecentLinks': 3,
};
void main() {
test('no new .instance singletons, and no more uses of the old ones', () {
final files = Directory('lib')
.listSync(recursive: true)
.whereType<File>()
.where((f) => f.path.endsWith('.dart'))
.toList();
final sources = [for (final f in files) f.readAsStringSync()];
// The app's own classes (framework singletons like
// `WidgetsBinding.instance` are not counted).
final classes = {
for (final s in sources)
for (final m in RegExp(r'^(?:abstract |final |base )*class (\w+)', multiLine: true).allMatches(s)) m.group(1)!,
};
final counts = <String, int>{};
for (final s in sources) {
for (final m in RegExp(r'\b([A-Z]\w*)\.instance\b').allMatches(s)) {
final name = m.group(1)!;
if (classes.contains(name)) counts[name] = (counts[name] ?? 0) + 1;
}
}
final grown = {
for (final e in counts.entries)
if (e.value > (baseline[e.key] ?? 0)) e.key: '${e.value} (baseline ${baseline[e.key] ?? 'none'})',
};
expect(grown, isEmpty,
reason: 'pass the system in through AppGraph / AppScope instead of a new `.instance` use or singleton');
});
}
+14
View File
@@ -0,0 +1,14 @@
// Test support (not a test): the app's composition root for tests.
import 'package:flutter/widgets.dart';
import 'package:starsync/src/app/app_graph.dart';
import 'package:starsync/src/screens/home/health_probe.dart';
import 'package:starsync/src/session/identity.dart' show ClientIdentity;
/// One graph per test file, like the app's one per run: nothing starts
/// until a test calls `navigation.start()` (or `goHome`), so widget tests
/// see the app before your server is up.
AppGraph testGraph({HealthGetter healthGet = defaultHealthGet}) =>
AppGraph.build(identity: ClientIdentity.ephemeral(), healthGet: healthGet);
/// [child] under [graph]'s [AppScope].
Widget scoped(AppGraph graph, Widget child) => AppScope(graph: graph, child: child);
+9 -4
View File
@@ -2,20 +2,25 @@ import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:starsync/src/widgets/text_focus.dart';
import 'test_graph.dart';
/// This file's composition root (see test_graph.dart).
final _graph = testGraph();
void main() {
// Regression: the old FocusNode-parent walk never met EditableText, so
// session shortcuts (Space, arrows, F) fired while typing in chat.
testWidgets('text field focus is detected, buttons are not', (tester) async {
final field = FocusNode();
final button = FocusNode();
await tester.pumpWidget(MaterialApp(
await tester.pumpWidget(scoped(_graph, MaterialApp(
home: Scaffold(
body: Column(children: [
TextField(focusNode: field),
TextButton(focusNode: button, onPressed: () {}, child: const Text('b')),
]),
),
));
)));
expect(textInputFocused(), isFalse);
field.requestFocus();
@@ -33,9 +38,9 @@ void main() {
testWidgets('focus under a KeyboardClaim counts as typing', (tester) async {
final claimed = FocusNode();
await tester.pumpWidget(MaterialApp(
await tester.pumpWidget(scoped(_graph, MaterialApp(
home: KeyboardClaim(child: Focus(focusNode: claimed, child: const SizedBox())),
));
)));
expect(textInputFocused(), isFalse);
claimed.requestFocus();
await tester.pump();
+9 -5
View File
@@ -6,16 +6,20 @@ import 'package:media_kit_video/media_kit_video.dart' show VideoState;
import 'package:starsync/src/controls/model/controls_prefs.dart';
import 'package:starsync/src/controls/frame.dart';
import 'package:starsync/src/shell/session_player.dart';
import 'package:starsync/src/state/session_state.dart';
import 'package:starsync/src/state/settings.dart';
import 'test_graph.dart';
/// This file's composition root (see test_graph.dart).
final _graph = testGraph();
// The wheel anywhere on the full player flashes the volume readout, in
// both skins, windowed and fullscreen, with the controls up or hidden.
// The picture is a black box with the session's controls on it (never a
// media_kit `Video`).
void main() {
final coord = SessionState.instance.coordinator;
final coord = _graph.coordinator;
final s = AppSettings.instance;
// A real player for the volume steps to go to. Never disposed: the
@@ -46,7 +50,7 @@ void main() {
for (final fullscreen in [false, true]) {
final what = '${skin.name}, ${fullscreen ? 'fullscreen' : 'windowed'}';
s.controlsSkin.value = skin;
await tester.pumpWidget(MaterialApp(
await tester.pumpWidget(scoped(_graph, MaterialApp(
theme: ThemeData.dark(),
home: Scaffold(
body: SessionPlayer(
@@ -68,7 +72,7 @@ void main() {
]),
),
),
));
)));
await tester.pump();
expect(opacity(), 0, reason: '$what: nothing before a step');
@@ -91,7 +95,7 @@ void main() {
expect(opacity(), 0, reason: '$what: gone after the second');
}
}
await tester.pumpWidget(const SizedBox());
await tester.pumpWidget(scoped(_graph, const SizedBox()));
await tester.pump(const Duration(seconds: 5));
});
}