自主任务接口接入和bug修复和工作记录页面
This commit is contained in:
836
test/v2_work_task_tracker_test.dart
Normal file
836
test/v2_work_task_tracker_test.dart
Normal file
@@ -0,0 +1,836 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:fpdart/fpdart.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:latlong2/latlong.dart';
|
||||
import 'package:maibu_satabot_v2/core/error/failure.dart';
|
||||
import 'package:maibu_satabot_v2/core/logging/work_trace_diagnostics.dart';
|
||||
import 'package:maibu_satabot_v2/core/network/mqtt/domain/interfaces/mqtt_client.dart';
|
||||
import 'package:maibu_satabot_v2/core/network/mqtt/domain/models/mqtt_config.dart';
|
||||
import 'package:maibu_satabot_v2/core/network/mqtt/domain/models/mqtt_message.dart';
|
||||
import 'package:maibu_satabot_v2/features/autonomous_work/data/v2_work_store.dart';
|
||||
import 'package:maibu_satabot_v2/features/autonomous_work/data/v2_work_task_tracker.dart';
|
||||
import 'package:maibu_satabot_v2/features/autonomous_work/domain/entities/work_session_models.dart';
|
||||
import 'package:maibu_satabot_v2/features/devices/domain/entities/device_schedule_plan_entity.dart';
|
||||
import 'package:maibu_satabot_v2/features/devices/domain/entities/device_task_entity.dart';
|
||||
import 'package:maibu_satabot_v2/features/devices/domain/repositories/device_task_repository.dart';
|
||||
import 'package:maibu_satabot_v2/features/devices/domain/repositories/path_repository.dart';
|
||||
import 'package:maibu_satabot_v2/features/devices/domain/usecases/create_device_task_usecase.dart';
|
||||
import 'package:maibu_satabot_v2/features/pv_control/presentation/models/work_trace_recorder.dart';
|
||||
|
||||
Future<void> flush() async {
|
||||
for (var i = 0; i < 15; i++) {
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
}
|
||||
}
|
||||
|
||||
class FakeMqtt implements MqttClient {
|
||||
final messages = StreamController<MqttMessage>.broadcast(sync: true);
|
||||
final topics = <String>{};
|
||||
final configs = <MqttConfig>[];
|
||||
@override
|
||||
bool isConnected = false;
|
||||
@override
|
||||
Stream<MqttMessage> get messageStream => messages.stream;
|
||||
@override
|
||||
Future<void> connect(MqttConfig config) async {
|
||||
configs.add(config);
|
||||
isConnected = true;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> disconnect() async {
|
||||
isConnected = false;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> subscribe(String topic) async {
|
||||
topics.add(topic);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> unsubscribe(String topic) async {
|
||||
topics.remove(topic);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> publish(String topic, String message) async {}
|
||||
void status(
|
||||
String status, {
|
||||
int taskId = 42,
|
||||
String deviceId = 'MC700-test',
|
||||
int? topicId,
|
||||
}) {
|
||||
messages.add(
|
||||
MqttMessage(
|
||||
topic: 'task/${topicId ?? taskId}/status',
|
||||
payload: jsonEncode({
|
||||
'taskId': taskId,
|
||||
'deviceId': deviceId,
|
||||
'status': status,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void arrive(dynamic entity, {int taskId = 42}) => messages.add(
|
||||
MqttMessage(
|
||||
topic: 'task/$taskId/arrive',
|
||||
payload: jsonEncode({
|
||||
'type': 'device_task_arrive_point',
|
||||
'deviceId': 'MC700-test',
|
||||
'taskId': taskId,
|
||||
'entity': entity,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class FakeTasks implements DeviceTaskRepository {
|
||||
List<DeviceTaskEntity> tasks = [entity()];
|
||||
Completer<Either<Failure, List<DeviceTaskEntity>>>? pending;
|
||||
String? error;
|
||||
int? operatedTask;
|
||||
bool? force;
|
||||
static DeviceTaskEntity entity({
|
||||
int id = 42,
|
||||
String state = 'EXECUTING',
|
||||
int routeId = 8,
|
||||
}) => DeviceTaskEntity(
|
||||
id: id,
|
||||
deviceId: 'MC700-test',
|
||||
taskStatus: state,
|
||||
taskStatusTranslate: '',
|
||||
routeId: routeId,
|
||||
siteId: 2,
|
||||
orgId: 3,
|
||||
);
|
||||
@override
|
||||
Future<Either<Failure, List<DeviceTaskEntity>>> getDeviceTaskPool({
|
||||
required String userId,
|
||||
required int siteId,
|
||||
required int orgId,
|
||||
int pageNum = 1,
|
||||
int pageSize = 99999999,
|
||||
}) async =>
|
||||
pending?.future ?? (error == null ? Right(tasks) : Left(Failure(error!)));
|
||||
@override
|
||||
Future<Either<Failure, bool>> cancelTask({
|
||||
required String deviceId,
|
||||
required int taskId,
|
||||
required int orgId,
|
||||
required int siteId,
|
||||
bool forceCancel = true,
|
||||
}) async {
|
||||
operatedTask = taskId;
|
||||
force = forceCancel;
|
||||
return error == null ? const Right(true) : Left(Failure(error!));
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Either<Failure, bool>> pauseTask({
|
||||
required String deviceId,
|
||||
required int taskId,
|
||||
required int orgId,
|
||||
required int siteId,
|
||||
}) async {
|
||||
operatedTask = taskId;
|
||||
return error == null ? const Right(true) : Left(Failure(error!));
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Either<Failure, Map<String, dynamic>>> recoveryTask({
|
||||
required String deviceId,
|
||||
required int taskId,
|
||||
required int orgId,
|
||||
required int siteId,
|
||||
}) async {
|
||||
operatedTask = taskId;
|
||||
return error == null ? const Right({}) : Left(Failure(error!));
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Either<Failure, bool>> saveDeviceSchedulePlan({
|
||||
required DeviceSchedulePlanEntity plan,
|
||||
}) async {
|
||||
return error == null ? const Right(true) : Left(Failure(error!));
|
||||
}
|
||||
}
|
||||
|
||||
class FakePath implements PathRepository {
|
||||
int creations = 0;
|
||||
@override
|
||||
Future<int> createDeviceTask({
|
||||
required String deviceId,
|
||||
required int routeId,
|
||||
required int siteId,
|
||||
required int orgId,
|
||||
}) async {
|
||||
creations++;
|
||||
return 100;
|
||||
}
|
||||
|
||||
@override
|
||||
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
|
||||
}
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
late FakeTasks tasks;
|
||||
late FakePath path;
|
||||
late FakeMqtt mqtt;
|
||||
late V2WorkTaskTracker tracker;
|
||||
late StreamSubscription<WorkTaskSnapshot?> sub;
|
||||
late List<WorkTaskSnapshot?> updates;
|
||||
late List<String> traceLogs;
|
||||
late bool failTraceLogs;
|
||||
late int failedTraceWrites;
|
||||
setUp(() {
|
||||
SharedPreferences.setMockInitialValues({
|
||||
'saved_device_task_ids': '{"legacy":77}',
|
||||
});
|
||||
tasks = FakeTasks();
|
||||
path = FakePath();
|
||||
mqtt = FakeMqtt();
|
||||
updates = [];
|
||||
traceLogs = [];
|
||||
failTraceLogs = false;
|
||||
failedTraceWrites = 0;
|
||||
tracker = V2WorkTaskTracker(
|
||||
repository: tasks,
|
||||
createTask: CreateDeviceTaskUseCase(path),
|
||||
resolveScope: (_) async => const WorkScope(siteId: 2, orgId: 3),
|
||||
userId: () => 'test-user',
|
||||
store: V2WorkStore('test-user'),
|
||||
mqtt: mqtt,
|
||||
diagnostics: WorkTraceDiagnostics(
|
||||
now: () => DateTime(2026, 11, 5),
|
||||
write: (line) {
|
||||
if (failTraceLogs) {
|
||||
failedTraceWrites++;
|
||||
throw StateError('诊断输出失败');
|
||||
}
|
||||
traceLogs.add(line);
|
||||
},
|
||||
),
|
||||
);
|
||||
sub = tracker.watch('MC700-test').listen(updates.add);
|
||||
});
|
||||
tearDown(() async {
|
||||
await sub.cancel();
|
||||
await flush();
|
||||
await mqtt.messages.close();
|
||||
});
|
||||
|
||||
test(
|
||||
'restore task subscribes with task ID, filters other devices and tasks',
|
||||
() async {
|
||||
final result = await tracker.load('MC700-test');
|
||||
await flush();
|
||||
expect(result.isOk, isTrue);
|
||||
expect(mqtt.topics, {'task/42/status', 'task/42/arrive'});
|
||||
expect(mqtt.configs.single.clientId, 'v2_work_task');
|
||||
mqtt.status('FINISH', taskId: 8); // routeId cannot be used as taskId
|
||||
mqtt.status('FINISH', deviceId: 'other-device');
|
||||
mqtt.status('FINISH', taskId: 99, topicId: 42);
|
||||
await flush();
|
||||
expect(tracker.current('MC700-test')!.state, WorkRunState.running);
|
||||
mqtt.status('PAUSE');
|
||||
await flush();
|
||||
expect(updates.last!.state, WorkRunState.paused);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'FINISH leaves terminal snapshot, removes active ID and preserves legacy cache',
|
||||
() async {
|
||||
await tracker.load('MC700-test');
|
||||
await flush();
|
||||
mqtt.status('EXECUTING');
|
||||
mqtt.status('FINISH');
|
||||
await flush();
|
||||
expect(updates.last!.state, WorkRunState.finished);
|
||||
expect(mqtt.topics, isEmpty);
|
||||
expect(await tracker.history('MC700-test'), hasLength(1));
|
||||
expect(
|
||||
traceLogs.any((s) => s.contains('[MQTT收到]') && s.contains('FINISH')),
|
||||
isTrue,
|
||||
);
|
||||
expect(
|
||||
traceLogs.any(
|
||||
(s) =>
|
||||
s.contains('[结束消息收到]') &&
|
||||
s.contains('"source":"mqtt_status"') &&
|
||||
s.contains('task/42/status'),
|
||||
),
|
||||
isTrue,
|
||||
);
|
||||
expect(
|
||||
traceLogs.any(
|
||||
(s) =>
|
||||
s.contains('[结束状态落地]') &&
|
||||
s.contains('"removedFromActive":true') &&
|
||||
s.contains('"inHistory":true'),
|
||||
),
|
||||
isTrue,
|
||||
);
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
expect(prefs.getString('saved_device_task_ids'), '{"legacy":77}');
|
||||
final stored = await V2WorkStore('test-user').read('tasks');
|
||||
expect(stored!['current'], isEmpty);
|
||||
final reloaded = await tracker.load('MC700-test');
|
||||
expect(
|
||||
reloaded.data,
|
||||
isEmpty,
|
||||
reason: 'stale pool cannot revive a finished task',
|
||||
);
|
||||
expect(updates.last!.state, WorkRunState.finished);
|
||||
},
|
||||
);
|
||||
|
||||
test('MQTT finish wins over an earlier pending HTTP response', () async {
|
||||
await tracker.load('MC700-test');
|
||||
await flush();
|
||||
tasks.pending = Completer<Either<Failure, List<DeviceTaskEntity>>>();
|
||||
final loading = tracker.load('MC700-test');
|
||||
await flush();
|
||||
mqtt.status('FINISH');
|
||||
tasks.pending!.complete(Right([FakeTasks.entity()]));
|
||||
expect((await loading).data, isEmpty);
|
||||
expect(tracker.current('MC700-test')!.state, WorkRunState.finished);
|
||||
});
|
||||
|
||||
test(
|
||||
'arrival points accumulate only during execution and empty arrival completes',
|
||||
() async {
|
||||
await tracker.load('MC700-test');
|
||||
await flush();
|
||||
mqtt.arrive({'lat': 31.1, 'lng': 120.1});
|
||||
await flush();
|
||||
expect(tracker.current('MC700-test')!.completedPoints, hasLength(1));
|
||||
mqtt.status('PAUSE');
|
||||
mqtt.arrive({'lat': 31.2, 'lng': 120.2});
|
||||
await flush();
|
||||
expect(tracker.current('MC700-test')!.completedPoints, hasLength(1));
|
||||
mqtt.arrive(null);
|
||||
await flush();
|
||||
expect(tracker.current('MC700-test')!.state, WorkRunState.finished);
|
||||
expect(
|
||||
traceLogs.any(
|
||||
(s) =>
|
||||
s.contains('[结束消息收到]') &&
|
||||
s.contains('"source":"mqtt_arrive_empty"') &&
|
||||
s.contains('"entityPresent":true'),
|
||||
),
|
||||
isTrue,
|
||||
);
|
||||
expect(
|
||||
traceLogs.any(
|
||||
(s) => s.contains('[结束状态落地]') && s.contains('task/42/arrive'),
|
||||
),
|
||||
isTrue,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test('NEW状态延迟时接受有效到达点,保留原始状态与诊断链路', () async {
|
||||
tasks.tasks = [FakeTasks.entity(state: 'NEW')];
|
||||
await tracker.load('MC700-test');
|
||||
await flush();
|
||||
expect(
|
||||
traceLogs.any(
|
||||
(s) => s.contains('[订阅登记]') && s.contains('task/42/arrive'),
|
||||
),
|
||||
isTrue,
|
||||
);
|
||||
mqtt.arrive({'lat': 31.1, 'lng': 120.1});
|
||||
await flush();
|
||||
expect(tracker.current('MC700-test')!.completedPoints, hasLength(1));
|
||||
expect(tracker.current('MC700-test')!.rawStatus, 'NEW');
|
||||
expect(tracker.current('MC700-test')!.executionStarted, isTrue);
|
||||
expect(tracker.current('MC700-test')!.canRecordTrace, isTrue);
|
||||
expect(
|
||||
traceLogs.any(
|
||||
(s) =>
|
||||
s.contains('[MQTT收到]') &&
|
||||
s.contains('task/42/arrive') &&
|
||||
s.contains('31.1'),
|
||||
),
|
||||
isTrue,
|
||||
);
|
||||
mqtt.status('EXECUTING');
|
||||
mqtt.arrive({'lat': 31.1, 'lng': 120.1});
|
||||
mqtt.arrive({'lat': 31.2, 'lng': 120.2});
|
||||
await flush();
|
||||
expect(tracker.current('MC700-test')!.completedPoints, hasLength(2));
|
||||
expect(
|
||||
traceLogs.any((s) => s.contains('[状态收到]') && s.contains('EXECUTING')),
|
||||
isTrue,
|
||||
);
|
||||
expect(
|
||||
traceLogs.any((s) => s.contains('[轨迹追加]') && s.contains('"points":2')),
|
||||
isTrue,
|
||||
);
|
||||
expect(
|
||||
traceLogs.any(
|
||||
(s) => s.contains('[任务快照]') && s.contains('"selected":true'),
|
||||
),
|
||||
isTrue,
|
||||
);
|
||||
});
|
||||
|
||||
test('过滤日志说明 topic、ID、type、坐标和解析失败,拒绝消息不修改轨迹', () async {
|
||||
tasks.tasks = [FakeTasks.entity(state: 'NEW')];
|
||||
await tracker.load('MC700-test');
|
||||
await flush();
|
||||
final valid = {
|
||||
'type': 'device_task_arrive_point',
|
||||
'taskId': 42,
|
||||
'deviceId': 'MC700-test',
|
||||
'entity': {'lat': 31.1, 'lng': 120.1},
|
||||
};
|
||||
void send(Map<String, dynamic> data, {String topic = 'task/42/arrive'}) =>
|
||||
mqtt.messages.add(MqttMessage(topic: topic, payload: jsonEncode(data)));
|
||||
send(valid, topic: 'task/99/arrive');
|
||||
send({...valid, 'taskId': 8});
|
||||
send({...valid, 'deviceId': 'other'});
|
||||
send({...valid, 'type': 'unexpected'});
|
||||
send({
|
||||
...valid,
|
||||
'entity': {'lat': 0, 'lng': 120.1},
|
||||
});
|
||||
send({...valid, 'entity': 'not a point'});
|
||||
mqtt.messages.add(
|
||||
MqttMessage(topic: 'task/42/arrive', payload: 'invalid json'),
|
||||
);
|
||||
await flush();
|
||||
expect(tracker.current('MC700-test')!.completedPoints, isEmpty);
|
||||
expect(tracker.current('MC700-test')!.executionStarted, isFalse);
|
||||
expect(tracker.current('MC700-test')!.canRecordTrace, isFalse);
|
||||
for (final reason in [
|
||||
'topic格式不符或不在当前订阅列表',
|
||||
'消息taskId与topic任务不一致',
|
||||
'deviceId不匹配',
|
||||
'到达点type不匹配',
|
||||
'坐标为空、非数值、零或超出范围',
|
||||
'entity不是坐标对象',
|
||||
'[解析失败]',
|
||||
]) {
|
||||
expect(traceLogs.any((s) => s.contains(reason)), isTrue, reason: reason);
|
||||
}
|
||||
mqtt.arrive({'lat': 31.1, 'lng': 120.1});
|
||||
mqtt.arrive({'lat': 31.1, 'lng': 120.1});
|
||||
await flush();
|
||||
expect(tracker.current('MC700-test')!.completedPoints, hasLength(1));
|
||||
expect(traceLogs.any((s) => s.contains('与上一轨迹点重复')), isTrue);
|
||||
});
|
||||
|
||||
test('诊断采样只减少日志,连续到达点完整保留;日志写入异常也不影响轨迹', () async {
|
||||
await tracker.load('MC700-test');
|
||||
await flush();
|
||||
for (var i = 0; i < 20; i++) {
|
||||
mqtt.arrive({'lat': 31.1 + i * 0.00001, 'lng': 120.1});
|
||||
}
|
||||
await flush();
|
||||
expect(tracker.current('MC700-test')!.completedPoints, hasLength(20));
|
||||
expect(traceLogs.where((s) => s.contains('[MQTT收到]')), hasLength(1));
|
||||
failTraceLogs = true;
|
||||
mqtt.status('PAUSE');
|
||||
expect(tracker.current('MC700-test')!.state, WorkRunState.paused);
|
||||
mqtt.status('EXECUTING');
|
||||
mqtt.arrive({'lat': 31.2, 'lng': 120.2});
|
||||
await flush();
|
||||
expect(tracker.current('MC700-test')!.completedPoints, hasLength(21));
|
||||
expect(failedTraceWrites, greaterThan(0));
|
||||
});
|
||||
|
||||
test(
|
||||
'new task survives empty pool delay and a new watcher receives its state',
|
||||
() async {
|
||||
tasks.tasks = [];
|
||||
final created = await tracker.start(
|
||||
const WorkStartRequest(
|
||||
deviceId: 'MC700-test',
|
||||
route: WorkRouteOption(id: '8', name: 'route'),
|
||||
),
|
||||
);
|
||||
await flush();
|
||||
expect(created.data!.taskId, '100');
|
||||
expect(created.data!.rawStatus, 'NEW');
|
||||
expect(created.data!.executionStarted, isTrue);
|
||||
expect(created.data!.canRecordTrace, isTrue);
|
||||
expect(mqtt.topics, {'task/100/status', 'task/100/arrive'});
|
||||
final secondUpdates = <WorkTaskSnapshot?>[];
|
||||
final second = tracker.watch('MC700-test').listen(secondUpdates.add);
|
||||
await flush();
|
||||
expect(secondUpdates.single!.taskId, '100');
|
||||
await second.cancel();
|
||||
await flush();
|
||||
expect(mqtt.topics, isNotEmpty);
|
||||
expect(path.creations, 1);
|
||||
final refreshed = await tracker.load('MC700-test');
|
||||
expect(refreshed.data!.single.taskId, '100');
|
||||
expect(tracker.current('MC700-test')!.taskId, '100');
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'pause resume stop use current task ID and stop cleans subscriptions',
|
||||
() async {
|
||||
await tracker.load('MC700-test');
|
||||
await flush();
|
||||
var current = tracker.current('MC700-test')!;
|
||||
current = (await tracker.command('MC700-test', current, 'pause')).data!;
|
||||
expect(current.state, WorkRunState.paused);
|
||||
current = (await tracker.command('MC700-test', current, 'resume')).data!;
|
||||
expect(current.state, WorkRunState.running);
|
||||
current = (await tracker.command('MC700-test', current, 'cancel')).data!;
|
||||
await flush();
|
||||
expect(tasks.operatedTask, 42);
|
||||
expect(tasks.force, isTrue);
|
||||
expect(current.rawStatus, 'CANCELED');
|
||||
expect(
|
||||
traceLogs.any(
|
||||
(s) => s.contains('[结束状态落地]') && s.contains('"source":"http_cancel"'),
|
||||
),
|
||||
isTrue,
|
||||
);
|
||||
expect(traceLogs.where((s) => s.contains('[结束消息收到]')), isEmpty);
|
||||
expect(mqtt.topics, isEmpty);
|
||||
expect(
|
||||
(await tracker.command('MC700-test', current, 'resume')).isOk,
|
||||
isFalse,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test('只选中NEW任务不记录GPS,确认开始复用任务后才记录', () async {
|
||||
tasks.tasks = [FakeTasks.entity(state: 'NEW')];
|
||||
await tracker.load('MC700-test');
|
||||
final selected = await tracker.select(tracker.current('MC700-test')!);
|
||||
expect(selected.data!.canRecordTrace, isFalse);
|
||||
final started = await tracker.start(
|
||||
const WorkStartRequest(
|
||||
deviceId: 'MC700-test',
|
||||
route: WorkRouteOption(id: '8', name: 'route'),
|
||||
reuseTaskId: '42',
|
||||
),
|
||||
);
|
||||
expect(started.data!.rawStatus, 'NEW');
|
||||
expect(started.data!.executionStarted, isTrue);
|
||||
expect(started.data!.canRecordTrace, isTrue);
|
||||
expect(path.creations, 0);
|
||||
await tracker.load('MC700-test');
|
||||
expect(tracker.current('MC700-test')!.canRecordTrace, isTrue);
|
||||
});
|
||||
|
||||
test('开始标记持久化,重进页面遇到NEW也不会丢掉轨迹接收权限', () async {
|
||||
tasks.tasks = [FakeTasks.entity(state: 'NEW')];
|
||||
await tracker.load('MC700-test');
|
||||
await tracker.start(
|
||||
const WorkStartRequest(
|
||||
deviceId: 'MC700-test',
|
||||
route: WorkRouteOption(id: '8', name: 'route'),
|
||||
reuseTaskId: '42',
|
||||
),
|
||||
);
|
||||
final stored = await V2WorkStore('test-user').read('tasks');
|
||||
expect((stored!['current'] as List).single['executionStarted'], isTrue);
|
||||
await sub.cancel();
|
||||
await flush();
|
||||
tracker = V2WorkTaskTracker(
|
||||
repository: tasks,
|
||||
createTask: CreateDeviceTaskUseCase(path),
|
||||
resolveScope: (_) async => const WorkScope(siteId: 2, orgId: 3),
|
||||
userId: () => 'test-user',
|
||||
store: V2WorkStore('test-user'),
|
||||
mqtt: mqtt,
|
||||
diagnostics: WorkTraceDiagnostics(write: traceLogs.add),
|
||||
);
|
||||
sub = tracker.watch('MC700-test').listen(updates.add);
|
||||
await tracker.load('MC700-test');
|
||||
await flush();
|
||||
expect(tracker.current('MC700-test')!.rawStatus, 'NEW');
|
||||
expect(tracker.current('MC700-test')!.canRecordTrace, isTrue);
|
||||
mqtt.arrive({'lat': 31.1, 'lng': 120.1});
|
||||
expect(tracker.current('MC700-test')!.completedPoints, hasLength(1));
|
||||
});
|
||||
|
||||
for (final status in ['EXECUTING', 'PAUSE', 'FAILED']) {
|
||||
test('$status之后的延迟NEW不能回退执行状态或解除暂停', () async {
|
||||
await tracker.load('MC700-test');
|
||||
await flush();
|
||||
mqtt.status(status);
|
||||
mqtt.status('NEW');
|
||||
expect(tracker.current('MC700-test')!.rawStatus, status);
|
||||
tasks.tasks = [FakeTasks.entity(state: 'NEW')];
|
||||
await tracker.load('MC700-test');
|
||||
expect(tracker.current('MC700-test')!.rawStatus, status);
|
||||
mqtt.arrive({'lat': 31.1, 'lng': 120.1});
|
||||
expect(
|
||||
tracker.current('MC700-test')!.completedPoints,
|
||||
hasLength(status == 'EXECUTING' ? 1 : 0),
|
||||
);
|
||||
mqtt.status('EXECUTING');
|
||||
mqtt.arrive({'lat': 31.2, 'lng': 120.2});
|
||||
expect(tracker.current('MC700-test')!.canRecordTrace, isTrue);
|
||||
mqtt.status('FINISH');
|
||||
mqtt.status('NEW');
|
||||
expect(tracker.current('MC700-test')!.state, WorkRunState.finished);
|
||||
});
|
||||
}
|
||||
|
||||
test('开始、NEW到达、实时车位、暂停与结束连通,GPS不写入任务到达点', () async {
|
||||
tasks.tasks = [];
|
||||
await tracker.start(
|
||||
const WorkStartRequest(
|
||||
deviceId: 'MC700-test',
|
||||
route: WorkRouteOption(id: '8', name: 'route'),
|
||||
),
|
||||
);
|
||||
await flush();
|
||||
final trace = WorkTraceRecorder();
|
||||
void sync() {
|
||||
final current = tracker.current('MC700-test')!;
|
||||
trace.synchronize(
|
||||
deviceId: current.deviceId,
|
||||
input: WorkTraceInput(
|
||||
taskId: current.taskId,
|
||||
recording: current.canRecordTrace,
|
||||
visible: current.state != WorkRunState.finished,
|
||||
completedPoints: current.completedPoints,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
const a = LatLng(31.1, 120.1);
|
||||
const b = LatLng(31.1001, 120.1001);
|
||||
const c = LatLng(31.1002, 120.1002);
|
||||
sync();
|
||||
trace.addPosition(a);
|
||||
trace.addPosition(b);
|
||||
expect(trace.points, [a, b]);
|
||||
mqtt.arrive({'lat': b.latitude, 'lng': b.longitude}, taskId: 100);
|
||||
sync();
|
||||
trace.addPosition(c);
|
||||
expect(trace.points, [b, c]);
|
||||
expect(tracker.current('MC700-test')!.completedPoints, [b]);
|
||||
await tracker.command(
|
||||
'MC700-test',
|
||||
tracker.current('MC700-test')!,
|
||||
'pause',
|
||||
);
|
||||
mqtt.status('NEW', taskId: 100);
|
||||
sync();
|
||||
expect(trace.addPosition(a), isFalse);
|
||||
expect(trace.points, [b, c]);
|
||||
mqtt.status('FINISH', taskId: 100);
|
||||
sync();
|
||||
expect(trace.points, isEmpty);
|
||||
expect((await tracker.history('MC700-test')).single.completedPoints, [b]);
|
||||
});
|
||||
|
||||
test('failed query cannot create or erase a running task', () async {
|
||||
await tracker.load('MC700-test');
|
||||
await flush();
|
||||
tasks.error = 'offline';
|
||||
expect((await tracker.load('MC700-test')).isOk, isFalse);
|
||||
expect(tracker.current('MC700-test')!.taskId, '42');
|
||||
expect(path.creations, 0);
|
||||
});
|
||||
|
||||
test(
|
||||
'V2 draft store serializes writes and isolates users from legacy keys',
|
||||
() async {
|
||||
final store = V2WorkStore('first');
|
||||
final points = <int>[1, 2, 3];
|
||||
final first = store.write('editor/2/device', {'points': points});
|
||||
points.clear();
|
||||
await first;
|
||||
expect((await store.read('editor/2/device'))!['points'], [1, 2, 3]);
|
||||
expect(await V2WorkStore('second').read('editor/2/device'), isNull);
|
||||
await store.write('editor/2/device', null);
|
||||
expect(await store.read('editor/2/device'), isNull);
|
||||
},
|
||||
);
|
||||
test(
|
||||
'missed FINISH push is recovered from task pool with its arrival points',
|
||||
() async {
|
||||
await tracker.load('MC700-test');
|
||||
await flush();
|
||||
mqtt.arrive({'lat': 31.1, 'lng': 120.1});
|
||||
await flush();
|
||||
tasks.tasks = [FakeTasks.entity(state: 'FINISH')];
|
||||
expect((await tracker.load('MC700-test')).data, isEmpty);
|
||||
await flush();
|
||||
expect(updates.last!.rawStatus, 'FINISH');
|
||||
expect(updates.last!.completedPoints, hasLength(1));
|
||||
expect(
|
||||
traceLogs.any(
|
||||
(s) => s.contains('[结束任务池确认]') && s.contains('"source":"task_pool"'),
|
||||
),
|
||||
isTrue,
|
||||
);
|
||||
expect(
|
||||
traceLogs.any(
|
||||
(s) => s.contains('[结束状态落地]') && s.contains('"source":"task_pool"'),
|
||||
),
|
||||
isTrue,
|
||||
);
|
||||
expect(traceLogs.where((s) => s.contains('[结束消息收到]')), isEmpty);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'queue receives other task completion without replacing current task',
|
||||
() async {
|
||||
tasks.tasks = [
|
||||
FakeTasks.entity(),
|
||||
FakeTasks.entity(id: 43, state: 'NEW'),
|
||||
];
|
||||
final changes = <WorkTaskSnapshot?>[];
|
||||
final queue = tracker
|
||||
.watch('MC700-test', allTasks: true)
|
||||
.listen(changes.add);
|
||||
await tracker.load('MC700-test');
|
||||
await flush();
|
||||
mqtt.status('FINISH', taskId: 43);
|
||||
await flush();
|
||||
expect(changes.last!.taskId, '43');
|
||||
expect(changes.last!.state, WorkRunState.finished);
|
||||
expect(updates.last!.taskId, '42');
|
||||
expect(updates.last!.state, WorkRunState.running);
|
||||
expect(
|
||||
traceLogs.any(
|
||||
(s) =>
|
||||
s.contains('[结束状态落地]') &&
|
||||
s.contains('"taskId":"43"') &&
|
||||
s.contains('"selected":false'),
|
||||
),
|
||||
isTrue,
|
||||
);
|
||||
expect(mqtt.topics, {'task/42/status', 'task/42/arrive'});
|
||||
await queue.cancel();
|
||||
},
|
||||
);
|
||||
|
||||
for (final status in ['CANCELED', 'CANCELLED']) {
|
||||
test('$status结束信号独立记录并保留原有结束处理', () async {
|
||||
await tracker.load('MC700-test');
|
||||
await flush();
|
||||
mqtt.status(status);
|
||||
await flush();
|
||||
expect(tracker.current('MC700-test')!.state, WorkRunState.finished);
|
||||
expect(
|
||||
traceLogs.any((s) => s.contains('[结束消息收到]') && s.contains(status)),
|
||||
isTrue,
|
||||
);
|
||||
expect(
|
||||
traceLogs.any(
|
||||
(s) => s.contains('[结束状态落地]') && s.contains('"source":"mqtt_status"'),
|
||||
),
|
||||
isTrue,
|
||||
);
|
||||
expect(mqtt.topics, isEmpty);
|
||||
});
|
||||
}
|
||||
|
||||
test('结束消息过滤记录ID不匹配及重复原因,不重复完成任务', () async {
|
||||
await tracker.load('MC700-test');
|
||||
await flush();
|
||||
mqtt.status('FINISH', deviceId: 'other-device');
|
||||
mqtt.status('FINISH', taskId: 99, topicId: 42);
|
||||
expect(tracker.current('MC700-test')!.state, WorkRunState.running);
|
||||
expect(
|
||||
traceLogs.any((s) => s.contains('[结束消息过滤]') && s.contains('deviceId不匹配')),
|
||||
isTrue,
|
||||
);
|
||||
expect(
|
||||
traceLogs.any(
|
||||
(s) => s.contains('[结束消息过滤]') && s.contains('消息taskId与topic任务不一致'),
|
||||
),
|
||||
isTrue,
|
||||
);
|
||||
mqtt.status('FINISH');
|
||||
mqtt.status('FINISH');
|
||||
await flush();
|
||||
expect(
|
||||
traceLogs.any(
|
||||
(s) => s.contains('[结束消息过滤]') && s.contains('任务已结束,忽略重复或迟到消息'),
|
||||
),
|
||||
isTrue,
|
||||
);
|
||||
expect(traceLogs.where((s) => s.contains('[结束状态落地]')), hasLength(1));
|
||||
expect(
|
||||
updates.where((t) => t?.state == WorkRunState.finished),
|
||||
hasLength(1),
|
||||
);
|
||||
expect(await tracker.history('MC700-test'), hasLength(1));
|
||||
});
|
||||
|
||||
test('空到达点日志记录entity是否缺失,保持原有结束语义', () async {
|
||||
await tracker.load('MC700-test');
|
||||
await flush();
|
||||
mqtt.messages.add(
|
||||
MqttMessage(
|
||||
topic: 'task/42/arrive',
|
||||
payload: jsonEncode({
|
||||
'type': 'device_task_arrive_point',
|
||||
'deviceId': 'MC700-test',
|
||||
'taskId': 42,
|
||||
}),
|
||||
),
|
||||
);
|
||||
await flush();
|
||||
expect(tracker.current('MC700-test')!.state, WorkRunState.finished);
|
||||
expect(
|
||||
traceLogs.any(
|
||||
(s) => s.contains('[结束消息收到]') && s.contains('"entityPresent":false'),
|
||||
),
|
||||
isTrue,
|
||||
);
|
||||
});
|
||||
|
||||
test('未收到结束消息时定期说明等待状态,不能把消息静默当成已结束', () async {
|
||||
await tracker.load('MC700-test');
|
||||
await flush();
|
||||
expect(mqtt.isConnected, isTrue);
|
||||
// 真实异步订阅与计时器共用同一时钟,验证生产中的10秒诊断周期。
|
||||
await Future<void>.delayed(const Duration(seconds: 11));
|
||||
expect(tracker.current('MC700-test')!.state, WorkRunState.running);
|
||||
expect(
|
||||
traceLogs.any(
|
||||
(s) =>
|
||||
s.contains('[结束确认等待]') &&
|
||||
s.contains('task/42/status') &&
|
||||
s.contains('"statusReceived":0'),
|
||||
),
|
||||
isTrue,
|
||||
);
|
||||
expect(traceLogs.where((s) => s.contains('[结束状态落地]')), isEmpty);
|
||||
await sub.cancel();
|
||||
await flush();
|
||||
expect(mqtt.topics, isEmpty);
|
||||
});
|
||||
|
||||
test(
|
||||
'last page exit unsubscribes and reentry resubscribes the active task',
|
||||
() async {
|
||||
await tracker.load('MC700-test');
|
||||
await flush();
|
||||
await sub.cancel();
|
||||
await flush();
|
||||
expect(mqtt.topics, isEmpty);
|
||||
expect(mqtt.isConnected, isFalse);
|
||||
sub = tracker.watch('MC700-test').listen(updates.add);
|
||||
await tracker.load('MC700-test');
|
||||
await flush();
|
||||
expect(mqtt.topics, {'task/42/status', 'task/42/arrive'});
|
||||
mqtt.status('FINISH');
|
||||
await flush();
|
||||
expect(updates.last!.state, WorkRunState.finished);
|
||||
},
|
||||
);
|
||||
}
|
||||
542
test/work_home_task_test.dart
Normal file
542
test/work_home_task_test.dart
Normal file
@@ -0,0 +1,542 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:fpdart/fpdart.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:maibu_satabot_v2/core/app/app_user_cubit.dart';
|
||||
import 'package:maibu_satabot_v2/core/di/injection.dart';
|
||||
import 'package:maibu_satabot_v2/core/domain/entities/user_entity.dart';
|
||||
import 'package:maibu_satabot_v2/core/error/failure.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/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/entities/device_task_entity.dart';
|
||||
import 'package:maibu_satabot_v2/features/devices/domain/repositories/device_task_repository.dart';
|
||||
import 'package:maibu_satabot_v2/features/devices/domain/usecases/get_device_task_pool_usecase.dart';
|
||||
import 'package:maibu_satabot_v2/features/devices/domain/usecases/save_device_schedule_plan_usecase.dart';
|
||||
import 'package:maibu_satabot_v2/features/devices/presentation/bloc/devices_cubit.dart';
|
||||
import 'package:maibu_satabot_v2/features/devices/presentation/bloc/devices_state.dart';
|
||||
import 'package:maibu_satabot_v2/features/v2/home/domain/entities/site_entity.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/site/presentation/cubit/site_cubit.dart';
|
||||
import 'package:maibu_satabot_v2/features/v2/work/presentation/cubit/work_home_task_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/pages/work_plan_page_v2.dart';
|
||||
import 'package:maibu_satabot_v2/features/v2/work/presentation/pages/work_home_page_v2.dart';
|
||||
|
||||
class _Tasks implements DeviceTaskRepository {
|
||||
final requests = <(String, int, int)>[];
|
||||
Future<Either<Failure, List<DeviceTaskEntity>>> Function(int siteId)
|
||||
response = (_) async => const Right([]);
|
||||
|
||||
@override
|
||||
Future<Either<Failure, List<DeviceTaskEntity>>> getDeviceTaskPool({
|
||||
required String userId,
|
||||
required int siteId,
|
||||
required int orgId,
|
||||
int pageNum = 1,
|
||||
int pageSize = 99999999,
|
||||
}) {
|
||||
requests.add((userId, siteId, orgId));
|
||||
return response(siteId);
|
||||
}
|
||||
|
||||
@override
|
||||
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
|
||||
}
|
||||
|
||||
DeviceTaskEntity task(
|
||||
int id,
|
||||
String status, {
|
||||
String? device,
|
||||
int site = 18,
|
||||
int org = 6,
|
||||
}) => DeviceTaskEntity(
|
||||
id: id,
|
||||
deviceId: device ?? 'SN$id',
|
||||
taskStatus: status,
|
||||
taskStatusTranslate: '',
|
||||
siteId: site,
|
||||
orgId: org,
|
||||
routeId: 256,
|
||||
);
|
||||
|
||||
class _Devices extends Cubit<DevicesState> implements DevicesCubit {
|
||||
_Devices() : super(const DevicesState());
|
||||
@override
|
||||
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
|
||||
}
|
||||
|
||||
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 _LocaleDelegate extends LocalizationsDelegate<AppLocalizations> {
|
||||
const _LocaleDelegate(this.value);
|
||||
final AppLocalizations value;
|
||||
@override
|
||||
bool isSupported(Locale locale) => true;
|
||||
@override
|
||||
Future<AppLocalizations> load(Locale locale) => SynchronousFuture(value);
|
||||
@override
|
||||
bool shouldReload(_LocaleDelegate old) => old.value != value;
|
||||
}
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
group('场站任务池状态', () {
|
||||
late _Tasks repository;
|
||||
late WorkHomeTaskCubit cubit;
|
||||
setUp(() {
|
||||
repository = _Tasks();
|
||||
cubit = WorkHomeTaskCubit(GetDeviceTaskPoolUseCase(repository));
|
||||
});
|
||||
tearDown(() => cubit.close());
|
||||
|
||||
test('单次查询包含整个场站设备,排除终态/跨场站/重复记录并按状态排序', () async {
|
||||
repository.response = (_) async => Right([
|
||||
task(1, 'NEW'),
|
||||
task(2, 'EXECUTING'),
|
||||
task(3, 'PAUSE'),
|
||||
task(4, 'FAILED'),
|
||||
task(5, 'CANCELING'),
|
||||
task(6, 'FINISH'),
|
||||
task(7, 'CANCELED'),
|
||||
task(8, 'CANCELLED'),
|
||||
task(9, 'EXECUTING', site: 99),
|
||||
task(10, 'NEW', org: 99),
|
||||
task(2, 'EXECUTING'),
|
||||
task(11, ' new '),
|
||||
]);
|
||||
await cubit.load(userId: 'u1', siteId: 18, orgId: 6);
|
||||
expect(repository.requests, [('u1', 18, 6)]);
|
||||
expect(cubit.state.status, WorkHomeTaskStatus.ready);
|
||||
expect(cubit.state.tasks.map((t) => t.id), [2, 3, 4, 5, 11, 1]);
|
||||
expect(cubit.state.runningCount, 1);
|
||||
expect(cubit.state.pendingCount, 2);
|
||||
});
|
||||
|
||||
test('切换场站立即清除旧数据,忽略迟到的旧场站响应', () async {
|
||||
final oldResponse = Completer<Either<Failure, List<DeviceTaskEntity>>>();
|
||||
repository.response = (site) => site == 18
|
||||
? oldResponse.future
|
||||
: Future.value(Right([task(20, 'NEW', site: 19)]));
|
||||
final old = cubit.load(userId: 'u1', siteId: 18, orgId: 6);
|
||||
final current = cubit.load(userId: 'u1', siteId: 19, orgId: 6);
|
||||
expect(cubit.state.tasks, isEmpty);
|
||||
await current;
|
||||
oldResponse.complete(Right([task(1, 'EXECUTING')]));
|
||||
await old;
|
||||
expect(cubit.state.tasks.single.id, 20);
|
||||
expect(cubit.state.pendingCount, 1);
|
||||
expect(cubit.state.runningCount, 0);
|
||||
});
|
||||
|
||||
test('并发刷新复用同一请求,退出登录后不回填旧任务', () async {
|
||||
final response = Completer<Either<Failure, List<DeviceTaskEntity>>>();
|
||||
repository.response = (_) => response.future;
|
||||
final first = cubit.load(userId: 'u1', siteId: 18, orgId: 6);
|
||||
final second = cubit.load(userId: 'u1', siteId: 18, orgId: 6);
|
||||
expect(repository.requests, hasLength(1));
|
||||
await cubit.load(userId: null, siteId: 18, orgId: 6);
|
||||
response.complete(Right([task(1, 'EXECUTING')]));
|
||||
await Future.wait([first, second]);
|
||||
expect(cubit.state.status, WorkHomeTaskStatus.noUser);
|
||||
expect(cubit.state.tasks, isEmpty);
|
||||
});
|
||||
|
||||
test('未选择场站不发送请求,接口失败可重试,空列表才显示真实的零', () async {
|
||||
await cubit.load(userId: 'u1', siteId: null, orgId: null);
|
||||
expect(repository.requests, isEmpty);
|
||||
expect(cubit.state.status, WorkHomeTaskStatus.noSite);
|
||||
repository.response = (_) async => Left(Failure('网络失败'));
|
||||
await cubit.load(userId: 'u1', siteId: 18, orgId: 6);
|
||||
expect(cubit.state.status, WorkHomeTaskStatus.failure);
|
||||
repository.response = (_) async => const Right([]);
|
||||
await cubit.load(userId: 'u1', siteId: 18, orgId: 6);
|
||||
expect(cubit.state.status, WorkHomeTaskStatus.ready);
|
||||
expect(cubit.state.runningCount, 0);
|
||||
expect(cubit.state.pendingCount, 0);
|
||||
});
|
||||
|
||||
test('同场站刷新保留内容,相同任务的新对象或返回顺序变化均不通知渲染', () async {
|
||||
repository.response = (_) async =>
|
||||
Right([task(1, 'NEW'), task(2, 'EXECUTING')]);
|
||||
await cubit.load(userId: 'u1', siteId: 18, orgId: 6);
|
||||
final original = cubit.state;
|
||||
final events = <WorkHomeTaskState>[];
|
||||
final subscription = cubit.stream.listen(events.add);
|
||||
addTearDown(subscription.cancel);
|
||||
final response = Completer<Either<Failure, List<DeviceTaskEntity>>>();
|
||||
repository.response = (_) => response.future;
|
||||
final refresh = cubit.load(userId: 'u1', siteId: 18, orgId: 6);
|
||||
expect(identical(cubit.state, original), isTrue);
|
||||
response.complete(Right([task(2, 'EXECUTING'), task(1, 'NEW')]));
|
||||
await refresh;
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
expect(identical(cubit.state, original), isTrue);
|
||||
expect(events, isEmpty);
|
||||
});
|
||||
|
||||
test('任务内容变化只发布一次 ready,真实空列表也能替换旧任务', () async {
|
||||
repository.response = (_) async => Right([task(1, 'NEW')]);
|
||||
await cubit.load(userId: 'u1', siteId: 18, orgId: 6);
|
||||
final events = <WorkHomeTaskState>[];
|
||||
final subscription = cubit.stream.listen(events.add);
|
||||
addTearDown(subscription.cancel);
|
||||
repository.response = (_) async => Right([task(1, 'EXECUTING')]);
|
||||
await cubit.load(userId: 'u1', siteId: 18, orgId: 6);
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
expect(events.map((s) => s.status), [WorkHomeTaskStatus.ready]);
|
||||
expect(cubit.state.runningCount, 1);
|
||||
expect(cubit.state.pendingCount, 0);
|
||||
repository.response = (_) async => const Right([]);
|
||||
await cubit.load(userId: 'u1', siteId: 18, orgId: 6);
|
||||
expect(cubit.state.tasks, isEmpty);
|
||||
expect(cubit.state.runningCount, 0);
|
||||
});
|
||||
|
||||
test('刷新失败保留上次任务和计数,成功后清除刷新错误', () async {
|
||||
repository.response = (_) async => Right([task(1, 'EXECUTING')]);
|
||||
await cubit.load(userId: 'u1', siteId: 18, orgId: 6);
|
||||
repository.response = (_) async => Left(Failure('临时断网'));
|
||||
await cubit.load(userId: 'u1', siteId: 18, orgId: 6);
|
||||
expect(cubit.state.status, WorkHomeTaskStatus.ready);
|
||||
expect(cubit.state.runningCount, 1);
|
||||
expect(cubit.state.tasks.single.id, 1);
|
||||
expect(cubit.state.error, '临时断网');
|
||||
repository.response = (_) async => Right([task(1, 'EXECUTING')]);
|
||||
await cubit.load(userId: 'u1', siteId: 18, orgId: 6);
|
||||
expect(cubit.state.error, isNull);
|
||||
});
|
||||
|
||||
test('已有数据时切换账号仍立即清除任务,忽略旧账号刷新结果', () async {
|
||||
repository.response = (_) async => Right([task(1, 'EXECUTING')]);
|
||||
await cubit.load(userId: 'u1', siteId: 18, orgId: 6);
|
||||
final old = Completer<Either<Failure, List<DeviceTaskEntity>>>();
|
||||
repository.response = (_) => old.future;
|
||||
final refresh = cubit.load(userId: 'u1', siteId: 18, orgId: 6);
|
||||
repository.response = (_) async => const Right([]);
|
||||
final switched = cubit.load(userId: 'u2', siteId: 18, orgId: 6);
|
||||
expect(cubit.state.status, WorkHomeTaskStatus.loading);
|
||||
expect(cubit.state.tasks, isEmpty);
|
||||
await switched;
|
||||
old.complete(Right([task(1, 'EXECUTING')]));
|
||||
await refresh;
|
||||
expect(cubit.state.status, WorkHomeTaskStatus.ready);
|
||||
expect(cubit.state.tasks, isEmpty);
|
||||
});
|
||||
});
|
||||
|
||||
group('作业首页真实查询链路', () {
|
||||
late Dio dio;
|
||||
late SiteCubit sites;
|
||||
late AppUserCubit users;
|
||||
late _Devices devices;
|
||||
late List<RequestOptions> requests;
|
||||
late Map<String, dynamic> response;
|
||||
|
||||
setUp(() async {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
sites = SiteCubit(await SharedPreferences.getInstance());
|
||||
sites.updateSites(const [
|
||||
SiteEntity(id: 18, siteName: '测试场站', orgId: 6, status: 0),
|
||||
]);
|
||||
users = AppUserCubit()
|
||||
..setAuth(
|
||||
const UserEntity(
|
||||
userId: 'u1',
|
||||
username: 'test',
|
||||
nickname: '',
|
||||
token: 'test',
|
||||
orgId: 999,
|
||||
),
|
||||
);
|
||||
devices = _Devices();
|
||||
requests = [];
|
||||
response = {
|
||||
'code': 200,
|
||||
'rows': [
|
||||
for (final t in [
|
||||
task(1, 'EXECUTING'),
|
||||
task(2, 'NEW'),
|
||||
task(3, 'PAUSE'),
|
||||
task(4, 'FAILED'),
|
||||
task(5, 'FINISH'),
|
||||
])
|
||||
{
|
||||
'id': t.id,
|
||||
'deviceId': t.deviceId,
|
||||
'routeId': t.routeId,
|
||||
'siteId': 18,
|
||||
'orgId': 6,
|
||||
if (t.id == 2)
|
||||
'taskStatus': t.taskStatus
|
||||
else
|
||||
'taskStaus': t.taskStatus,
|
||||
},
|
||||
],
|
||||
};
|
||||
dio = Dio()
|
||||
..interceptors.add(
|
||||
InterceptorsWrapper(
|
||||
onRequest: (options, handler) {
|
||||
requests.add(options);
|
||||
handler.resolve(
|
||||
Response(
|
||||
requestOptions: options,
|
||||
statusCode: 200,
|
||||
data: options.method == 'GET'
|
||||
? {
|
||||
'code': 200,
|
||||
'rows': [
|
||||
{'deviceName': 'SN1', 'deviceId': 'robot-1'},
|
||||
],
|
||||
}
|
||||
: response,
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
sl.registerSingleton<SiteCubit>(sites);
|
||||
sl.registerSingleton<AppUserCubit>(users);
|
||||
sl.registerSingleton<DevicesCubit>(devices);
|
||||
sl.registerSingleton<ILoggerService>(_Logger());
|
||||
sl.registerFactory<RobotListBloc>(() => RobotListBloc(dio));
|
||||
sl.registerFactory<SchedulePlanCreateCubit>(
|
||||
() => SchedulePlanCreateCubit(
|
||||
SaveDeviceSchedulePlanUseCase(
|
||||
DeviceTaskRepositoryImpl(datasource: DeviceTaskDatasourceImpl(dio)),
|
||||
),
|
||||
),
|
||||
);
|
||||
sl.registerFactory<WorkHomeTaskCubit>(
|
||||
() => WorkHomeTaskCubit(
|
||||
GetDeviceTaskPoolUseCase(
|
||||
DeviceTaskRepositoryImpl(datasource: DeviceTaskDatasourceImpl(dio)),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
tearDown(() async {
|
||||
await sites.close();
|
||||
await users.close();
|
||||
await devices.close();
|
||||
dio.close();
|
||||
await sl.reset();
|
||||
});
|
||||
|
||||
Future<void> mount(WidgetTester tester, {bool active = true}) async {
|
||||
final l10n = await tester.runAsync(() async {
|
||||
final l10n = AppLocalizations(const Locale('zh', 'CN'));
|
||||
await l10n.load();
|
||||
return l10n;
|
||||
});
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
localizationsDelegates: [_LocaleDelegate(l10n!)],
|
||||
home: WorkHomePageV2(isActive: active),
|
||||
),
|
||||
);
|
||||
addTearDown(() async {
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
await tester.pump();
|
||||
});
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
String stat(WidgetTester tester, String label) =>
|
||||
tester.widget<Text>(find.byKey(ValueKey('work_stat_$label'))).data!;
|
||||
|
||||
testWidgets('20秒轮询无变化不重建页面,有任务变化才更新统计', (tester) async {
|
||||
tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
|
||||
await mount(tester);
|
||||
final original = tester.widget(
|
||||
find.byKey(const ValueKey('work_task_SN1_1')),
|
||||
);
|
||||
await tester.pump(const Duration(seconds: 20));
|
||||
await tester.pumpAndSettle();
|
||||
expect(requests, hasLength(2));
|
||||
expect(
|
||||
identical(
|
||||
tester.widget(find.byKey(const ValueKey('work_task_SN1_1'))),
|
||||
original,
|
||||
),
|
||||
isTrue,
|
||||
);
|
||||
expect(find.byType(CircularProgressIndicator), findsNothing);
|
||||
response = {'code': 200, 'rows': []};
|
||||
await tester.pump(const Duration(seconds: 20));
|
||||
await tester.pumpAndSettle();
|
||||
expect(requests, hasLength(3));
|
||||
expect(stat(tester, '执行中'), '0');
|
||||
expect(find.text('暂无作业'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('轮询失败保留任务与统计,用图标提示错误;恢复后移除提示', (tester) async {
|
||||
tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
|
||||
await mount(tester);
|
||||
response = {'code': 500, 'msg': '任务池暂时不可用'};
|
||||
await tester.pump(const Duration(seconds: 20));
|
||||
await tester.pumpAndSettle();
|
||||
expect(stat(tester, '执行中'), '1');
|
||||
expect(find.text('任务 #1'), findsOneWidget);
|
||||
expect(find.byKey(const ValueKey('work_refresh_error')), findsOneWidget);
|
||||
expect(find.text('任务加载失败'), findsNothing);
|
||||
response = {'code': 200, 'rows': []};
|
||||
await tester.pump(const Duration(seconds: 20));
|
||||
await tester.pumpAndSettle();
|
||||
expect(stat(tester, '执行中'), '0');
|
||||
expect(find.byKey(const ValueKey('work_refresh_error')), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('下发作业计划直接进入新建页,保留原列表页但不经过它', (tester) async {
|
||||
await mount(tester);
|
||||
await tester.ensureVisible(find.text('下发作业计划'));
|
||||
await tester.tap(find.text('下发作业计划'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byType(WorkPlanCreatePageV2), findsOneWidget);
|
||||
expect(find.byType(WorkPlanPageV2), findsNothing);
|
||||
expect(tester.takeException(), isNull);
|
||||
});
|
||||
|
||||
testWidgets('按当前用户和场站组织查询,统计和所有任务来自同一返回列表', (tester) async {
|
||||
await mount(tester);
|
||||
expect(requests, hasLength(1));
|
||||
expect(requests.single.method, 'POST');
|
||||
expect(requests.single.uri.path, '/iot/deviceTask/deviceTaskPool');
|
||||
expect(requests.single.data, {
|
||||
'userId': 'u1',
|
||||
'siteId': 18,
|
||||
'orgId': 6,
|
||||
'pageNum': 1,
|
||||
'pageSize': 99999999,
|
||||
});
|
||||
expect(stat(tester, '执行中'), '1');
|
||||
expect(stat(tester, '待执行'), '1');
|
||||
expect(stat(tester, '今日已完成'), '—');
|
||||
expect(find.text('任务 #1'), findsOneWidget);
|
||||
expect(find.text('任务 #3'), findsOneWidget);
|
||||
expect(find.text('任务 #5'), findsNothing);
|
||||
expect(find.text('68%'), findsNothing);
|
||||
await tester.ensureVisible(find.text('全部任务'));
|
||||
await tester.tap(find.text('全部任务'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('执行设备:SN2'), findsOneWidget);
|
||||
expect(find.text('任务 #5'), findsNothing);
|
||||
expect(requests, hasLength(1));
|
||||
expect(tester.takeException(), isNull);
|
||||
});
|
||||
|
||||
testWidgets('点待执行统计只显示 NEW 任务,失败/暂停不混入', (tester) async {
|
||||
await mount(tester);
|
||||
await tester.tap(find.text('待执行'));
|
||||
await tester.pumpAndSettle();
|
||||
final sheet = find.byType(BottomSheet);
|
||||
expect(
|
||||
find.descendant(of: sheet, matching: find.text('任务 #2')),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(
|
||||
find.descendant(of: sheet, matching: find.text('任务 #3')),
|
||||
findsNothing,
|
||||
);
|
||||
expect(tester.takeException(), isNull);
|
||||
});
|
||||
|
||||
testWidgets('任务设备不在场站列表时提示,不误用列表中的第一台设备', (tester) async {
|
||||
await mount(tester);
|
||||
await tester.tap(find.text('待执行'));
|
||||
await tester.pumpAndSettle();
|
||||
final card = find.byKey(const ValueKey('work_task_SN2_2'));
|
||||
final button = find.descendant(of: card, matching: find.text('查看任务'));
|
||||
await tester.ensureVisible(button);
|
||||
await tester.tap(button);
|
||||
await tester.pumpAndSettle();
|
||||
expect(requests.last.method, 'GET');
|
||||
expect(requests.last.queryParameters['siteId'], 18);
|
||||
expect(find.text('当前场站设备列表中未找到对应设备'), findsOneWidget);
|
||||
expect(find.byType(RobotAutonomousWorkPageV2), findsNothing);
|
||||
expect(tester.takeException(), isNull);
|
||||
await tester.pump(const Duration(seconds: 3));
|
||||
});
|
||||
|
||||
testWidgets('请求失败显示重试,成功空列表显示零和空态', (tester) async {
|
||||
response = {'code': 500, 'msg': '任务池不可用'};
|
||||
await mount(tester);
|
||||
expect(stat(tester, '执行中'), '—');
|
||||
expect(find.text('任务加载失败'), findsOneWidget);
|
||||
response = {'code': 200, 'rows': []};
|
||||
await tester.ensureVisible(find.text('重新加载'));
|
||||
await tester.tap(find.text('重新加载'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(stat(tester, '执行中'), '0');
|
||||
expect(stat(tester, '待执行'), '0');
|
||||
expect(find.text('暂无作业'), findsOneWidget);
|
||||
expect(requests, hasLength(2));
|
||||
});
|
||||
|
||||
testWidgets('切换场站触发新查询,返回列表替换旧任务', (tester) async {
|
||||
await mount(tester);
|
||||
response = {
|
||||
'code': 200,
|
||||
'rows': [
|
||||
{
|
||||
'id': 10,
|
||||
'deviceId': 'other',
|
||||
'taskStaus': 'NEW',
|
||||
'siteId': 19,
|
||||
'orgId': 7,
|
||||
},
|
||||
],
|
||||
};
|
||||
sites.updateSites(const [
|
||||
SiteEntity(id: 19, siteName: '另一场站', orgId: 7, status: 0),
|
||||
]);
|
||||
await tester.pumpAndSettle();
|
||||
expect(requests, hasLength(2));
|
||||
expect(requests.last.data['siteId'], 19);
|
||||
expect(requests.last.data['orgId'], 7);
|
||||
expect(stat(tester, '执行中'), '0');
|
||||
expect(find.text('任务 #1'), findsNothing);
|
||||
expect(find.text('任务 #10'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('非当前 tab 不查询,激活后加载;退出登录清空任务', (tester) async {
|
||||
await mount(tester, active: false);
|
||||
expect(requests, isEmpty);
|
||||
final app = tester.widget<MaterialApp>(find.byType(MaterialApp));
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
localizationsDelegates: app.localizationsDelegates,
|
||||
home: const WorkHomePageV2(isActive: true),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
expect(requests, hasLength(1));
|
||||
users.clearAuth();
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('任务 #1'), findsNothing);
|
||||
expect(find.text('请先登录后查看作业任务'), findsOneWidget);
|
||||
expect(stat(tester, '执行中'), '—');
|
||||
expect(requests, hasLength(1));
|
||||
});
|
||||
});
|
||||
}
|
||||
691
test/work_plan_route_picker_test.dart
Normal file
691
test/work_plan_route_picker_test.dart
Normal file
@@ -0,0 +1,691 @@
|
||||
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 = <int>[];
|
||||
final started = <WorkStartRequest>[];
|
||||
@override
|
||||
Future<WorkResult<WorkTaskSnapshot>> startWork(
|
||||
WorkStartRequest request,
|
||||
) async {
|
||||
started.add(request);
|
||||
throw StateError('立即下发入口不应启动任务');
|
||||
}
|
||||
|
||||
Future<WorkResult<List<WorkRouteOption>>> Function() load = () async =>
|
||||
WorkResult.ok([const WorkRouteOption(id: '8', name: '测试作业路线')]);
|
||||
|
||||
@override
|
||||
Future<WorkScope> resolveScope({required String deviceId}) async =>
|
||||
WorkScope(siteId: siteId);
|
||||
|
||||
@override
|
||||
Future<WorkResult<List<WorkRouteOption>>> loadRoutes({required int siteId}) {
|
||||
requestedSites.add(siteId);
|
||||
return load();
|
||||
}
|
||||
|
||||
@override
|
||||
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
|
||||
}
|
||||
|
||||
class _NavigationObserver extends NavigatorObserver {
|
||||
final pushes = <Route<dynamic>>[];
|
||||
@override
|
||||
void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
|
||||
super.didPush(route, previousRoute);
|
||||
pushes.add(route);
|
||||
}
|
||||
}
|
||||
|
||||
class _TestLogger implements ILoggerService {
|
||||
final messages = <String>[];
|
||||
|
||||
@override
|
||||
void logWithLevel(
|
||||
String message, {
|
||||
String level = 'INFO',
|
||||
Map<String, dynamic>? data,
|
||||
bool shouldLog = false,
|
||||
}) {
|
||||
if (shouldLog) messages.add(message);
|
||||
}
|
||||
|
||||
@override
|
||||
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
|
||||
}
|
||||
|
||||
// 同步提供本地化依赖,避免资产读取影响弹窗生命周期测试。
|
||||
class _TestLocalizationsDelegate
|
||||
extends LocalizationsDelegate<AppLocalizations> {
|
||||
const _TestLocalizationsDelegate([this.localizations]);
|
||||
|
||||
final AppLocalizations? localizations;
|
||||
|
||||
@override
|
||||
bool isSupported(Locale locale) => true;
|
||||
|
||||
@override
|
||||
Future<AppLocalizations> 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<RequestOptions> saveRequests;
|
||||
late Future<Map<String, dynamic>> 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>(siteCubit);
|
||||
sl.registerSingleton<AutonomousWorkGateway>(gateway);
|
||||
sl.registerSingleton<ILoggerService>(logger);
|
||||
sl.registerFactory<RobotListBloc>(() => RobotListBloc(dio));
|
||||
sl.registerFactory<SchedulePlanCreateCubit>(
|
||||
() => SchedulePlanCreateCubit(
|
||||
SaveDeviceSchedulePlanUseCase(
|
||||
DeviceTaskRepositoryImpl(datasource: DeviceTaskDatasourceImpl(dio)),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
await siteCubit.close();
|
||||
dio.close();
|
||||
await sl.reset();
|
||||
});
|
||||
|
||||
Future<void> 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<void> 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<void> 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<void> submit(WidgetTester tester) async {
|
||||
final button = find.text('work_v2.plan_create.submit');
|
||||
await tester.ensureVisible(button);
|
||||
await tester.tap(button);
|
||||
}
|
||||
|
||||
Future<void> 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 = <MethodCall>[];
|
||||
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<FilledButton>(button).onPressed!;
|
||||
await tester.tap(button);
|
||||
queuedSubmit(); // 模拟已排队的第二次点击,不能再推入一个作业中心。
|
||||
expect(navigation.pushes, hasLength(pushed + 1));
|
||||
final pageRoute = navigation.pushes.last as MaterialPageRoute<void>;
|
||||
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<void> capturePreview(WidgetTester tester, String name) async {
|
||||
if (!const bool.fromEnvironment('CAPTURE_WORK_PLAN')) return;
|
||||
final boundary = tester.renderObject<RenderRepaintBoundary>(
|
||||
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<WorkResult<List<WorkRouteOption>>>();
|
||||
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(<WorkRouteOption>[]);
|
||||
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<Map<String, dynamic>>();
|
||||
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<FilledButton>(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<FilledButton>(
|
||||
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);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
139
test/work_trace_recorder_test.dart
Normal file
139
test/work_trace_recorder_test.dart
Normal file
@@ -0,0 +1,139 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:latlong2/latlong.dart';
|
||||
import 'package:maibu_satabot_v2/features/pv_control/presentation/models/work_trace_recorder.dart';
|
||||
|
||||
void main() {
|
||||
const a = LatLng(31.1, 120.1);
|
||||
const b = LatLng(31.1001, 120.1001);
|
||||
const c = LatLng(31.1002, 120.1002);
|
||||
const d = LatLng(31.1003, 120.1003);
|
||||
late WorkTraceRecorder recorder;
|
||||
|
||||
void sync({
|
||||
String device = 'device',
|
||||
String? task = '42',
|
||||
bool recording = true,
|
||||
bool visible = true,
|
||||
List<LatLng> completed = const [],
|
||||
}) {
|
||||
recorder.synchronize(
|
||||
deviceId: device,
|
||||
input: WorkTraceInput(
|
||||
taskId: task,
|
||||
recording: recording,
|
||||
visible: visible,
|
||||
completedPoints: completed,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
setUp(() => recorder = WorkTraceRecorder());
|
||||
|
||||
test('未开始、无设备或无任务时不累计定位', () {
|
||||
sync(recording: false);
|
||||
expect(recorder.addPosition(a), isFalse);
|
||||
for (final input in [
|
||||
const WorkTraceInput(taskId: '42', recording: true, visible: false),
|
||||
const WorkTraceInput(taskId: null, recording: true, visible: true),
|
||||
]) {
|
||||
recorder.synchronize(deviceId: 'device', input: input);
|
||||
expect(recorder.addPosition(a), isFalse);
|
||||
expect(recorder.points, isEmpty);
|
||||
}
|
||||
sync(device: '');
|
||||
expect(recorder.addPosition(a), isFalse);
|
||||
});
|
||||
|
||||
test('首个到达点之前按定位累计,两个有效位置即可画线', () {
|
||||
sync();
|
||||
expect(recorder.addPosition(a), isTrue);
|
||||
expect(recorder.addPosition(b), isTrue);
|
||||
expect(recorder.addPosition(b), isFalse);
|
||||
expect(recorder.points, [a, b]);
|
||||
expect(recorder.hasCompletedPoints, isFalse);
|
||||
});
|
||||
|
||||
test('首个到达点切换为到达点加最新车位,不保留之前的GPS折线', () {
|
||||
sync();
|
||||
recorder.addPosition(a);
|
||||
recorder.addPosition(b);
|
||||
sync(completed: [a]);
|
||||
expect(recorder.hasCompletedPoints, isTrue);
|
||||
expect(recorder.points, [a, b]);
|
||||
recorder.addPosition(c);
|
||||
recorder.addPosition(d);
|
||||
expect(recorder.points, [a, d]);
|
||||
});
|
||||
|
||||
test('仅收到一个到达点时,下一次定位就能组成绿色线段', () {
|
||||
sync(completed: [a]);
|
||||
expect(recorder.points, [a]);
|
||||
recorder.addPosition(b);
|
||||
expect(recorder.points, [a, b]);
|
||||
});
|
||||
|
||||
test('新到达点替代实时尾点,重合坐标不产生重复尾点', () {
|
||||
sync(completed: [a]);
|
||||
recorder.addPosition(b);
|
||||
sync(completed: [a, b]);
|
||||
expect(recorder.points, [a, b]);
|
||||
recorder.addPosition(c);
|
||||
expect(recorder.points, [a, b, c]);
|
||||
expect(recorder.addPosition(c), isFalse);
|
||||
});
|
||||
|
||||
test('暂停冻结尾点,恢复后接入当前位置', () {
|
||||
sync(completed: [a]);
|
||||
recorder.addPosition(b);
|
||||
sync(recording: false, completed: [a]);
|
||||
expect(recorder.addPosition(c), isFalse);
|
||||
expect(recorder.points, [a, b]);
|
||||
sync(completed: [a]);
|
||||
expect(recorder.addPosition(c), isTrue);
|
||||
expect(recorder.points, [a, c]);
|
||||
});
|
||||
|
||||
test('结束隐藏并清空,不能带着旧GPS开始下一次记录', () {
|
||||
sync();
|
||||
recorder.addPosition(a);
|
||||
recorder.addPosition(b);
|
||||
sync(visible: false, recording: false, completed: [a]);
|
||||
expect(recorder.points, isEmpty);
|
||||
sync();
|
||||
recorder.addPosition(c);
|
||||
expect(recorder.points, [c]);
|
||||
});
|
||||
|
||||
test('切换任务或设备清理之前的GPS和到达点', () {
|
||||
sync(completed: [a]);
|
||||
recorder.addPosition(b);
|
||||
sync(task: '43');
|
||||
expect(recorder.points, isEmpty);
|
||||
recorder.addPosition(c);
|
||||
sync(device: 'other-device', task: '43');
|
||||
recorder.addPosition(d);
|
||||
expect(recorder.points, [d]);
|
||||
});
|
||||
|
||||
test('GPS轨迹限制长度并忽略小于阈值的抖动', () {
|
||||
recorder = WorkTraceRecorder(maxGpsPoints: 2);
|
||||
sync();
|
||||
recorder.addPosition(a);
|
||||
expect(recorder.addPosition(const LatLng(31.1000001, 120.1)), isFalse);
|
||||
recorder.addPosition(b);
|
||||
recorder.addPosition(c);
|
||||
expect(recorder.points, [b, c]);
|
||||
});
|
||||
|
||||
test('过滤无效坐标并复制输入,外部不能更改已记录的轨迹', () {
|
||||
final completed = [a, a, const LatLng(0, 120), b];
|
||||
sync(completed: completed);
|
||||
completed.clear();
|
||||
expect(recorder.points, [a, b]);
|
||||
expect(recorder.addPosition(const LatLng(31, 0)), isFalse);
|
||||
expect(() => recorder.points.add(c), throwsUnsupportedError);
|
||||
recorder.reset();
|
||||
expect(recorder.points, isEmpty);
|
||||
expect(recorder.addPosition(c), isFalse);
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user