import 'dart:async'; import 'dart:io'; import 'dart:ui' as ui; import 'package:dio/dio.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:maibu_satabot_v2/core/di/injection.dart'; import 'package:maibu_satabot_v2/core/localization/app_localizations.dart'; import 'package:maibu_satabot_v2/core/logging/i_logger_service.dart'; import 'package:maibu_satabot_v2/features/autonomous_work/domain/entities/work_session_models.dart'; import 'package:maibu_satabot_v2/features/autonomous_work/domain/repositories/autonomous_work_gateway.dart'; import 'package:maibu_satabot_v2/features/devices/data/datasources/device_task_datasource.dart'; import 'package:maibu_satabot_v2/features/devices/data/repositories/device_task_repository_impl.dart'; import 'package:maibu_satabot_v2/features/devices/domain/usecases/save_device_schedule_plan_usecase.dart'; import 'package:maibu_satabot_v2/features/v2/device_list/presentation/bloc/robot_list_bloc.dart'; import 'package:maibu_satabot_v2/features/v2/device_list/presentation/pages/robot_autonomous_work_page_v2.dart'; import 'package:maibu_satabot_v2/features/v2/home/domain/entities/site_entity.dart'; import 'package:maibu_satabot_v2/features/v2/site/presentation/cubit/site_cubit.dart'; import 'package:maibu_satabot_v2/features/v2/work/presentation/cubit/schedule_plan_create_cubit.dart'; import 'package:maibu_satabot_v2/features/v2/work/presentation/pages/work_plan_create_page_v2.dart'; import 'package:maibu_satabot_v2/features/v2/work/presentation/widgets/work_phone_ui.dart'; import 'package:shared_preferences/shared_preferences.dart'; class _RouteGateway implements AutonomousWorkGateway { int? siteId = 17; final requestedSites = []; final started = []; @override Future> startWork( WorkStartRequest request, ) async { started.add(request); throw StateError('立即下发入口不应启动任务'); } Future>> Function() load = () async => WorkResult.ok([const WorkRouteOption(id: '8', name: '测试作业路线')]); @override Future resolveScope({required String deviceId}) async => WorkScope(siteId: siteId); @override Future>> loadRoutes({required int siteId}) { requestedSites.add(siteId); return load(); } @override dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); } class _NavigationObserver extends NavigatorObserver { final pushes = >[]; @override void didPush(Route route, Route? previousRoute) { super.didPush(route, previousRoute); pushes.add(route); } } class _TestLogger implements ILoggerService { final messages = []; @override void logWithLevel( String message, { String level = 'INFO', Map? data, bool shouldLog = false, }) { if (shouldLog) messages.add(message); } @override dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); } // 同步提供本地化依赖,避免资产读取影响弹窗生命周期测试。 class _TestLocalizationsDelegate extends LocalizationsDelegate { const _TestLocalizationsDelegate([this.localizations]); final AppLocalizations? localizations; @override bool isSupported(Locale locale) => true; @override Future load(Locale locale) => SynchronousFuture(localizations ?? AppLocalizations(locale)); @override bool shouldReload(_TestLocalizationsDelegate old) => false; } void main() { late _RouteGateway gateway; late SiteCubit siteCubit; late Dio dio; late _TestLogger logger; late List saveRequests; late Future> Function() saveResponse; late _NavigationObserver navigation; setUp(() async { SharedPreferences.setMockInitialValues({}); siteCubit = SiteCubit(await SharedPreferences.getInstance()); gateway = _RouteGateway(); logger = _TestLogger(); saveRequests = []; navigation = _NavigationObserver(); saveResponse = () async => {'msg': '操作成功', 'code': 200, 'data': 1}; dio = Dio(); // 只替换 HTTP 边界,提交仍经过真实 Cubit、UseCase、Repository、Datasource。 dio.interceptors.add( InterceptorsWrapper( onRequest: (options, handler) async { if (options.method == 'GET') { handler.resolve( Response( requestOptions: options, statusCode: 200, data: { 'code': 200, 'rows': [ { 'deviceName': 'MC700-test', 'deviceId': 3, 'deviceAlias': '测试设备', }, { 'deviceName': 'MC700-second', 'deviceId': 4, 'deviceAlias': '第二台设备', }, ], }, ), ); return; } saveRequests.add(options); handler.resolve( Response( requestOptions: options, statusCode: 200, data: await saveResponse(), ), ); }, ), ); sl.registerSingleton(siteCubit); sl.registerSingleton(gateway); sl.registerSingleton(logger); sl.registerFactory(() => RobotListBloc(dio)); sl.registerFactory( () => SchedulePlanCreateCubit( SaveDeviceSchedulePlanUseCase( DeviceTaskRepositoryImpl(datasource: DeviceTaskDatasourceImpl(dio)), ), ), ); }); tearDown(() async { await siteCubit.close(); dio.close(); await sl.reset(); }); Future openPage( WidgetTester tester, { AppLocalizations? localizations, }) async { await tester.pumpWidget( RepaintBoundary( key: const ValueKey('work_plan_preview'), child: MaterialApp( navigatorObservers: [navigation], debugShowCheckedModeBanner: false, theme: localizations == null ? null : ThemeData(fontFamily: 'PreviewFont'), localizationsDelegates: [_TestLocalizationsDelegate(localizations)], home: Builder( builder: (context) => Scaffold( body: TextButton( onPressed: () => Navigator.of(context).push(WorkPlanCreatePageV2.route()), child: const Text('打开新建计划'), ), ), ), ), ), ); await tester.tap(find.text('打开新建计划')); await tester.pumpAndSettle(); } Future openPicker(WidgetTester tester) async { await openPage(tester); await tester.pumpAndSettle(); final context = tester.element(find.byType(WorkPlanCreatePageV2)); final pickLabel = AppLocalizations.of( context, ).translate('work_v2.plan_create.route_pick'); await tester.ensureVisible(find.text(pickLabel)); await tester.tap(find.text(pickLabel)); await tester.pump(); await tester.pump(const Duration(milliseconds: 400)); } Future fillPlan(WidgetTester tester) async { siteCubit.updateSites(const [ SiteEntity(id: 17, siteName: '测试场站', orgId: 23, status: 0), ]); await openPicker(tester); await tester.pumpAndSettle(); await tester.tap(find.text('测试作业路线')); await tester.pumpAndSettle(); final devicePick = find.text('work_v2.plan_create.device_pick'); await tester.ensureVisible(devicePick); await tester.tap(devicePick); await tester.pumpAndSettle(); await tester.tap(find.text('测试设备')); await tester.pumpAndSettle(); expect(find.byType(TextField), findsNothing); } Future submit(WidgetTester tester) async { final button = find.text('work_v2.plan_create.submit'); await tester.ensureVisible(button); await tester.tap(button); } Future selectMode(WidgetTester tester, String key) async { final target = find.byKey(ValueKey(key)); await tester.ensureVisible(target); await tester.tap(target); await tester.pumpAndSettle(); } testWidgets('路线立即下发携带实际选择的设备与路线,进入前不创建或执行任务', (tester) async { final platformCalls = []; tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( SystemChannels.platform, (call) async { platformCalls.add(call); return null; }, ); addTearDown( () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( SystemChannels.platform, null, ), ); const selectedRoute = WorkRouteOption(id: '9', name: '另一条作业路线'); gateway.load = () async => WorkResult.ok([ const WorkRouteOption(id: '8', name: '测试作业路线'), selectedRoute, ]); await fillPlan(tester); await tester.ensureVisible(find.text('测试作业路线')); await tester.tap(find.text('测试作业路线')); await tester.pumpAndSettle(); await tester.tap(find.text('另一条作业路线')); await tester.pumpAndSettle(); await tester.ensureVisible(find.text('测试设备(MC700-test)')); await tester.tap(find.text('测试设备(MC700-test)')); await tester.pumpAndSettle(); await tester.tap(find.text('第二台设备')); await tester.pumpAndSettle(); await selectMode(tester, 'work_plan_timing_immediate'); expect(find.byType(TextField), findsNothing); final button = find.byKey(const ValueKey('work_plan_submit')); final context = tester.element(button); final pushed = navigation.pushes.length; final queuedSubmit = tester.widget(button).onPressed!; await tester.tap(button); queuedSubmit(); // 模拟已排队的第二次点击,不能再推入一个作业中心。 expect(navigation.pushes, hasLength(pushed + 1)); final pageRoute = navigation.pushes.last as MaterialPageRoute; final destination = pageRoute.builder(context) as RobotAutonomousWorkPageV2; expect(destination.robot.name, 'MC700-second'); expect(destination.robot.id, '4'); expect(destination.robot.alias, '第二台设备'); expect(identical(destination.initialRoute, selectedRoute), isTrue); expect(destination.entryPanel, isNull); expect(saveRequests, isEmpty); expect(gateway.started, isEmpty); // 在目标页构建前返回,只验证导航参数;既有作业中心负责后续开始确认。 Navigator.of(context).pop(); await tester.pumpAndSettle(); expect(find.byType(WorkPlanCreatePageV2), findsOneWidget); expect(find.text('另一条作业路线'), findsOneWidget); expect(find.text('第二台设备(MC700-second)'), findsOneWidget); expect( platformCalls.any( (c) => c.method == 'SystemChrome.setPreferredOrientations' && (c.arguments as List).contains('DeviceOrientation.portraitUp'), ), isTrue, ); expect(tester.takeException(), isNull); }); testWidgets('路线立即下发缺少路线时只提示选择,不跳转或请求创建接口', (tester) async { await openPage(tester); await selectMode(tester, 'work_plan_timing_immediate'); final pushed = navigation.pushes.length; await tester.tap(find.byKey(const ValueKey('work_plan_submit'))); await tester.pumpAndSettle(); expect(navigation.pushes, hasLength(pushed)); expect(find.text('work_v2.plan_create.route_pick'), findsNWidgets(2)); expect(saveRequests, isEmpty); expect(gateway.started, isEmpty); await tester.pump(const Duration(seconds: 3)); }); testWidgets('路线立即下发缺少设备时只提示选择,不跳转或创建任务', (tester) async { await openPicker(tester); await tester.pumpAndSettle(); await tester.tap(find.text('测试作业路线')); await tester.pumpAndSettle(); await selectMode(tester, 'work_plan_timing_immediate'); final pushed = navigation.pushes.length; await tester.tap(find.byKey(const ValueKey('work_plan_submit'))); await tester.pumpAndSettle(); expect(navigation.pushes, hasLength(pushed)); expect(find.text('work_v2.plan_create.device_pick'), findsNWidgets(2)); expect(saveRequests, isEmpty); expect(gateway.started, isEmpty); await tester.pump(const Duration(seconds: 3)); }); testWidgets('选择后场站发生变化时阻止使用旧设备路线进入作业中心', (tester) async { await fillPlan(tester); await selectMode(tester, 'work_plan_timing_immediate'); siteCubit.updateSites(const [ SiteEntity(id: 19, siteName: '新场站', orgId: 24, status: 0), ]); final pushed = navigation.pushes.length; await tester.tap(find.byKey(const ValueKey('work_plan_submit'))); await tester.pumpAndSettle(); expect(navigation.pushes, hasLength(pushed)); expect(find.text('work_v2.plan_create.selection_changed'), findsOneWidget); expect(saveRequests, isEmpty); expect(gateway.started, isEmpty); await tester.pump(const Duration(seconds: 3)); }); Future capturePreview(WidgetTester tester, String name) async { if (!const bool.fromEnvironment('CAPTURE_WORK_PLAN')) return; final boundary = tester.renderObject( find.byKey(const ValueKey('work_plan_preview')), ); await tester.runAsync(() async { final image = await boundary.toImage(pixelRatio: 2); final bytes = await image.toByteData(format: ui.ImageByteFormat.png); final directory = Directory('build/ui_previews'); await directory.create(recursive: true); await File( '${directory.path}/$name.png', ).writeAsBytes(bytes!.buffer.asUint8List()); image.dispose(); }); } testWidgets('打开路线弹窗即请求当前场站列表,返回后可选择并回填', (tester) async { final pending = Completer>>(); gateway.load = () => pending.future; await openPicker(tester); expect(gateway.requestedSites, [17]); expect(find.byType(CircularProgressIndicator), findsOneWidget); pending.complete( WorkResult.ok([const WorkRouteOption(id: '8', name: '测试作业路线')]), ); await tester.pumpAndSettle(); expect(find.byType(CircularProgressIndicator), findsNothing); await tester.tap(find.text('测试作业路线')); await tester.pumpAndSettle(); expect(find.byType(BottomSheet), findsNothing); expect(find.text('测试作业路线'), findsOneWidget); expect(tester.takeException(), isNull); }); testWidgets('加载异常结束转圈,重试后展示列表', (tester) async { gateway.load = () async => throw StateError('路线请求失败'); await openPicker(tester); await tester.pumpAndSettle(); expect(find.byType(CircularProgressIndicator), findsNothing); expect(find.textContaining('路线请求失败'), findsOneWidget); gateway.load = () async => WorkResult.ok([const WorkRouteOption(id: '8', name: '测试作业路线')]); final context = tester.element(find.byType(WorkPlanCreatePageV2)); await tester.tap( find.text( AppLocalizations.of(context).translate('work_v2.route_lib.reload'), ), ); await tester.pumpAndSettle(); expect(gateway.requestedSites, [17, 17]); expect(find.text('测试作业路线'), findsOneWidget); }); testWidgets('未选择场站时停止加载且不请求列表', (tester) async { gateway.siteId = null; await openPicker(tester); await tester.pumpAndSettle(); expect(gateway.requestedSites, isEmpty); expect(find.byType(CircularProgressIndicator), findsNothing); final context = tester.element(find.byType(WorkPlanCreatePageV2)); expect( find.text( AppLocalizations.of(context).translate('work_v2.plan_create.no_site'), ), findsOneWidget, ); }); testWidgets('列表为空时显示空态并停止加载', (tester) async { gateway.load = () async => WorkResult.ok([]); await openPicker(tester); await tester.pumpAndSettle(); expect(find.byType(CircularProgressIndicator), findsNothing); final context = tester.element(find.byType(WorkPlanCreatePageV2)); expect( find.text( AppLocalizations.of(context).translate('work_v2.route_lib.empty_site'), ), findsOneWidget, ); }); testWidgets('点击创建计划能提示未选择路线,不抛出 Provider 查找异常', (tester) async { await openPage(tester); await submit(tester); await tester.pumpAndSettle(); expect(find.text('work_v2.plan_create.route_pick'), findsNWidgets(2)); expect(saveRequests, isEmpty); expect(tester.takeException(), isNull); await tester.pump(const Duration(seconds: 3)); }); testWidgets('选择路线后点击创建能提示必填设备,不发出无效请求', (tester) async { await openPicker(tester); await tester.pumpAndSettle(); await tester.tap(find.text('测试作业路线')); await tester.pumpAndSettle(); await submit(tester); await tester.pumpAndSettle(); expect(find.text('work_v2.plan_create.device_pick'), findsNWidgets(2)); expect(saveRequests, isEmpty); expect(find.byType(CircularProgressIndicator), findsNothing); await tester.pump(const Duration(seconds: 3)); }); testWidgets('完整填写后点击创建调用保存接口、打印日志,等待期间不重复提交', (tester) async { final pending = Completer>(); saveResponse = () => pending.future; await fillPlan(tester); await submit(tester); await tester.tap(find.text('work_v2.plan_create.submit')); await tester.pump(); await tester.pump(const Duration(milliseconds: 100)); expect(saveRequests, hasLength(1)); final request = saveRequests.single; expect(request.method, 'POST'); expect(request.uri.path, '/iot/deviceTask/save'); expect(request.data, containsPair('deviceId', 'MC700-test')); expect(request.data['planName'], startsWith('测试作业路线-')); expect( (request.data['planName'] as String).runes.length, lessThanOrEqualTo(30), ); expect(request.data, containsPair('routeId', 8)); expect(request.data, containsPair('siteId', 17)); expect(request.data, containsPair('orgId', 23)); expect(request.data['deviceTaskPlanRules'], { 'type': 'DAY', 'dayTime': '08:00:00', }); expect(find.byType(CircularProgressIndicator), findsOneWidget); expect(logger.messages.any((m) => m.contains('请求: POST')), isTrue); expect(logger.messages.any((m) => m.contains('参数:')), isTrue); // 真实接口的成功报文:data 是整数,不能强转为 bool。 pending.complete({'msg': '操作成功', 'code': 200, 'data': 1}); await tester.pumpAndSettle(); expect(find.byType(WorkPlanCreatePageV2), findsNothing); expect(find.text('work_v2.plan_create.success'), findsOneWidget); expect( logger.messages.any((m) => m.contains('响应: statusCode=200')), isTrue, ); expect(tester.takeException(), isNull); expect(logger.messages.any((m) => m.contains('结果: 成功')), isTrue); expect(logger.messages.any((m) => m.contains('异常:')), isFalse); await tester.pump(const Duration(seconds: 3)); }); testWidgets('保存接口失败显示原因,恢复按钮后可以重试', (tester) async { saveResponse = () async => {'code': 500, 'msg': '方案名称已存在'}; await fillPlan(tester); await submit(tester); await tester.pumpAndSettle(); expect(find.textContaining('方案名称已存在'), findsOneWidget); expect(find.byType(WorkPlanCreatePageV2), findsOneWidget); expect(find.byType(CircularProgressIndicator), findsNothing); expect(logger.messages.any((m) => m.contains('业务失败: code=500')), isTrue); saveResponse = () async => {'code': 200, 'data': true}; await submit(tester); await tester.pumpAndSettle(); expect(saveRequests, hasLength(2)); expect(find.byType(WorkPlanCreatePageV2), findsNothing); await tester.pump(const Duration(seconds: 3)); }); for (final result in [0, false]) { testWidgets('保存结果为 $result 时提示失败并停留在表单', (tester) async { saveResponse = () async => {'code': 200, 'data': result}; await fillPlan(tester); await submit(tester); await tester.pumpAndSettle(); expect(saveRequests, hasLength(1)); expect(find.byType(WorkPlanCreatePageV2), findsOneWidget); expect(find.text('创建计划失败,请重试'), findsOneWidget); expect(find.byType(CircularProgressIndicator), findsNothing); expect(logger.messages.any((m) => m.contains('结果: 未保存')), isTrue); expect(logger.messages.any((m) => m.contains('结果: 成功')), isFalse); expect(tester.takeException(), isNull); await tester.pump(const Duration(seconds: 3)); }); } for (final weekly in [true, false]) { testWidgets('切换四种组合保留表单,返回后仍能创建${weekly ? '按周' : '按月'}路线定时任务', ( tester, ) async { await fillPlan(tester); final cycle = find.text( 'work_v2.plan_create.type_${weekly ? 'week' : 'month'}', ); await tester.ensureVisible(find.byType(WorkFilterRow)); // 这里使用翻译 key 作为文本,第三项比真实文案长,需先横向滑到末尾。 if (!weekly) { await tester.drag(find.byType(WorkFilterRow), const Offset(-700, 0)); await tester.pumpAndSettle(); } await tester.ensureVisible(cycle); await tester.tap(cycle); await tester.pumpAndSettle(); for (final label in weekly ? ['work_v2.plan.weekday_fri', 'work_v2.plan.weekday_mon'] : ['15', '1']) { await tester.ensureVisible(find.text(label)); await tester.tap(find.text(label)); await tester.pumpAndSettle(); } for (final mode in [ ['work_plan_dispatch_area', 'work_plan_timing_scheduled'], ['work_plan_dispatch_area', 'work_plan_timing_immediate'], ['work_plan_dispatch_route', 'work_plan_timing_immediate'], ]) { for (final key in mode) { await selectMode(tester, key); } final button = find.byKey(const ValueKey('work_plan_submit')); final area = mode.first.endsWith('area'); expect( tester.widget(button).onPressed, area ? isNull : isNotNull, ); if (area) { await tester.tap(button); await tester.pumpAndSettle(); } expect(saveRequests, isEmpty); expect( find.text('work_v2.plan_create.coming_soon'), area ? findsOneWidget : findsNothing, ); expect(find.byType(TextField), findsNothing); expect( find.text('work_v2.plan_create.cycle_label'), mode.last.endsWith('immediate') ? findsNothing : findsOneWidget, ); } await selectMode(tester, 'work_plan_timing_scheduled'); expect(find.byType(TextField), findsNothing); expect(find.text('测试作业路线'), findsOneWidget); expect(find.text('测试设备(MC700-test)'), findsOneWidget); expect( tester .widget( find.byKey(const ValueKey('work_plan_submit')), ) .onPressed, isNotNull, ); await submit(tester); await tester.pumpAndSettle(); expect(saveRequests, hasLength(1)); expect(saveRequests.single.uri.path, '/iot/deviceTask/save'); expect(saveRequests.single.data['planName'], startsWith('测试作业路线-')); expect(saveRequests.single.data['routeId'], 8); expect( saveRequests.single.data['deviceTaskPlanRules'], weekly ? { 'type': 'WEEK', 'days': ['MONDAY', 'FRIDAY'], 'dayTime': '08:00:00', } : { 'type': 'MONTH', 'dates': [1, 15], 'dayTime': '08:00:00', }, ); expect(find.byType(WorkPlanCreatePageV2), findsNothing); expect(tester.takeException(), isNull); await tester.pump(const Duration(seconds: 3)); }); } for (final locale in [const Locale('zh', 'CN'), const Locale('en', 'US')]) { for (final width in [320.0, 390.0]) { testWidgets('${locale.languageCode} 页面在 ${width.toInt()} 宽手机上切换无溢出', ( tester, ) async { tester.view.devicePixelRatio = 1; tester.view.physicalSize = Size(width, 844); addTearDown(tester.view.resetDevicePixelRatio); addTearDown(tester.view.resetPhysicalSize); final localizations = await tester.runAsync(() async { final l10n = AppLocalizations(locale); await l10n.load(); if (Platform.isWindows) { final font = FontLoader('PreviewFont'); font.addFont( Future.value( ByteData.sublistView( await File('C:/Windows/Fonts/msyh.ttc').readAsBytes(), ), ), ); await font.load(); } final icons = FontLoader('MaterialIcons'); icons.addFont(rootBundle.load('fonts/MaterialIcons-Regular.otf')); await icons.load(); return l10n; }); await openPage(tester, localizations: localizations); expect(tester.takeException(), isNull); final prefix = '${locale.languageCode}_${width.toInt()}'; await capturePreview(tester, '${prefix}_route_scheduled'); await selectMode(tester, 'work_plan_dispatch_area'); expect(tester.takeException(), isNull); expect( find.text(localizations!.translate('work_v2.plan_create.route_pick')), findsNothing, ); await capturePreview(tester, '${prefix}_area_scheduled'); await selectMode(tester, 'work_plan_timing_immediate'); expect(tester.takeException(), isNull); await capturePreview(tester, '${prefix}_area_immediate'); await selectMode(tester, 'work_plan_dispatch_route'); expect(tester.takeException(), isNull); await capturePreview(tester, '${prefix}_route_immediate'); expect(saveRequests, isEmpty); }); } } }