Files
flutterApp/test/region_list_test.dart
2026-11-06 08:44:05 +08:00

362 lines
13 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import 'dart:async';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:maibu_satabot_v2/core/logging/i_logger_service.dart';
import 'package:maibu_satabot_v2/features/autonomous_work/domain/repositories/autonomous_work_gateway.dart';
import 'package:maibu_satabot_v2/features/regions/data/datasources/region_remote_datasource.dart';
import 'package:maibu_satabot_v2/features/regions/data/repositories/region_repository_impl.dart';
import 'package:maibu_satabot_v2/features/regions/domain/entities/region_draft.dart';
import 'package:maibu_satabot_v2/features/regions/domain/usecases/region_usecases.dart';
import 'package:maibu_satabot_v2/features/regions/presentation/cubit/region_list_cubit.dart';
import 'package:maibu_satabot_v2/features/regions/presentation/widgets/region_list_panel.dart';
import 'package:maibu_satabot_v2/features/regions/presentation/widgets/no_device_crosshair_hint.dart';
Map<String, dynamic> row({int id = 16, int site = 18}) => {
'id': id,
'regionName': '测试分区',
'regionCode': null,
'remark': null,
'siteId': '$site',
'type': 'region',
'status': 1,
'delFlag': false,
'defaultRoute': 266,
'bindRoutes': [265, 266],
'scope': [
{'lat': 31.08342690658137, 'lng': 120.84065934046428},
{'lat': 31.083408345015524, 'lng': 120.8409046603276},
{'lat': 31.08329929760247, 'lng': 120.84085343939437},
{'lat': 31.08325985510068, 'lng': 120.84065664455204},
],
};
class _Logger implements ILoggerService {
@override
void logWithLevel(
String message, {
String level = 'INFO',
Map<String, dynamic>? data,
bool shouldLog = false,
}) {}
@override
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}
class _Routes implements AutonomousWorkGateway {
@override
dynamic noSuchMethod(Invocation invocation) =>
throw StateError('分区列表/删除不应调用路线接口');
}
class _Harness {
_Harness() {
dio.interceptors.add(
InterceptorsWrapper(
onRequest: (options, handler) async {
requests.add(options);
handler.resolve(
Response(
requestOptions: options,
statusCode: 200,
data: await respond(options),
),
);
},
),
);
repository = RegionRepositoryImpl(
remote: RegionRemoteDatasource(dio, _Logger()),
routes: _Routes(),
);
cubit = RegionListCubit(
LoadRegionsUseCase(repository),
DeleteRegionsUseCase(repository),
);
}
final dio = Dio();
final requests = <RequestOptions>[];
late final RegionRepositoryImpl repository;
late final RegionListCubit cubit;
Future<Map<String, dynamic>> Function(RequestOptions) respond =
(options) async => {
'code': 200,
'msg': '操作成功',
'data': options.method == 'GET' ? [row()] : 1,
};
Future<void> load() => cubit.load(siteId: 18, ownerId: 'u1');
Future<void> close() async {
await cubit.close();
dio.close();
}
}
Future<void> _mount(
WidgetTester tester,
_Harness h, {
VoidCallback? create,
ValueChanged<RegionDraft>? edit,
Object? Function()? currentScope,
}) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Center(
child: SizedBox(
width: 320,
height: 300,
child: RegionListPanel(
cubit: h.cubit,
currentScope: currentScope ?? () => ('u1', 18),
onCreate: create ?? () {},
onEdit: edit ?? (_) {},
onRefresh: () => h.load(),
),
),
),
),
),
);
await tester.pumpAndSettle();
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
test('GET 按场站查询,字符串 siteId/空字段正常解析,编辑数据完整', () async {
final h = _Harness();
addTearDown(h.close);
await h.load();
final request = h.requests.single;
expect(request.method, 'GET');
expect(request.uri.path, '/system/region/selectBySiteId');
expect(request.queryParameters, {'siteId': 18});
final region = h.cubit.state.regions.single;
expect(region.id, 16);
expect(region.siteId, 18);
expect(region.code, '');
expect(region.remark, '');
expect(region.scopeError, isNull);
expect(region.scope.first.lat, 31.08342690658137);
expect(region.defaultRouteId, 266);
expect(region.boundRouteIds, [265, 266]);
});
test('列表过滤其他场站、已删除和其他区域类型,去重主键', () async {
final h = _Harness();
addTearDown(h.close);
h.respond = (_) async => {
'code': 200,
'data': [
row(),
row(),
row(id: 17, site: 19),
{...row(id: 18), 'delFlag': true},
{...row(id: 19), 'type': 'obstacle'},
],
};
await h.load();
expect(h.cubit.state.regions.map((r) => r.id), [16]);
});
test('删除发送 POST JSON 数组 [16],data:1 成功后移除并取消选中', () async {
final h = _Harness();
addTearDown(h.close);
await h.load();
h.cubit.select(16);
expect(await h.cubit.deleteRegion(h.cubit.state.regions.single), isTrue);
expect(h.requests.last.method, 'POST');
expect(h.requests.last.uri.path, '/system/region/delete');
expect(h.requests.last.data, [16]);
expect(h.cubit.state.regions, isEmpty);
expect(h.cubit.state.selectedId, isNull);
});
test('删除失败保留列表、选择和可重试状态', () async {
final h = _Harness();
addTearDown(h.close);
await h.load();
h.cubit.select(16);
h.respond = (_) async => {'code': 500, 'msg': '分区已被绑定'};
expect(await h.cubit.deleteRegion(h.cubit.state.regions.single), isFalse);
expect(h.cubit.state.regions.single.id, 16);
expect(h.cubit.state.selectedId, 16);
expect(h.cubit.state.deletingId, isNull);
expect(h.cubit.state.operationError, contains('已被绑定'));
});
test('未登录/未选场站不请求;旧场站迟到的响应不会覆盖新场站', () async {
final h = _Harness();
addTearDown(h.close);
await h.cubit.load(siteId: 18, ownerId: null);
expect(h.cubit.state.status, RegionListStatus.noUser);
await h.cubit.load(siteId: null, ownerId: 'u1');
expect(h.cubit.state.status, RegionListStatus.noSite);
expect(h.requests, isEmpty);
final oldResponse = Completer<Map<String, dynamic>>();
h.respond = (o) => o.queryParameters['siteId'] == 18
? oldResponse.future
: Future.value({
'code': 200,
'data': [row(id: 20, site: 19)],
});
final old = h.load();
await Future<void>.delayed(Duration.zero);
await h.cubit.load(siteId: 19, ownerId: 'u1');
oldResponse.complete({
'code': 200,
'data': [row()],
});
await old;
expect(h.cubit.state.regions.single.id, 20);
expect(h.cubit.state.siteId, 19);
});
test('重复删除只发一次,退出登录不接受删除结果', () async {
final h = _Harness();
addTearDown(h.close);
await h.load();
final pending = Completer<Map<String, dynamic>>();
final started = Completer<void>();
h.respond = (_) {
started.complete();
return pending.future;
};
final region = h.cubit.state.regions.single;
final first = h.cubit.deleteRegion(region);
expect(await h.cubit.deleteRegion(region), isFalse);
await started.future;
expect(h.requests.where((r) => r.method == 'POST'), hasLength(1));
await h.cubit.load(siteId: 18, ownerId: null);
pending.complete({'code': 200, 'data': 1});
expect(await first, isFalse);
expect(h.cubit.state.status, RegionListStatus.noUser);
});
test('保存后强制刷新不复用保存前的旧列表请求', () async {
final h = _Harness();
addTearDown(h.close);
final oldResponse = Completer<Map<String, dynamic>>();
final started = Completer<void>();
h.respond = (_) {
started.complete();
return oldResponse.future;
};
final old = h.load();
await started.future;
h.respond = (_) async => {
'code': 200,
'data': [row(id: 20)],
};
await h.cubit.load(siteId: 18, ownerId: 'u1', force: true);
oldResponse.complete({'code': 200, 'data': []});
await old;
expect(h.cubit.state.regions.single.id, 20);
});
testWidgets('共享列表:选中高亮、修改传完整对象、新增独立入口', (tester) async {
final h = _Harness();
addTearDown(h.close);
await tester.runAsync(h.load);
RegionDraft? edited;
var creates = 0;
await _mount(tester, h, create: () => creates++, edit: (r) => edited = r);
await tester.tap(find.text('测试分区'));
await tester.pump();
expect(h.cubit.state.selectedId, 16);
await tester.tap(find.byKey(const ValueKey('region_edit_16')));
expect(edited?.id, 16);
expect(edited?.scope, hasLength(4));
expect(edited?.boundRouteIds, [265, 266]);
await tester.tap(find.byKey(const ValueKey('region_list_create')));
expect(creates, 1);
expect(tester.takeException(), isNull);
});
testWidgets('删除先确认,取消不请求,失败保留行并显示原因', (tester) async {
final h = _Harness();
addTearDown(h.close);
await tester.runAsync(h.load);
await _mount(tester, h);
await tester.tap(find.byKey(const ValueKey('region_delete_16')));
await tester.pumpAndSettle();
await tester.tap(find.text('取消'));
await tester.pumpAndSettle();
expect(h.requests, hasLength(1));
h.respond = (_) async => {'code': 500, 'msg': '删除失败'};
await tester.tap(find.byKey(const ValueKey('region_delete_16')));
await tester.pumpAndSettle();
await tester.tap(find.byKey(const ValueKey('region_delete_confirm')));
await tester.pumpAndSettle();
expect(find.byKey(const ValueKey('region_row_16')), findsOneWidget);
expect(find.byKey(const ValueKey('region_delete_error')), findsOneWidget);
});
testWidgets('删除成功才移除分区行并通知地图', (tester) async {
final h = _Harness();
addTearDown(h.close);
await tester.runAsync(h.load);
RegionDraft? deleted;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: SizedBox(
width: 320,
height: 300,
child: RegionListPanel(
cubit: h.cubit,
currentScope: () => ('u1', 18),
onCreate: () {},
onEdit: (_) {},
onRefresh: () {},
onDeleted: (r) => deleted = r,
),
),
),
),
);
await tester.pumpAndSettle();
final response = Completer<Map<String, dynamic>>();
h.respond = (_) => response.future;
await tester.tap(find.byKey(const ValueKey('region_delete_16')));
await tester.pumpAndSettle();
await tester.tap(find.byKey(const ValueKey('region_delete_confirm')));
await tester.pump(const Duration(milliseconds: 250));
expect(h.cubit.state.deletingId, 16);
expect(find.byKey(const ValueKey('region_row_16')), findsOneWidget);
expect(deleted, isNull);
response.complete({'code': 200, 'data': 1});
await tester.pumpAndSettle();
expect(find.byKey(const ValueKey('region_row_16')), findsNothing);
expect(deleted?.id, 16);
await tester.pump(const Duration(seconds: 3));
});
testWidgets('确认弹窗期间切换场站,不发送旧分区删除请求', (tester) async {
final h = _Harness();
addTearDown(h.close);
await tester.runAsync(h.load);
Object scope = ('u1', 18);
await _mount(tester, h, currentScope: () => scope);
await tester.tap(find.byKey(const ValueKey('region_delete_16')));
await tester.pumpAndSettle();
scope = ('u1', 19);
await tester.tap(find.byKey(const ValueKey('region_delete_confirm')));
await tester.pumpAndSettle();
expect(h.requests, hasLength(1));
expect(h.cubit.state.regions, hasLength(1));
await tester.pump(const Duration(seconds: 3));
});
testWidgets('无设备提示可关闭,选择/取消选择设备后保持关闭状态', (tester) async {
Future<void> show(bool hasDevice) => tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: SizedBox(
width: 280,
child: NoDeviceCrosshairHint(hasDevice: hasDevice),
),
),
),
);
await show(true);
expect(find.textContaining('准星打点'), findsNothing);
await show(false);
expect(find.textContaining('准星打点'), findsOneWidget);
await tester.tap(find.byKey(const ValueKey('dismiss_crosshair_hint')));
await tester.pump();
expect(find.textContaining('准星打点'), findsNothing);
await show(true);
await show(false);
expect(find.textContaining('准星打点'), findsNothing);
});
}