Skip to content

PasteFerry (隔空贴): clipboard and file sync across macOS, Windows and Linux. Direct-first, end-to-end encrypted. Optional official access: no server to host. Independent self-hosting remains available.

10.4 KB
Raw Blame
import 'dart:io';

import 'package:fixnum/fixnum.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';

import 'package:pasteferry_ui/app_state.dart';
import 'package:pasteferry_ui/background_service.dart';
import 'package:pasteferry_ui/gen/pasteferry/v1/daemon.pb.dart';
import 'package:pasteferry_ui/i18n.dart';
import 'package:pasteferry_ui/main.dart';
import 'package:pasteferry_ui/widgets/feedback_dialog.dart';
import 'package:pasteferry_ui/widgets/pairing_dialog.dart';

class _DemoState extends AppState {
  @override
  Future<PairingCode> createPairingCode() async => (code: 'K7MP2X', addresses: ['192.168.1.20']);

  @override
  Future<String> exportDiagnostics({int logLines = 200}) async =>
      'PasteFerry diagnostics report\n${List.filled(40, 'time=2026-10-13T20:41:02 level=INFO msg=信令已连接').join('\n')}';
}

AppState _demo(String language, {LinkState link = LinkState.online, ServiceState? service}) =>
    _DemoState()
      ..debugSeed(
        link: link,
        serviceState: service,
        status: Status(signalingConnected: true, version: '1.3.0'),
        config: Config(
          language: language,
          signalingUrl: 'wss://sync.example.com/signal',
          deviceName: 'MacBook Pro',
          autoSyncThresholdBytes: Int64(50 << 20),
          historyTtlSeconds: Int64(3 * 86400),
          cacheTtlSeconds: Int64(86400),
        ),
        self: Device(id: 'self', name: 'MacBook Pro', publicKeyFingerprint: 'H3QD-7KXA-M2PV'),
        peers: [
          Device(
            id: 'air',
            name: 'MacBook Air',
            online: true,
            connection: ConnectionKind.CONNECTION_KIND_RELAY,
            publicKeyFingerprint: 'R8NF-2WTC-QL5J',
          ),
        ],
        records: [
          ClipRecord(
            id: '1',
            kind: ClipKind.CLIP_KIND_IMAGE,
            originDeviceName: 'MacBook Air',
            textPreview: '图片 2.4 MB',
            totalSize: Int64(2 << 20),
          ),
          ClipRecord(
            id: '2',
            kind: ClipKind.CLIP_KIND_FILE,
            status: ClipStatus.CLIP_STATUS_REMOTE_ONLY,
            originDeviceName: 'MacBook Air',
            textPreview: 'report.key 等 2 项',
            totalSize: Int64(900 << 20),
            items: [ClipItem(name: 'report.key'), ClipItem(name: 'notes.txt')],
          ),
        ],
        favorites: [
          ClipRecord(
            id: 'fav',
            kind: ClipKind.CLIP_KIND_TEXT,
            favorite: true,
            textPreview: 'https://pasteferry.cc/download/',
            isLink: true,
            outgoing: true,
            totalSize: Int64(31),
          ),
          ClipRecord(
            id: 'saving',
            kind: ClipKind.CLIP_KIND_FILE,
            favorite: true,
            status: ClipStatus.CLIP_STATUS_FAILED,
            error: '源设备当前不可达',
            originDeviceName: 'MacBook Air',
            items: [ClipItem(name: 'report.key')],
          ),
        ],
        // 快捷键被占用、还没授予辅助功能:设置页上要显示的东西最多的情况
        quickPaste: QuickPasteStatus(
          running: true,
          hotkey: 'alt+v',
          hotkeyError: 'in_use',
          pasteUnavailableReason: 'not_trusted',
        ),
      );

