feat: new ui (#1455)

This commit is contained in:
Levi authored and GitHub committed 2026-09-05 19:53:41 +08:00
1 parent 3be8db664c
commit 177c225f16
742 files changed
+59951 -5934

No files matched your search

@@ -0,0 +1,20 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:gopeed/api/model/downloader_config.dart';
void main() {
test('auto-start tasks uses the backend-owned top-level config field', () {
final config = DownloaderConfig(autoStartTasks: true);
final json = config.toJson();
expect(json['autoStartTasks'], isTrue);
expect(json['extra'], isNot(contains('autoStartTasks')));
expect(DownloaderConfig.fromJson(json).autoStartTasks, isTrue);
});
test('legacy extra auto-start setting is not migrated', () {
final json = DownloaderConfig().toJson();
(json['extra'] as Map<String, dynamic>)['autoStartTasks'] = true;
expect(DownloaderConfig.fromJson(json).autoStartTasks, isFalse);
});
}
+51
View File
@@ -0,0 +1,51 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:gopeed/api/api.dart' as api;
import 'package:gopeed/api/model/options.dart';
import 'package:gopeed/api/model/request.dart';
import 'package:gopeed/api/model/resolve_task.dart';
void main() {
test('resolve sends the complete resolve task for magnet links', () async {
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
addTearDown(server.close);
late Map<String, dynamic> requestBody;
final responseHandled = Completer<void>();
server.listen((request) async {
requestBody = jsonDecode(await utf8.decoder.bind(request).join()) as Map<String, dynamic>;
request.response.headers.contentType = ContentType.json;
request.response.write(
jsonEncode({
'code': 0,
'data': {
'id': 'resolved-id',
'res': {'name': 'sample', 'size': 0, 'range': false, 'files': <Object>[], 'hash': ''},
},
}),
);
await request.response.close();
responseHandled.complete();
});
api.init('tcp', '127.0.0.1:${server.port}', '');
final result = await api.resolve(
ResolveTask(
req: Request(url: 'magnet:?xt=urn:btih:0123456789abcdef0123456789abcdef01234567'),
opts: Options(path: '/downloads', selectFiles: const []),
),
);
await responseHandled.future;
expect(result.id, 'resolved-id');
expect(requestBody.keys, containsAll(<String>['req', 'opts']));
expect(
(requestBody['req'] as Map<String, dynamic>)['url'],
'magnet:?xt=urn:btih:0123456789abcdef0123456789abcdef01234567',
);
expect((requestBody['opts'] as Map<String, dynamic>)['path'], '/downloads');
});
}
+192
View File
@@ -0,0 +1,192 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:gopeed/api/model/task.dart';
import 'package:gopeed/api/model/task_stats.dart';
void main() {
test('HTTP stats parse the current Go connection payload', () {
final stats =
TaskStats.fromJson(Protocol.http, {
'snapshot': {
'connections': [
{'downloaded': 1024, 'total': 4096, 'completed': false, 'failed': false, 'retryTimes': 2},
{'downloaded': 2048, 'total': 2048, 'completed': true, 'failed': false, 'retryTimes': 0},
],
},
'runtime': null,
})
as HttpTaskStats;
expect(stats.connections, hasLength(2));
expect(stats.connections.first.downloaded, 1024);
expect(stats.connections.first.total, 4096);
expect(stats.connections.first.retryTimes, 2);
expect(stats.connections.last.completed, isTrue);
});
test('BT stats decode the ordered completion bitset and peer transport', () {
final stats =
TaskStats.fromJson(Protocol.bt, {
'snapshot': {
'seedBytes': 820,
'seedRatio': 0.64,
'seedTime': 3723,
'pieceMap': {
'encoding': 'bitset-v1',
'pieceCount': 8,
'pieceSize': 16384,
'completedPieces': 3,
'data': 'hQ==',
},
},
'runtime': {
'totalPeers': 128,
'activePeers': 16,
'connectedSeeders': 8,
'connectedLeechers': 8,
'peers': [
{
'address': '127.0.0.1:6881',
'client': 'Gopeed',
'downloadSpeed': 2048,
'uploadSpeed': 1024,
'pieceCount': 12,
'completion': 0.75,
'relevance': 0.25,
'source': 'PEX',
'transport': 'utp',
},
],
},
})
as BtTaskStats;
expect(stats.activePeers, 16);
expect(stats.connectedLeechers, 8);
expect(stats.seedTime, 3723);
expect(stats.pieceMap.toStates(), [
TaskPieceState.completed,
TaskPieceState.pending,
TaskPieceState.completed,
TaskPieceState.pending,
TaskPieceState.pending,
TaskPieceState.pending,
TaskPieceState.pending,
TaskPieceState.completed,
]);
expect(stats.pieceMap.completedPieces, 3);
expect(stats.pieceMap.pieceSize, 16384);
expect(stats.peers.single.downloadSpeed, 2048);
expect(stats.peers.single.pieceCount, 12);
expect(stats.peers.single.completion, 0.75);
expect(stats.peers.single.relevance, 0.25);
expect(stats.peers.single.transport, 'utp');
});
test('BT persisted snapshot remains useful when runtime is absent', () {
final stats =
TaskStats.fromJson(Protocol.bt, {
'snapshot': {
'seedBytes': 820,
'seedRatio': 0.64,
'seedTime': 65,
'pieceMap': {
'encoding': 'bitset-v1',
'pieceCount': 4,
'pieceSize': 16384,
'completedPieces': 2,
'data': 'Aw==',
},
},
'runtime': null,
})
as BtTaskStats;
expect(stats.totalPeers, 0);
expect(stats.activePeers, 0);
expect(stats.connectedLeechers, 0);
expect(stats.seedTime, 65);
expect(stats.peers, isEmpty);
expect(stats.pieceMap.completedPieces, 2);
expect(stats.pieceMap.toStates(), [
TaskPieceState.completed,
TaskPieceState.completed,
TaskPieceState.pending,
TaskPieceState.pending,
]);
});
test('piece map rejects unsupported versions and malformed byte lengths', () {
expect(
TaskPieceMap.fromJson({
'encoding': 'bitset-v2',
'pieceCount': 4,
'pieceSize': 1024,
'completedPieces': 0,
'data': 'AA==',
}),
isNull,
);
expect(
TaskPieceMap.fromJson({
'encoding': 'bitset-v1',
'pieceCount': 9,
'pieceSize': 1024,
'completedPieces': 0,
'data': 'AA==',
}),
isNull,
);
});
test('stats models ignore fields that are not part of the Go response contract', () {
final http =
TaskStats.fromJson(Protocol.http, {
'snapshot': {
'connections': [
{'received': 1024, 'completed': false, 'failed': false, 'retries': 2},
],
},
})
as HttpTaskStats;
final bt =
TaskStats.fromJson(Protocol.bt, {
'snapshot': {
'uploaded': 1024,
'shareRatio': 0.5,
'pieces': [2, 1, 0],
},
'runtime': {'seeders': 8},
})
as BtTaskStats;
expect(http.connections.single.downloaded, 0);
expect(http.connections.single.retryTimes, 0);
expect(bt.connectedSeeders, 0);
expect(bt.seedBytes, 0);
expect(bt.seedRatio, 0);
expect(bt.pieceMap.isEmpty, isTrue);
});
test('ED2K stats parse the existing aggregate fields', () {
final stats =
TaskStats.fromJson(Protocol.ed2k, {
'snapshot': {'upload': 320, 'totalDone': 68, 'totalWanted': 100},
'runtime': {'activePeers': 12, 'totalPeers': 86, 'downloadRate': 4800000, 'uploadRate': 320000},
})
as Ed2kTaskStats;
expect(stats.totalPeers, 86);
expect(stats.downloadRate, 4800000);
expect(stats.totalDone / stats.totalWanted, 0.68);
expect(stats.peers, isEmpty);
});
test('a missing protocol has no statistics panel', () {
expect(
TaskStats.fromJson(null, {
'snapshot': {'value': 1},
}),
isNull,
);
});
}
@@ -0,0 +1,30 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:gopeed/app/application/app_deep_link_controller.dart';
import 'package:share_handler/share_handler.dart';
void main() {
test('keeps the established path-style Gopeed deep-link routes', () {
expect(gopeedDeepLinkRoute(Uri.parse('gopeed:///create')), '/create');
expect(gopeedDeepLinkRoute(Uri.parse('gopeed:///extension')), '/extension');
});
test('rejects host-style Gopeed deep-link routes', () {
expect(gopeedDeepLinkRoute(Uri.parse('gopeed://create')), isEmpty);
expect(gopeedDeepLinkRoute(Uri.parse('gopeed://extension')), isEmpty);
});
test('uses a shared attachment path before an optional caption', () {
final media = SharedMedia(
content: 'https://example.com/caption',
attachments: [SharedAttachment(path: '/tmp/example.torrent', type: SharedAttachmentType.file)],
);
expect(sharedMediaUri(media), Uri.file('/tmp/example.torrent'));
});
test('uses shared text when there is no attachment', () {
final media = SharedMedia(content: ' magnet:?xt=urn:btih:example ');
expect(sharedMediaUri(media), Uri.parse('magnet:?xt=urn:btih:example'));
});
}
+85
View File
@@ -0,0 +1,85 @@
import 'package:flutter/foundation.dart' show TargetPlatform, debugDefaultTargetPlatformOverride;
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:gopeed/shared/theme/app_palette.dart';
import 'package:gopeed/shared/theme/app_theme.dart';
import 'package:gopeed/shared/widgets/detail/app_detail_surface_desktop.dart';
import 'package:shadcn_flutter/shadcn_flutter.dart' as shad;
void main() {
test('Android themes use platform fonts', () {
debugDefaultTargetPlatformOverride = TargetPlatform.android;
try {
final typography = AppTheme.light().typography;
expect(typography.sans.fontFamily, isNull);
expect(typography.mono.fontFamily, 'monospace');
} finally {
debugDefaultTargetPlatformOverride = null;
}
});
test('Windows themes use a deterministic CJK font fallback', () {
debugDefaultTargetPlatformOverride = TargetPlatform.windows;
try {
final shadTheme = AppTheme.light();
final materialTheme = AppTheme.materialLight();
expect(shadTheme.typography.sans.fontFamily, 'packages/shadcn_flutter/GeistSans');
expect(shadTheme.typography.sans.fontFamilyFallback, const ['Microsoft YaHei UI']);
expect(materialTheme.textTheme.bodyMedium?.fontFamilyFallback, const ['Microsoft YaHei UI']);
expect(materialTheme.primaryTextTheme.bodyMedium?.fontFamilyFallback, const ['Microsoft YaHei UI']);
} finally {
debugDefaultTargetPlatformOverride = null;
}
});
test('light theme separates navigation, canvas, and raised surfaces', () {
const palette = AppPalette.light;
expect(palette.railBg, isNot(palette.sideBg));
expect(palette.sideBg, isNot(palette.bg));
expect(palette.bg, isNot(palette.cardBg));
expect(palette.railBg, isNot(palette.cardBg));
});
testWidgets('desktop detail drawer is raised only in the light theme', (tester) async {
const drawerKey = ValueKey('palette-test-detail-drawer');
Future<BoxDecoration> pumpDrawer({required bool light}) async {
final palette = light ? AppPalette.light : AppPalette.dark;
await tester.pumpWidget(
shad.ShadcnApp(
theme: light ? AppTheme.light() : AppTheme.dark(),
materialTheme: light ? AppTheme.materialLight() : AppTheme.materialDark(),
home: SizedBox.expand(
child: AppDetailDrawer(
open: true,
title: 'Details',
onClose: () {},
drawerKey: drawerKey,
child: const SizedBox(),
),
),
),
);
await tester.pumpAndSettle();
final drawer = tester.widget<Container>(find.byKey(drawerKey));
final decoration = drawer.decoration! as BoxDecoration;
final border = decoration.border! as Border;
expect(border.left.color, light ? palette.headerDivider : palette.border);
expect(border.top.color, palette.headerDivider);
expect(find.byKey(const ValueKey('app-detail-drawer-close-button')), findsOneWidget);
return decoration;
}
final lightDecoration = await pumpDrawer(light: true);
expect(lightDecoration.color, AppPalette.light.cardBg);
expect(lightDecoration.boxShadow, isNotEmpty);
final darkDecoration = await pumpDrawer(light: false);
expect(darkDecoration.color, AppPalette.dark.bg);
expect(darkDecoration.boxShadow, isNull);
});
}
@@ -0,0 +1,44 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:gopeed/core/capabilities/capability_rpc.dart';
import 'package:gopeed/core/window/app_window_appearance.dart';
class _Payload {
const _Payload(this.value);
factory _Payload.fromJson(Map<String, dynamic> json) => _Payload(json['value'] as int);
final int value;
Map<String, dynamic> toJson() => {'value': value};
}
void main() {
test('one method descriptor supports direct and serialized dispatch', () async {
const method = RpcMethod<_Payload, _Payload>('test.increment');
final codecs = RpcCodecRegistry()..register<_Payload>((json) => _Payload.fromJson(json! as Map<String, dynamic>));
final registry = CapabilityRegistry(codecs)..bind(method, (payload) => _Payload(payload.value + 1));
final local = await LocalCapabilityInvoker(registry).invoke(method, const _Payload(1));
final serialized = codecs.decode<_Payload>(await registry.invoke(method.name, codecs.encode(const _Payload(4))));
expect(local.value, 2);
expect(serialized.value, 5);
});
test('appearance snapshots use the shared codec registry', () {
final codecs = RpcCodecRegistry()
..register<AppWindowAppearance>((json) => AppWindowAppearance.fromJson(json! as Map<String, dynamic>));
const appearance = AppWindowAppearance(themeMode: 'dark', themeColor: 'blue', locale: 'zh');
expect(codecs.decode<AppWindowAppearance>(codecs.encode(appearance)), appearance);
});
test('unknown capabilities return a structured error', () async {
final registry = CapabilityRegistry(RpcCodecRegistry());
expect(
() => registry.invoke('missing', null),
throwsA(isA<CapabilityException>().having((error) => error.code, 'code', 'method_not_found')),
);
});
}
@@ -0,0 +1,32 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:gopeed/core/entry/app_startup_options.dart';
void main() {
test('starts hidden for the launch-at-startup flag', () {
expect(AppStartupOptions.fromArgs(const ['--hidden']).hidden, isTrue);
});
test('starts hidden for the browser host silent wake URI', () {
expect(AppStartupOptions.fromArgs(const ['gopeed:?hidden=true']).hidden, isTrue);
expect(AppStartupOptions.fromArgs(const ['gopeed:///?hidden=true']).hidden, isTrue);
});
test('does not hide task and extension deep links', () {
expect(AppStartupOptions.fromArgs(const ['gopeed:///create?hidden=true']).hidden, isFalse);
expect(AppStartupOptions.fromArgs(const ['gopeed:///extension']).hidden, isFalse);
});
test('merges a platform-provided initial URI before the window is shown', () {
final options = AppStartupOptions.fromArgs(const []);
expect(options.withInitialUri(Uri.parse('gopeed:?hidden=true')).hidden, isTrue);
expect(options.withInitialUri(Uri.parse('gopeed:///create')).hidden, isFalse);
});
test('recognizes only the root hidden wake URI', () {
expect(isSilentGopeedWakeUri(Uri.parse('gopeed:?hidden=true')), isTrue);
expect(isSilentGopeedWakeUri(Uri.parse('gopeed:///?hidden=true')), isTrue);
expect(isSilentGopeedWakeUri(Uri.parse('gopeed:///create?hidden=true')), isFalse);
expect(isSilentGopeedWakeUri(Uri.parse('https://example.com/?hidden=true')), isFalse);
});
}
@@ -0,0 +1,13 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:gopeed/core/utils/byte_size_formatter.dart';
void main() {
test('formats scaled byte sizes with up to two decimal places', () {
expect(ByteSizeFormatter.format(-1), '0 B');
expect(ByteSizeFormatter.format(512), '512 B');
expect(ByteSizeFormatter.format(1536), '1.5 KB');
expect(ByteSizeFormatter.format(1280), '1.25 KB');
expect(ByteSizeFormatter.format(32 * 1024 * 1024), '32 MB');
expect(ByteSizeFormatter.format(2 * 1024 * 1024 * 1024), '2 GB');
});
}
@@ -0,0 +1,8 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:gopeed/core/utils/content_uri_resolver.dart';
void main() {
test('rejects non-content URIs', () async {
expect(() => ContentUriResolver.copyToCache(Uri.parse('file:///tmp/example.torrent')), throwsArgumentError);
});
}
@@ -0,0 +1,14 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:gopeed/core/utils/transfer_rate_formatter.dart';
void main() {
test('formats transfer rates with adaptive binary units', () {
expect(TransferRateFormatter.format(-1).text, '0 B/s');
expect(TransferRateFormatter.format(512).text, '512 B/s');
expect(TransferRateFormatter.format(96 * 1024).text, '96 KB/s');
expect(TransferRateFormatter.format(1536).text, '1.5 KB/s');
expect(TransferRateFormatter.format(1280).text, '1.25 KB/s');
expect(TransferRateFormatter.format(10 * 1024 * 1024).text, '10 MB/s');
expect(TransferRateFormatter.format(2 * 1024 * 1024 * 1024).text, '2 GB/s');
});
}
@@ -0,0 +1,61 @@
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:gopeed/api/model/create_task.dart';
import 'package:gopeed/api/model/request.dart';
import 'package:gopeed/core/window/app_window_launcher.dart';
import 'package:gopeed/core/window/window_capability_transport.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
const multiWindowChannel = MethodChannel('mixin.one/desktop_multi_window');
const windowChannels = MethodChannel('mixin.one/desktop_multi_window/channels');
final messenger = TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
setUp(() {
messenger.setMockMethodCallHandler(windowChannels, (call) async => null);
});
tearDown(() async {
await AppWindowCapabilityHost.instance.stop();
messenger.setMockMethodCallHandler(multiWindowChannel, null);
messenger.setMockMethodCallHandler(windowChannels, null);
});
test('create-task window stays hidden until child bootstrap is ready', () async {
final calls = <MethodCall>[];
messenger.setMockMethodCallHandler(multiWindowChannel, (call) async {
calls.add(call);
if (call.method == 'createWindow') return 'create-window-id';
return null;
});
messenger.setMockMethodCallHandler(windowChannels, (call) async {
calls.add(call);
return null;
});
final opened = await AppWindowLauncher.openCreateTaskWindow(
createTask: CreateTask(req: Request(url: 'https://example.com/file.zip')),
);
expect(opened, isTrue);
final createCall = calls.firstWhere((call) => call.method == 'createWindow');
final configuration = Map<String, dynamic>.from(createCall.arguments as Map);
expect(configuration['hiddenAtLaunch'], isTrue);
expect(
calls.where((call) => call.method == 'window_show' && (call.arguments as Map)['windowId'] == 'create-window-id'),
isEmpty,
);
});
test('create-task window failure reports fallback availability', () async {
messenger.setMockMethodCallHandler(multiWindowChannel, (call) async {
if (call.method == 'createWindow') {
throw PlatformException(code: 'create_failed');
}
return null;
});
expect(await AppWindowLauncher.openCreateTaskWindow(), isFalse);
});
}
@@ -0,0 +1,55 @@
import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
import 'package:gopeed/core/window/app_window_bootstrap.dart';
import 'package:gopeed/core/window/app_window_payload.dart';
import 'package:gopeed/l10n/l10n.dart';
void main() {
test('create-task child window has a localized native title', () {
expect(
AppWindowBootstrap.subWindowTitle(AppWindowType.createTask, appLocalizationsFor('en')),
'Create Task - Gopeed',
);
expect(AppWindowBootstrap.subWindowTitle(AppWindowType.createTask, appLocalizationsFor('zh')), '创建任务 - Gopeed');
});
test('create-task payload only carries initial task data', () {
final raw = AppWindowPayload.createTask(
createTask: {
'urls': ['https://example.com/file.zip'],
},
).toRaw();
final decoded = jsonDecode(raw) as Map<String, dynamic>;
expect(decoded.keys, containsAll(<String>['type', 'createTask']));
expect(decoded.keys, hasLength(2));
expect(decoded, isNot(contains('apiToken')));
expect(decoded, isNot(contains('theme')));
expect(decoded, isNot(contains('createHistory')));
});
test('create-task payload preserves nested browser request parameters', () {
final payload = AppWindowPayload.createTask(
createTask: {
'req': {
'rawUrl': 'https://page.example/download',
'url': 'https://cdn.example/archive.zip',
'extra': {
'method': 'GET',
'header': {'Cookie': 'session=abc', 'Referer': 'https://page.example/', 'Authorization': 'Bearer token'},
'body': '',
},
'labels': {'source': 'browser-extension'},
'skipVerifyCert': true,
},
'opts': {'name': 'archive.zip', 'path': 'D:/Downloads', 'selectFiles': <int>[], 'extra': null},
},
);
final decoded = AppWindowPayload.fromRaw(payload.toRaw()).createTask;
expect(decoded?['req'], payload.createTask?['req']);
expect(decoded?['opts'], payload.createTask?['opts']);
});
}
@@ -0,0 +1,100 @@
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:gopeed/features/auth/presentation/pages/login_page.dart';
import 'package:gopeed/l10n/app_localizations.dart';
import 'package:gopeed/shared/theme/app_component_themes.dart';
import 'package:gopeed/shared/theme/app_theme.dart';
import 'package:gopeed/shared/widgets/app_loading_button.dart';
import 'package:shadcn_flutter/shadcn_flutter.dart' as shad;
void main() {
Widget buildApp() {
return ProviderScope(
child: shad.ShadcnApp(
theme: AppTheme.light(),
materialTheme: AppTheme.materialLight(),
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: const AppComponentThemes(child: LoginPage()),
),
);
}
Future<void> setViewport(WidgetTester tester, Size size) async {
tester.view.physicalSize = size;
tester.view.devicePixelRatio = 1;
addTearDown(() {
tester.view.resetPhysicalSize();
tester.view.resetDevicePixelRatio();
});
await tester.pumpWidget(buildApp());
await tester.pumpAndSettle();
}
testWidgets('uses a compact responsive card on mobile', (tester) async {
await setViewport(tester, const Size(390, 844));
expect(find.byKey(const ValueKey('login-compact-card')), findsOneWidget);
expect(find.byKey(const ValueKey('login-desktop-card')), findsNothing);
expect(find.byType(SingleChildScrollView), findsNothing);
expect(find.byType(FittedBox), findsOneWidget);
expect(tester.takeException(), isNull);
});
testWidgets('uses a split card on desktop', (tester) async {
await setViewport(tester, const Size(1200, 800));
expect(find.byKey(const ValueKey('login-desktop-card')), findsOneWidget);
expect(find.byKey(const ValueKey('login-compact-card')), findsNothing);
expect(find.byType(SingleChildScrollView), findsNothing);
expect(find.byType(FittedBox), findsOneWidget);
expect(tester.takeException(), isNull);
});
testWidgets('fits a short narrow viewport without overflow or scrolling', (tester) async {
await setViewport(tester, const Size(320, 480));
expect(find.byType(SingleChildScrollView), findsNothing);
expect(find.byKey(const ValueKey('login-compact-card')), findsOneWidget);
expect(tester.takeException(), isNull);
});
testWidgets('exposes browser-compatible username and password autofill fields', (tester) async {
await setViewport(tester, const Size(390, 844));
final username = tester.widget<shad.TextField>(find.byKey(const ValueKey('login-username-field')));
final password = tester.widget<shad.TextField>(find.byKey(const ValueKey('login-password-field')));
final autofillGroup = tester.widget<AutofillGroup>(find.byType(AutofillGroup));
expect(autofillGroup.onDisposeAction, AutofillContextAction.cancel);
expect(username.autofillHints, contains(AutofillHints.username));
expect(username.autofocus, isTrue);
expect(username.textInputAction, TextInputAction.done);
expect(password.autofillHints, contains(AutofillHints.password));
expect(password.textInputAction, TextInputAction.done);
expect(password.obscureText, isTrue);
expect(password.features.whereType<shad.InputPasswordToggleFeature>(), hasLength(1));
});
testWidgets('uses a compact centered neutral login action', (tester) async {
await setViewport(tester, const Size(1200, 800));
final buttonContainer = find.byKey(const ValueKey('login-submit-button-container'));
final button = tester.widget<AppLoadingButton>(find.byKey(const ValueKey('login-submit-button')));
expect(tester.getSize(buttonContainer), const Size(148, 40));
expect(button.alignment, Alignment.center);
expect(button.variant, AppLoadingButtonVariant.primary);
});
testWidgets('validates required credentials before submitting', (tester) async {
await setViewport(tester, const Size(390, 844));
await tester.tap(find.byKey(const ValueKey('login-submit-button')));
await tester.pump();
expect(find.text('Please enter your username'), findsOneWidget);
expect(find.text('Please enter your password'), findsOneWidget);
});
}
@@ -0,0 +1,95 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:gopeed/api/model/extension.dart';
import 'package:gopeed/api/model/store_extension.dart';
import 'package:gopeed/features/extensions/application/extensions_controller.dart';
import 'package:gopeed/features/extensions/presentation/widgets/extension_icon.dart';
import 'package:path/path.dart' as path;
void main() {
test('installed extension uses its local icon instead of the store icon', () {
final item = ExtensionListItem(installed: _installed(), store: _store());
final source = resolveExtensionIconSource(item, web: false, storageDirectory: '/app-data');
expect(source.kind, ExtensionIconSourceKind.file);
expect(source.location, path.join('/app-data', 'extensions', 'gopeed@test', 'images', 'icon.png'));
});
test('development extension uses its development directory', () {
final item = ExtensionListItem(
installed: _installed(devMode: true, devPath: '/extension-source'),
store: _store(),
);
final source = resolveExtensionIconSource(item, web: false, storageDirectory: '/app-data');
expect(source.kind, ExtensionIconSourceKind.file);
expect(source.location, path.join('/extension-source', 'images', 'icon.png'));
});
test('web uses the local Gopeed extension file endpoint', () {
final item = ExtensionListItem(installed: _installed(), store: _store());
final source = resolveExtensionIconSource(item, web: true);
expect(source.kind, ExtensionIconSourceKind.network);
expect(source.location, '/fs/extensions/gopeed@test/images/icon.png');
});
test('uninstalled market extension keeps using its remote icon', () {
final source = resolveExtensionIconSource(ExtensionListItem(store: _store()), web: false);
expect(source.kind, ExtensionIconSourceKind.network);
expect(source.location, 'https://cdn.example.com/icon.png');
});
test('installed extension without an icon uses the bundled fallback', () {
final source = resolveExtensionIconSource(
ExtensionListItem(
installed: _installed(icon: ''),
store: _store(),
),
web: false,
storageDirectory: '/app-data',
);
expect(source.kind, ExtensionIconSourceKind.asset);
expect(source.location, 'assets/extension/default_icon.png');
});
}
Extension _installed({String icon = 'images/icon.png', bool devMode = false, String devPath = ''}) {
return Extension(
identity: 'gopeed@test',
name: 'test',
author: 'gopeed',
title: 'Test',
description: 'Test extension',
icon: icon,
version: '1.0.0',
homepage: '',
repository: Repository(url: 'https://github.com/GopeedLab/test', directory: ''),
disabled: false,
devMode: devMode,
devPath: devPath,
);
}
StoreExtension _store() {
return StoreExtension(
id: 'gopeed@test',
repoFullName: 'GopeedLab/test',
repoUrl: 'https://github.com/GopeedLab/test',
name: 'test',
author: 'gopeed',
title: 'Test',
description: 'Test extension',
icon: 'https://cdn.example.com/icon.png',
version: '1.0.0',
homepage: null,
readme: null,
installCount: 1,
stars: 1,
topics: const [],
);
}
@@ -0,0 +1,48 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:gopeed/api/model/downloader_config.dart';
import 'package:gopeed/app/application/app_runtime_controller.dart';
import 'package:gopeed/core/capabilities/app_capabilities.dart';
import 'package:gopeed/core/capabilities/capability_rpc.dart';
import 'package:gopeed/core/capabilities/gopeed_capability.dart';
import 'package:gopeed/core/common/start_config.dart';
import 'package:gopeed/features/settings/application/settings_controller.dart';
void main() {
test('settings reload backend config after the page releases its provider', () async {
var backendDirectory = 'D:/Initial';
var getConfigCalls = 0;
final registry = CapabilityRegistry(createAppCapabilityCodecs())
..bind(GopeedMethods.getConfig, (_) {
getConfigCalls++;
return DownloaderConfig(downloadDir: backendDirectory);
});
final container = ProviderContainer(
overrides: [
appCapabilitiesProvider.overrideWithValue(AppCapabilities(LocalCapabilityInvoker(registry))),
appRuntimeControllerProvider.overrideWith(_TestRuntimeController.new),
],
);
addTearDown(container.dispose);
final firstListener = container.listen(settingsControllerProvider, (_, _) {}, fireImmediately: true);
expect((await container.read(settingsControllerProvider.future)).config.downloadDir, 'D:/Initial');
firstListener.close();
await container.pump();
backendDirectory = 'E:/Created task';
final secondListener = container.listen(settingsControllerProvider, (_, _) {}, fireImmediately: true);
addTearDown(secondListener.close);
expect((await container.read(settingsControllerProvider.future)).config.downloadDir, 'E:/Created task');
expect(getConfigCalls, 2);
});
}
class _TestRuntimeController extends AppRuntimeController {
@override
Future<AppRuntimeState> build() async => AppRuntimeState(
startConfig: StartConfig(),
runningPort: 0,
downloaderConfig: DownloaderConfig(downloadDir: 'C:/Stale runtime snapshot'),
);
}
@@ -0,0 +1,358 @@
import 'package:flutter/widgets.dart';
import 'package:flutter/widgets.dart' as flutter show Row;
import 'package:flutter/material.dart' show Icons;
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:go_router/go_router.dart';
import 'package:gopeed/api/model/create_task.dart';
import 'package:gopeed/api/model/downloader_config.dart';
import 'package:gopeed/api/model/options.dart';
import 'package:gopeed/api/model/request.dart';
import 'package:gopeed/core/capabilities/app_capabilities.dart';
import 'package:gopeed/core/capabilities/capability_rpc.dart';
import 'package:gopeed/core/capabilities/gopeed_capability.dart';
import 'package:gopeed/core/capabilities/storage_capability.dart';
import 'package:gopeed/features/tasks/presentation/pages/create_task_window_page.dart';
import 'package:gopeed/shared/services/download_directory_picker.dart';
import 'package:gopeed/shared/theme/app_component_themes.dart';
import 'package:gopeed/shared/theme/app_design_tokens.dart';
import 'package:gopeed/shared/theme/app_theme.dart';
import 'package:gopeed/shared/widgets/app_tooltip.dart';
import 'package:shadcn_flutter/shadcn_flutter.dart' as shad;
void main() {
testWidgets('browser extension request parameters populate the form and survive submission', (
WidgetTester tester,
) async {
tester.view.physicalSize = const Size(1024, 720);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
DownloadDirectoryPicker.debugPlatformOverride = TargetPlatform.android;
final androidLocations = <String, String>{'application': 'D:/Downloads', 'downloads': 'G:/Manually selected'};
DownloadDirectoryPicker.debugAndroidLocationsLoader = () async => androidLocations;
DownloadDirectoryPicker.debugDownloadsPreparer = (path) async => path;
addTearDown(() {
DownloadDirectoryPicker.debugPlatformOverride = null;
DownloadDirectoryPicker.debugAndroidLocationsLoader = null;
DownloadDirectoryPicker.debugDownloadsPreparer = null;
});
CreateTask? submitted;
final config = DownloaderConfig(downloadDir: 'C:/Downloads')
..extra.defaultDirectDownload = true
..extra.downloadCategories = [
DownloadCategory(name: 'Archives', path: 'E:/Archives/%year%'),
DownloadCategory(name: 'Archives', path: 'F:/Archives'),
DownloadCategory(name: 'Long video category', path: 'G:/Videos'),
DownloadCategory(name: 'Long document category', path: 'H:/Documents'),
]
..protocolConfig.http.connections = 8;
final registry = CapabilityRegistry(createAppCapabilityCodecs())
..bind(GopeedMethods.getConfig, (_) => config)
..bind(GopeedMethods.createTask, (task) {
submitted = task;
return 'created-task';
})
..bind(StorageMethods.saveCreateHistory, (_) => const RpcUnit());
final capabilities = AppCapabilities(LocalCapabilityInvoker(registry));
final initialTask = CreateTask(
req: Request(
rawUrl: 'https://page.example/download',
url: 'https://cdn.example/archive.zip',
extra: ReqExtraHttp(
method: 'POST',
header: const {
'User-Agent': 'Browser UA',
'Cookie': 'session=abc',
'Referer': 'https://page.example/',
'Authorization': 'Bearer token',
},
body: 'request-body',
).toJson(),
labels: const {'source': 'browser-extension'},
proxy: RequestProxy(
mode: RequestProxyMode.custom,
scheme: 'socks5',
host: '127.0.0.1:7890',
usr: 'proxy-user',
pwd: 'proxy-password',
),
skipVerifyCert: true,
),
opts: Options(
name: 'archive.zip',
path: 'D:/Downloads',
extra: OptsExtraHttp(
connections: 12,
autoTorrent: true,
deleteTorrentAfterDownload: true,
autoExtract: true,
archivePassword: 'archive-password',
deleteAfterExtract: true,
).toJson(),
),
);
final router = GoRouter(
initialLocation: '/create',
routes: [
GoRoute(path: '/', builder: (_, _) => const SizedBox()),
GoRoute(
path: '/create',
builder: (_, _) => CreateTaskWindowPage(initialTask: initialTask),
),
],
);
addTearDown(router.dispose);
await tester.pumpWidget(
ProviderScope(
overrides: [appCapabilitiesProvider.overrideWithValue(capabilities)],
child: shad.ShadcnApp.router(
theme: AppTheme.light(),
materialTheme: AppTheme.materialLight(),
builder: (context, child) => AppComponentThemes(child: child ?? const SizedBox.shrink()),
routerConfig: router,
),
),
);
await tester.pumpAndSettle();
expect(_fieldText(tester, 'create-task-http-header-name-0'), 'User-Agent');
expect(_fieldText(tester, 'create-task-http-header-value-0'), 'Browser UA');
expect(_fieldText(tester, 'create-task-http-header-name-3'), 'Authorization');
expect(_fieldText(tester, 'create-task-http-header-value-3'), 'Bearer token');
expect(_fieldText(tester, 'create-task-proxy-server'), '127.0.0.1');
expect(_fieldText(tester, 'create-task-proxy-port'), '7890');
expect(_fieldText(tester, 'create-task-proxy-username'), 'proxy-user');
expect(_fieldText(tester, 'create-task-proxy-password'), 'proxy-password');
expect(_fieldText(tester, 'create-task-archive-password'), 'archive-password');
expect(find.byKey(const ValueKey('create-task-skip-verify-cert')), findsOneWidget);
expect(find.byKey(const ValueKey('create-task-auto-torrent')), findsOneWidget);
expect(find.byKey(const ValueKey('create-task-delete-torrent')), findsOneWidget);
expect(find.byKey(const ValueKey('create-task-auto-extract')), findsOneWidget);
expect(find.byKey(const ValueKey('create-task-delete-after-extract')), findsOneWidget);
expect(find.text('Archives'), findsNWidgets(2));
expect(find.text('Quick folders'), findsNothing);
expect(find.byKey(const ValueKey('create-task-category-0')), findsOneWidget);
expect(find.byKey(const ValueKey('create-task-category-1')), findsOneWidget);
expect(find.byKey(const ValueKey('create-task-category-2')), findsOneWidget);
expect(find.byKey(const ValueKey('create-task-category-3')), findsOneWidget);
final shortcutRow = find.byKey(const ValueKey('create-task-directory-shortcuts'));
expect(tester.getSize(shortcutRow).height, 28);
final rememberDirectory = find.byKey(const ValueKey('create-task-remember-download-directory-checkbox'));
final directDownloadCheckbox = find.byKey(const ValueKey('create-task-direct-download-checkbox'));
final rememberDirectoryRow = find.byKey(const ValueKey('create-task-remember-download-directory'));
final directoryComponent = find.byKey(const ValueKey('create-task-directory-component'));
final directoryOptionsRow = find.byKey(const ValueKey('create-task-directory-options-row'));
final directoryOptionsLayout = find.byKey(const ValueKey('create-task-directory-options-layout'));
final directoryPicker = find.byKey(const ValueKey('create-task-directory-picker'));
expect(tester.widget<shad.Checkbox>(rememberDirectory).state, shad.CheckboxState.unchecked);
expect(tester.widget<shad.Checkbox>(rememberDirectory).size, isNull);
expect(tester.getSize(rememberDirectory), const Size.square(AppDesignTokens.checkboxSize));
expect(tester.getCenter(rememberDirectory).dx, closeTo(tester.getCenter(directDownloadCheckbox).dx, 0.5));
final rememberDirectoryLabel = tester.widget<Text>(
find.byKey(const ValueKey('create-task-remember-download-directory-label')),
);
final directDownloadLabel = tester.widget<Text>(find.byKey(const ValueKey('create-task-direct-download-label')));
expect(rememberDirectoryLabel.style, directDownloadLabel.style);
expect(rememberDirectoryLabel.maxLines, directDownloadLabel.maxLines);
expect(rememberDirectoryLabel.overflow, directDownloadLabel.overflow);
expect(tester.widget<shad.IconButton>(directoryPicker).variance, same(shad.ButtonVariance.outline));
expect(tester.widget<flutter.Row>(directoryOptionsLayout).mainAxisAlignment, MainAxisAlignment.spaceBetween);
expect(tester.getCenter(rememberDirectoryRow).dy, closeTo(tester.getCenter(shortcutRow).dy, 0.5));
expect(tester.getTopRight(directoryOptionsRow).dx, closeTo(tester.getTopRight(directoryComponent).dx, 0.5));
expect(
tester.getTopRight(find.byKey(const ValueKey('create-task-category-3'))).dx,
closeTo(tester.getTopRight(directoryComponent).dx, 0.5),
);
tester.view.physicalSize = const Size(520, 720);
await tester.pumpAndSettle();
final shortcutContent = find.byKey(const ValueKey('create-task-directory-shortcuts-content'));
expect(tester.getTopLeft(shortcutRow).dy, greaterThan(tester.getBottomLeft(rememberDirectoryRow).dy));
expect(tester.getSize(shortcutRow).width, closeTo(tester.getSize(directoryComponent).width, 0.5));
expect(tester.getSize(shortcutContent).width, greaterThan(tester.getSize(shortcutRow).width));
final shortcutScrollable = find.descendant(of: shortcutRow, matching: find.byType(Scrollable));
expect(tester.state<ScrollableState>(shortcutScrollable).position.maxScrollExtent, greaterThan(0));
tester.view.physicalSize = const Size(719, 720);
await tester.pumpAndSettle();
expect(
tester.widget<shad.Column>(find.byKey(const ValueKey('create-task-directory-options-layout'))),
isA<shad.Column>(),
);
tester.view.physicalSize = const Size(720, 720);
await tester.pumpAndSettle();
expect(
tester.widget<flutter.Row>(find.byKey(const ValueKey('create-task-directory-options-layout'))).mainAxisAlignment,
MainAxisAlignment.spaceBetween,
);
tester.view.physicalSize = const Size(1024, 720);
await tester.pumpAndSettle();
await tester.tap(directoryPicker);
await tester.pumpAndSettle();
await tester.tap(find.byKey(const ValueKey('android-app-directory-option')));
await tester.pumpAndSettle();
expect(tester.widget<shad.Checkbox>(rememberDirectory).state, shad.CheckboxState.unchecked);
await tester.tap(directoryPicker);
await tester.pumpAndSettle();
await tester.tap(find.byKey(const ValueKey('android-downloads-directory-option')));
await tester.pumpAndSettle();
expect(tester.widget<shad.Checkbox>(rememberDirectory).state, shad.CheckboxState.checked);
expect(tester.takeException(), isNull);
await tester.tap(find.byKey(const ValueKey('create-task-category-3')));
await tester.pump();
expect(tester.widget<shad.Checkbox>(rememberDirectory).state, shad.CheckboxState.unchecked);
expect(
find.descendant(
of: find.byKey(const ValueKey('create-task-category-3')),
matching: find.byIcon(Icons.folder_outlined),
),
findsOneWidget,
);
androidLocations['downloads'] = 'C:/Downloads';
await tester.tap(directoryPicker);
await tester.pumpAndSettle();
await tester.tap(find.byKey(const ValueKey('android-downloads-directory-option')));
await tester.pumpAndSettle();
expect(tester.widget<shad.Checkbox>(rememberDirectory).state, shad.CheckboxState.unchecked);
androidLocations['downloads'] = 'G:/Manually selected';
await tester.tap(directoryPicker);
await tester.pumpAndSettle();
await tester.tap(find.byKey(const ValueKey('android-downloads-directory-option')));
await tester.pumpAndSettle();
expect(tester.widget<shad.Checkbox>(rememberDirectory).state, shad.CheckboxState.checked);
await tester.tap(find.text('Confirm'));
await tester.pumpAndSettle();
final request = submitted?.req;
expect(request, isNotNull);
expect(request?.rawUrl, initialTask.req?.rawUrl);
expect(request?.labels, initialTask.req?.labels);
expect(request?.proxy?.mode, RequestProxyMode.custom);
expect(request?.proxy?.scheme, 'socks5');
expect(request?.proxy?.host, '127.0.0.1:7890');
expect(request?.proxy?.usr, 'proxy-user');
expect(request?.proxy?.pwd, 'proxy-password');
expect(request?.skipVerifyCert, isTrue);
expect(ReqExtraHttp.fromJson(request?.extra! as Map<String, dynamic>).toJson(), initialTask.req?.extra);
expect(submitted?.opts?.path, 'G:/Manually selected');
final options = OptsExtraHttp.fromJson(submitted?.opts?.extra! as Map<String, dynamic>);
expect(options.connections, 12);
expect(options.autoTorrent, isTrue);
expect(options.deleteTorrentAfterDownload, isTrue);
expect(options.autoExtract, isTrue);
expect(options.archivePassword, 'archive-password');
expect(options.deleteAfterExtract, isTrue);
expect(submitted?.opts?.asDefaultPath, isTrue);
});
testWidgets('create history supports filtering, deleting one entry, and clearing all entries', (
WidgetTester tester,
) async {
tester.view.physicalSize = const Size(1024, 720);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
final histories = <String>[
'https://example.com/alpha.zip',
'https://example.com/beta.iso',
'magnet:?xt=urn:btih:gamma',
];
String? removedHistory;
var cleared = false;
final registry = CapabilityRegistry(createAppCapabilityCodecs())
..bind(GopeedMethods.getConfig, (_) => DownloaderConfig(downloadDir: '/downloads'))
..bind(StorageMethods.getCreateHistory, (_) => List<String>.unmodifiable(histories))
..bind(StorageMethods.removeCreateHistory, (value) {
removedHistory = value;
histories.remove(value);
return const RpcUnit();
})
..bind(StorageMethods.clearCreateHistory, (_) {
cleared = true;
histories.clear();
return const RpcUnit();
});
final capabilities = AppCapabilities(LocalCapabilityInvoker(registry));
await tester.pumpWidget(
ProviderScope(
overrides: [appCapabilitiesProvider.overrideWithValue(capabilities)],
child: shad.ShadcnApp(
theme: AppTheme.light(),
materialTheme: AppTheme.materialLight(),
home: AppComponentThemes(child: const CreateTaskWindowPage()),
),
),
);
await tester.pumpAndSettle();
await tester.tap(find.byIcon(Icons.history));
await tester.pumpAndSettle();
expect(
tester.getSize(find.byKey(const ValueKey('create-history-title-bar'))).width,
tester.getSize(find.byKey(const ValueKey('create-history-content'))).width,
);
final alphaItem = find.byKey(const ValueKey('create-history-item-https://example.com/alpha.zip'));
final betaItem = find.byKey(const ValueKey('create-history-item-https://example.com/beta.iso'));
final gammaItem = find.byKey(const ValueKey('create-history-item-magnet:?xt=urn:btih:gamma'));
expect(alphaItem, findsOneWidget);
expect(betaItem, findsOneWidget);
expect(gammaItem, findsOneWidget);
final clearAction = find.byKey(const ValueKey('create-history-clear'));
final closeAction = find.byKey(const ValueKey('create-history-close'));
expect(
tester.widget<AppTooltip>(find.ancestor(of: clearAction, matching: find.byType(AppTooltip))).message,
'Clear History',
);
expect(
tester.widget<AppTooltip>(find.ancestor(of: closeAction, matching: find.byType(AppTooltip))).message,
'Close',
);
final historyText = tester.widget<Text>(find.descendant(of: alphaItem, matching: find.byType(Text)));
expect(historyText.data, contains('\u200B'));
expect(historyText.semanticsLabel, 'https://example.com/alpha.zip');
final filter = find.byKey(const ValueKey('create-history-filter'));
await tester.enterText(filter, 'beta');
await tester.pump();
expect(alphaItem, findsNothing);
expect(betaItem, findsOneWidget);
expect(gammaItem, findsNothing);
await tester.tap(find.byKey(const ValueKey('create-history-delete-https://example.com/beta.iso')));
await tester.pumpAndSettle();
expect(removedHistory, 'https://example.com/beta.iso');
expect(find.text('No History Found'), findsOneWidget);
await tester.enterText(filter, '');
await tester.pump();
expect(alphaItem, findsOneWidget);
expect(gammaItem, findsOneWidget);
await tester.tap(find.byKey(const ValueKey('create-history-clear')));
await tester.pumpAndSettle();
expect(cleared, isTrue);
expect(find.text('No history'), findsOneWidget);
expect(find.byKey(const ValueKey('create-history-clear')), findsOneWidget);
expect(find.byKey(const ValueKey('create-history-close')), findsOneWidget);
});
}
String _fieldText(WidgetTester tester, String key) {
final editable = find.descendant(of: find.byKey(ValueKey(key)), matching: find.byType(EditableText));
return tester.widget<EditableText>(editable).controller.text;
}
@@ -0,0 +1,47 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:gopeed/features/tasks/domain/task_record.dart';
import 'package:gopeed/features/tasks/presentation/task_record_localizations.dart';
import 'package:gopeed/l10n/app_localizations_en.dart';
void main() {
test('remaining time and download duration share unit thresholds and rounding', () {
final l10n = AppLocalizationsEn();
final cases = <(int, String, String)>[
(59, '59 seconds remaining', '59 seconds'),
(60, '1 minute remaining', '1 minute'),
(61, '2 minutes remaining', '2 minutes'),
(3599, '60 minutes remaining', '60 minutes'),
(3600, '1 hour remaining', '1 hour'),
(3723, '2 hours remaining', '2 hours'),
];
for (final (seconds, remaining, duration) in cases) {
final runningTask = TaskRecord(
id: 'running-$seconds',
name: 'archive.zip',
status: TaskStatus.downloading,
downloaded: '1 MB',
url: 'https://example.com/archive.zip',
storagePath: '/downloads/archive.zip',
files: const [],
uploading: false,
remainingSeconds: seconds,
);
final completedTask = TaskRecord(
id: 'completed-$seconds',
name: 'archive.zip',
status: TaskStatus.completed,
downloaded: '1 MB',
url: 'https://example.com/archive.zip',
storagePath: '/downloads/archive.zip',
files: const [],
uploading: false,
downloadDuration: Duration(seconds: seconds),
);
expect(runningTask.localizedRemaining(l10n), remaining);
expect(completedTask.localizedDownloadDuration(l10n), duration);
expect(formatTaskDuration(l10n, Duration(seconds: seconds)), duration);
}
});
}
+16
View File
@@ -0,0 +1,16 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:gopeed/util/package_info.dart';
void main() {
group('normalizeAppVersion', () {
test('treats a four-part platform version as a beta version', () {
expect(normalizeAppVersion('2.0.0.1'), '2.0.0-beta.1');
expect(normalizeAppVersion('2.0.0.12'), '2.0.0-beta.12');
});
test('keeps stable and semantic prerelease versions unchanged', () {
expect(normalizeAppVersion('2.0.0'), '2.0.0');
expect(normalizeAppVersion('2.0.0-beta.1'), '2.0.0-beta.1');
});
});
}
@@ -0,0 +1,96 @@
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:gopeed/shared/theme/app_component_themes.dart';
import 'package:gopeed/shared/theme/app_design_tokens.dart';
import 'package:gopeed/shared/theme/app_palette.dart';
import 'package:gopeed/shared/theme/app_theme.dart';
import 'package:shadcn_flutter/shadcn_flutter.dart' as shad;
void main() {
testWidgets('provides the standard checkbox metrics', (tester) async {
late shad.CheckboxTheme checkboxTheme;
await tester.pumpWidget(
shad.ShadcnApp(
theme: AppTheme.light(),
materialTheme: AppTheme.materialLight(),
home: AppComponentThemes(
child: Builder(
builder: (context) {
checkboxTheme = shad.ComponentTheme.of<shad.CheckboxTheme>(context);
return const SizedBox();
},
),
),
),
);
expect(checkboxTheme.size, AppDesignTokens.checkboxSize);
expect(checkboxTheme.gap, AppDesignTokens.checkboxLabelGap);
});
testWidgets('uses a high-contrast checkbox border in the dark theme', (tester) async {
late shad.CheckboxTheme checkboxTheme;
await tester.pumpWidget(
shad.ShadcnApp(
theme: AppTheme.dark(),
materialTheme: AppTheme.materialDark(),
home: AppComponentThemes(
child: Builder(
builder: (context) {
checkboxTheme = shad.ComponentTheme.of<shad.CheckboxTheme>(context);
return const SizedBox();
},
),
),
),
);
expect(checkboxTheme.borderColor, AppPalette.dark.textMuted);
expect(_contrastRatio(checkboxTheme.borderColor!, AppPalette.dark.bg), greaterThanOrEqualTo(3));
});
testWidgets('uses distinct borderless secondary button fills in the light theme', (tester) async {
late shad.SecondaryButtonTheme buttonTheme;
late BuildContext themedContext;
await tester.pumpWidget(
shad.ShadcnApp(
theme: AppTheme.light(),
materialTheme: AppTheme.materialLight(),
home: AppComponentThemes(
child: Builder(
builder: (context) {
themedContext = context;
buttonTheme = shad.ComponentTheme.of<shad.SecondaryButtonTheme>(context);
return const SizedBox();
},
),
),
),
);
final decoration =
buttonTheme.decoration!(themedContext, const <WidgetState>{}, const BoxDecoration()) as BoxDecoration;
final hoveredDecoration =
buttonTheme.decoration!(themedContext, const <WidgetState>{WidgetState.hovered}, const BoxDecoration())
as BoxDecoration;
final disabledDecoration =
buttonTheme.decoration!(themedContext, const <WidgetState>{WidgetState.disabled}, const BoxDecoration())
as BoxDecoration;
expect(decoration.border, isNull);
expect(hoveredDecoration.border, isNull);
expect(disabledDecoration.border, isNull);
expect(decoration.color, isNot(AppPalette.light.surfaceSoft));
expect(hoveredDecoration.color, isNot(decoration.color));
});
}
double _contrastRatio(Color first, Color second) {
final firstLuminance = first.computeLuminance();
final secondLuminance = second.computeLuminance();
final lighter = firstLuminance > secondLuminance ? firstLuminance : secondLuminance;
final darker = firstLuminance > secondLuminance ? secondLuminance : firstLuminance;
return (lighter + 0.05) / (darker + 0.05);
}
@@ -0,0 +1,127 @@
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:gopeed/shared/theme/app_component_themes.dart';
import 'package:gopeed/shared/theme/app_palette.dart';
import 'package:gopeed/shared/theme/app_theme.dart';
import 'package:gopeed/shared/widgets/app_loading_button.dart';
import 'package:shadcn_flutter/shadcn_flutter.dart' as shad;
void main() {
testWidgets('loading buttons replace only the icon and preserve their color family', (tester) async {
await tester.pumpWidget(
shad.ShadcnApp(
theme: AppTheme.dark(),
materialTheme: AppTheme.materialDark(),
home: AppComponentThemes(
child: Column(
children: [
AppLoadingButton(
key: const ValueKey('secondary-loading-button'),
onPressed: () {},
loading: true,
icon: const Icon(shad.LucideIcons.refreshCw),
child: const Text('Check for Updates'),
),
AppLoadingButton(
key: const ValueKey('brand-loading-button'),
onPressed: () {},
loading: true,
variant: AppLoadingButtonVariant.brand,
icon: const Icon(shad.LucideIcons.download),
child: const Text('Update'),
),
AppLoadingButton(
key: const ValueKey('primary-loading-button'),
onPressed: () {},
loading: true,
variant: AppLoadingButtonVariant.primary,
icon: const Icon(shad.LucideIcons.save),
child: const Text('Save'),
),
],
),
),
),
);
await tester.pump();
final secondary = find.byKey(const ValueKey('secondary-loading-button'));
final brand = find.byKey(const ValueKey('brand-loading-button'));
final primary = find.byKey(const ValueKey('primary-loading-button'));
expect(find.descendant(of: secondary, matching: find.text('Check for Updates')), findsOneWidget);
expect(find.descendant(of: brand, matching: find.text('Update')), findsOneWidget);
expect(find.descendant(of: primary, matching: find.text('Save')), findsOneWidget);
expect(find.descendant(of: secondary, matching: find.byIcon(shad.LucideIcons.refreshCw)), findsNothing);
expect(find.descendant(of: brand, matching: find.byIcon(shad.LucideIcons.download)), findsNothing);
expect(find.descendant(of: primary, matching: find.byIcon(shad.LucideIcons.save)), findsNothing);
final secondaryProgress = tester.widget<shad.CircularProgressIndicator>(
find.descendant(of: secondary, matching: find.byType(shad.CircularProgressIndicator)),
);
final brandProgress = tester.widget<shad.CircularProgressIndicator>(
find.descendant(of: brand, matching: find.byType(shad.CircularProgressIndicator)),
);
final primaryProgress = tester.widget<shad.CircularProgressIndicator>(
find.descendant(of: primary, matching: find.byType(shad.CircularProgressIndicator)),
);
expect(
tester.widget<shad.Clickable>(find.descendant(of: primary, matching: find.byType(shad.Clickable))).enabled,
isFalse,
);
expect(secondaryProgress.color, AppPalette.dark.textMuted);
expect(secondaryProgress.color, isNot(AppPalette.dark.brand));
expect(brandProgress.color, AppPalette.dark.brandForeground);
expect(primaryProgress.color, AppPalette.dark.primaryActionForeground);
final secondaryDecoration =
tester
.widget<shad.Clickable>(find.descendant(of: secondary, matching: find.byType(shad.Clickable)))
.decoration!
.resolve({WidgetState.disabled})
as BoxDecoration;
final brandDecoration =
tester
.widget<shad.Clickable>(find.descendant(of: brand, matching: find.byType(shad.Clickable)))
.decoration!
.resolve({WidgetState.disabled})
as BoxDecoration;
expect(secondaryDecoration.color, AppPalette.dark.surfaceSoft);
expect(brandDecoration.color, AppPalette.dark.brand);
});
testWidgets('text-only loading buttons replace their label with a centered loader', (tester) async {
await tester.pumpWidget(
shad.ShadcnApp(
theme: AppTheme.dark(),
materialTheme: AppTheme.materialDark(),
home: AppComponentThemes(
child: Center(
child: SizedBox(
key: const ValueKey('text-only-loading-bounds'),
width: 148,
height: 40,
child: AppLoadingButton(
key: const ValueKey('text-only-loading-button'),
onPressed: () {},
loading: true,
alignment: Alignment.center,
variant: AppLoadingButtonVariant.primary,
child: const Text('Login'),
),
),
),
),
),
);
await tester.pump();
final bounds = tester.getRect(find.byKey(const ValueKey('text-only-loading-bounds')));
final loader = find.descendant(
of: find.byKey(const ValueKey('text-only-loading-button')),
matching: find.byType(shad.CircularProgressIndicator),
);
expect(find.text('Login'), findsNothing);
expect(loader, findsOneWidget);
expect(tester.getRect(loader).center, bounds.center);
});
}
@@ -0,0 +1,43 @@
import 'dart:io';
import 'package:flutter/material.dart' show MaterialApp, Tooltip;
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:gopeed/shared/widgets/app_tooltip.dart';
void main() {
testWidgets('AppTooltip delegates product tooltips to Flutter Tooltip', (tester) async {
await tester.pumpWidget(
const MaterialApp(
home: AppTooltip(message: 'Details', child: SizedBox.square(dimension: 24)),
),
);
expect(tester.widget<Tooltip>(find.byType(Tooltip)).message, 'Details');
});
test('product source does not instantiate Tooltip directly', () {
final violations = <String>[];
final tooltipConstructor = RegExp(r'\b(?:\w+\.)?Tooltip\s*\(');
for (final entity in Directory('lib').listSync(recursive: true)) {
if (entity is! File || !entity.path.endsWith('.dart') || entity.path.endsWith('app_tooltip.dart')) {
continue;
}
final lines = entity.readAsLinesSync();
for (var index = 0; index < lines.length; index++) {
if (tooltipConstructor.hasMatch(lines[index])) {
violations.add('${entity.path}:${index + 1}');
}
}
}
expect(
violations,
isEmpty,
reason:
'Use AppTooltip so product tooltip styling stays centralized. Direct Tooltip usage found at: '
'${violations.join(', ')}',
);
});
}
+202
View File
@@ -0,0 +1,202 @@
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:gopeed/api/model/downloader_config.dart';
import 'package:gopeed/features/settings/presentation/widgets/app_update_dialog.dart';
import 'package:gopeed/shared/theme/app_theme.dart';
import 'package:gopeed/util/arch/arch.dart';
import 'package:gopeed/util/github_mirror.dart';
import 'package:gopeed/util/package_info.dart' as app_package;
import 'package:gopeed/util/updater.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:shadcn_flutter/shadcn_flutter.dart' as shad;
void main() {
TestWidgetsFlutterBinding.ensureInitialized().platformDispatcher.localeTestValue = const Locale('en');
setUpAll(() {
app_package.packageInfo = PackageInfo(
appName: 'Gopeed',
packageName: 'com.gopeed.Gopeed',
version: '1.7.0',
buildNumber: '1',
);
});
group('version comparison', () {
test('uses semantic version precedence', () {
expect(isNewerVersion('1.10.0', '1.9.9'), isTrue);
expect(isNewerVersion('2.0.0-beta.2', '2.0.0-beta.1'), isTrue);
expect(isNewerVersion('2.0.0-rc.1', '2.0.0-beta.2'), isTrue);
expect(isNewerVersion('2.0.0', '2.0.0-rc.1'), isTrue);
expect(isNewerVersion('1.2.3', '1.2.3'), isFalse);
expect(isNewerVersion('1.2.2', '1.2.3'), isFalse);
expect(isNewerVersion('invalid', '1.2.3'), isFalse);
});
});
group('release selection', () {
Map<String, dynamic> release(String version, {bool prerelease = false, bool draft = false}) => {
'tag_name': 'v$version',
'prerelease': prerelease,
'draft': draft,
'body': '$version notes',
'html_url': 'https://example.com/$version',
};
test('stable builds ignore preview releases', () {
final selected = selectUpdateRelease([release('2.1.0-beta.1', prerelease: true), release('2.0.1')], '2.0.0');
expect(selected?.version, '2.0.1');
});
test('preview builds advance within the same preview line', () {
final selected = selectUpdateRelease([
release('2.0.0-beta.2', prerelease: true),
release('1.9.9'),
release('2.1.0-beta.1', prerelease: true),
], '2.0.0-beta.1');
expect(selected?.version, '2.0.0-beta.2');
});
test('four-part platform beta selects the next GitHub prerelease and matching asset', () {
final currentVersion = app_package.normalizeAppVersion('2.0.0.1');
final selected = selectUpdateRelease([release('2.0.0-beta.2', prerelease: true)], currentVersion);
expect(selected?.version, '2.0.0-beta.2');
expect(
updateAssetName(selected!.version, channel: UpdateChannel.macosDmg, architecture: Architecture.arm64),
'Gopeed-v2.0.0-beta.2-macos-arm64.dmg',
);
});
test('preview builds graduate to the final stable release', () {
final selected = selectUpdateRelease([
release('2.0.0-beta.2', prerelease: true),
release('2.0.0'),
], '2.0.0-beta.1');
expect(selected?.version, '2.0.0');
});
test('selects the greatest eligible version and ignores invalid releases', () {
final selected = selectUpdateRelease([
release('2.0.0-beta.3', prerelease: true),
release('2.0.0-beta.4', prerelease: true, draft: true),
{'tag_name': 'not-a-version'},
release('2.0.0-beta.2', prerelease: true),
], '2.0.0-beta.1');
expect(selected?.version, '2.0.0-beta.3');
});
});
group('release assets', () {
test('uses the release naming convention for desktop packages', () {
expect(
updateAssetName('1.8.0', channel: UpdateChannel.windowsPortable, architecture: Architecture.x64),
'Gopeed-v1.8.0-windows-amd64-portable.zip',
);
expect(
updateAssetName('1.8.0', channel: UpdateChannel.macosDmg, architecture: Architecture.arm64),
'Gopeed-v1.8.0-macos-arm64.dmg',
);
expect(
updateAssetName('1.8.0', channel: UpdateChannel.linuxDeb, architecture: Architecture.ia32),
'Gopeed-v1.8.0-linux-386.deb',
);
});
test('maps Android ABI names', () {
expect(
updateAssetName('1.8.0', channel: UpdateChannel.androidApk, architecture: Architecture.arm),
'Gopeed-v1.8.0-android-armeabi-v7a.apk',
);
expect(
updateAssetName('1.8.0', channel: UpdateChannel.androidApk, architecture: Architecture.arm64),
'Gopeed-v1.8.0-android-arm64-v8a.apk',
);
});
});
test('selects the matching bilingual release notes', () {
const notes = '# Release notes\n\n- English change\n\n# 更新日志\n\n- 中文更新';
expect(localizedReleaseNotes(notes, 'en'), '# Release notes\n\n- English change');
expect(localizedReleaseNotes(notes, 'zh-CN'), '# 更新日志\n\n- 中文更新');
});
test('builds enabled GitHub proxy URLs and ignores deleted mirrors', () {
final config = ExtraConfigGithubMirror(
mirrors: [
GithubMirror(type: GithubMirrorType.ghProxy, url: 'https://mirror.example'),
GithubMirror(type: GithubMirrorType.ghProxy, url: 'https://deleted.example', isDeleted: true),
],
);
expect(
githubMirrorUrls(
'https://github.com/GopeedLab/gopeed/releases/download/v1.8.0/app.zip',
MirrorType.githubRelease,
config: config,
),
['https://mirror.example/https://github.com/GopeedLab/gopeed/releases/download/v1.8.0/app.zip'],
);
});
testWidgets('update dialog shows beta versions without tag prefixes', (tester) async {
tester.view.physicalSize = const Size(390, 760);
tester.view.devicePixelRatio = 1;
addTearDown(() {
tester.view.resetPhysicalSize();
tester.view.resetDevicePixelRatio();
});
app_package.packageInfo = PackageInfo(
appName: 'Gopeed',
packageName: 'com.gopeed.Gopeed',
version: '2.0.0.1',
buildNumber: '1',
);
addTearDown(() {
app_package.packageInfo = PackageInfo(
appName: 'Gopeed',
packageName: 'com.gopeed.Gopeed',
version: '1.7.0',
buildNumber: '1',
);
});
const version = VersionInfo(
version: '2.0.0-beta.2',
changeLog: '# Release notes\n\n- Faster downloads\n\n# 更新日志\n\n- 下载更快',
releaseUrl: 'https://example.com/release',
);
await tester.pumpWidget(
shad.ShadcnApp(
theme: AppTheme.light(),
materialTheme: AppTheme.materialLight(),
home: Builder(
builder: (context) => shad.SecondaryButton(
onPressed: () => showAppUpdateDialog(context, versionInfo: version, onUpdate: (_, _) async {}),
child: const Text('Open update'),
),
),
),
);
await tester.tap(find.text('Open update'));
await tester.pumpAndSettle();
expect(find.byKey(const ValueKey('app-update-dialog')), findsOneWidget);
expect(find.text('A new version is available'), findsOneWidget);
expect(find.text('2.0.0-beta.1 → 2.0.0-beta.2'), findsOneWidget);
expect(find.textContaining('v2.0.0'), findsNothing);
expect(find.text('Faster downloads'), findsOneWidget);
expect(find.text('下载更快'), findsNothing);
expect(find.text('Later'), findsOneWidget);
expect(find.text('Update Now'), findsOneWidget);
final dialog = tester.getRect(find.byKey(const ValueKey('app-update-dialog')));
expect(dialog.width, lessThan(320));
expect(tester.getCenter(find.byKey(const ValueKey('app-update-heading'))).dx, closeTo(dialog.center.dx, 0.01));
expect(tester.getCenter(find.byKey(const ValueKey('app-update-actions'))).dx, closeTo(dialog.center.dx, 0.01));
expect(tester.takeException(), isNull);
});
}
File diff suppressed because it is too large. Load diff