void main() {
  test('按系统的语言偏好取第一个支持的,都不支持时用英文', () {
    expect(resolveLocale(const [Locale('ja', 'JP')]), const Locale('ja'));
    expect(resolveLocale(const [Locale('fr'), Locale('ja')]), const Locale('ja'));
    expect(resolveLocale(const [Locale('fr')]), const Locale('en'));
    expect(resolveLocale(null), const Locale('en'));
  });

  // macOS 报 zh-Hant-TW,Windows 报 zh-TW,Linux 报 zh_TW;香港、澳门用香港的繁体
  test('中文按文字与地区分简体、台湾繁体、香港繁体', () {
    Locale zh(String? script, String? region) =>
        resolveLocale([Locale.fromSubtags(languageCode: 'zh', scriptCode: script, countryCode: region)]);
    expect(zh('Hant', 'TW'), zhHantTW);
    expect(zh(null, 'TW'), zhHantTW);
    expect(zh('Hant', null), zhHantTW);
    expect(zh('Hant', 'HK'), zhHantHK);
    expect(zh(null, 'HK'), zhHantHK);
    expect(zh(null, 'MO'), zhHantHK);
    expect(zh('Hans', 'HK'), const Locale('zh'));
    expect(zh('Hans', 'CN'), const Locale('zh'));
    expect(zh(null, 'CN'), const Locale('zh'));
    expect(zh(null, 'SG'), const Locale('zh'));
    expect(zh(null, null), const Locale('zh'));
  });

  test('设置里的空字符串表示跟随系统', () {
    expect(localeFromSetting(''), isNull);
    expect(localeFromSetting('zh-Hans'), const Locale('zh'));
    expect(localeFromSetting('zh-Hant-TW'), zhHantTW);
    expect(localeFromSetting('zh-Hant-HK'), zhHantHK);
    expect(localeFromSetting('en'), const Locale('en'));
    expect(localeFromSetting('ja'), const Locale('ja'));
  });

  testWidgets('设置里选的语言优先于系统语言', (tester) async {
    await tester.pumpWidget(PasteFerryApp(state: _demo('en')));
    expect(find.text('History'), findsWidgets);
    expect(find.text('复制记录'), findsNothing);
  });

  testWidgets('设置里选了繁体,界面用繁体', (tester) async {
    await tester.pumpWidget(PasteFerryApp(state: _demo('zh-Hant-HK')));
    expect(find.text(lookupAppLocalizations(zhHantHK).navHistory), findsWidgets);
    expect(find.text('复制记录'), findsNothing);
  });

  testWidgets('跟随系统时用系统语言', (tester) async {
    await tester.pumpWidget(PasteFerryApp(state: _demo('')));
    expect(find.text('复制记录'), findsWidgets);
  });

  testWidgets('配置里的语言一变,界面立即换过来', (tester) async {
    final state = _demo('');
    await tester.pumpWidget(PasteFerryApp(state: state));
    expect(find.text('复制记录'), findsWidgets);

    state.config!.language = 'ja';
    state.notifyListeners();
    await tester.pump();
    expect(find.text('履歴'), findsWidgets);
    expect(find.text('复制记录'), findsNothing);
  });

  testWidgets('图片与文件的标题按界面语言显示,不用后台服务存下的中文摘要', (tester) async {
    await tester.pumpWidget(PasteFerryApp(state: _demo('en')));
    expect(find.text('Image'), findsOneWidget);
    expect(find.text('report.key and 1 more'), findsOneWidget);
    expect(find.textContaining('图片'), findsNothing);
  });

  // 英文、日文通常比中文长:在最小窗口尺寸下把每一页、每个对话框都打开一遍,确认没有文字溢出
  for (final language in ['en', 'ja', 'zh-Hans', 'zh-Hant-TW', 'zh-Hant-HK']) {
    group('最小窗口下的 $language 界面', () {
      setUp(() {
        final view = TestWidgetsFlutterBinding.instance.platformDispatcher.views.first;
        view.physicalSize = const Size(760, 520);
        view.devicePixelRatio = 1;
      });
      tearDown(() => TestWidgetsFlutterBinding.instance.platformDispatcher.views.first.reset());

      Future<AppLocalizations> open(WidgetTester tester, AppState state) async {
        await tester.pumpWidget(PasteFerryApp(state: state));
        await tester.pump();
        return AppLocalizations.of(tester.element(find.byType(Shell)));
      }

      testWidgets('三个页面', (tester) async {
        final l = await open(tester, _demo(language));
        await tester.tap(find.text(l.navFavorites).first);
        await tester.pump();
        expect(find.text('https://pasteferry.cc/download/'), findsOneWidget);
        await tester.tap(find.text(l.navDevices).first);
        await tester.pump();
        expect(find.text(l.pairedDevices), findsOneWidget);
        await tester.tap(find.text(l.navSettings).first);
        await tester.pump();
        // 设置首页列出各类,逐个点进去、拉到底,再回到首页
        final pages = <String, String>{
          l.general: l.language,
          l.appearance: l.themeMode,
          l.settingsConnection: l.lanDiscovery,
          l.sync: l.syncImages,
          // 辅助功能授权只有 Mac 上有
          l.quickPaste: Platform.isMacOS ? l.quickPasteAccessibility : l.quickPasteWindow,
          l.navSend: l.receiveNotify,
          l.storage: l.favoritesUsage,
          l.about: l.updateAuto,
        };
        for (final MapEntry(key: title, value: last) in pages.entries) {
          // 只在设置的列表里找:「隔空传送」这些标题侧边栏里也有;列表下面的项没滚到时还没建出来
          final row = find.descendant(of: find.byType(ListView).last, matching: find.text(title));
          await tester.dragUntilVisible(row, find.byType(ListView).last, const Offset(0, -100));
          await tester.ensureVisible(row);
          await tester.pump();
          await tester.tap(row);
          await tester.pump();
          final end = find.descendant(of: find.byType(ListView).last, matching: find.text(last));
          await tester.dragUntilVisible(end, find.byType(ListView).last, const Offset(0, -100));
          await tester.tap(find.text(l.navSettings).last);
          await tester.pump();
        }
      });

      testWidgets('配对对话框', (tester) async {
        final l = await open(tester, _demo(language));
        showPairingDialog(tester.element(find.byType(Shell)));
        await tester.pumpAndSettle();
        expect(find.text('K7MP2X'), findsOneWidget);
        await tester.tap(find.text(l.enterCode));
        await tester.pumpAndSettle();
        expect(find.text(l.enterCodeShown), findsOneWidget);
      });

      testWidgets('核对指纹', (tester) async {
        final state = _demo(language);
        state.debugSeed(
          status: state.status!,
          config: state.config!,
          self: state.self!,
          pendingPairing: Device(name: 'MacBook Air', publicKeyFingerprint: 'R8NF-2WTC-QL5J', pairingSession: 's'),
        );
        final l = await open(tester, state);
        await tester.pumpAndSettle();
        expect(find.text(l.confirmMatch), findsOneWidget);
      });

      testWidgets('反馈问题', (tester) async {
        final l = await open(tester, _demo(language));
        showFeedbackDialog(tester.element(find.byType(Shell)));
        await tester.pumpAndSettle();
        expect(find.text(l.diagNewIssue), findsOneWidget);
      });

      testWidgets('启用后台服务的引导页', (tester) async {
        final l = await open(tester, _demo(language, link: LinkState.offline, service: ServiceState.notInstalled));
        expect(find.text(l.svcEnable), findsOneWidget);
      });
    });
  }
}