接入设备故障告警和场站实时任务进度
This commit is contained in:
701
test/device_alarms_test.dart
Normal file
701
test/device_alarms_test.dart
Normal file
@@ -0,0 +1,701 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_localizations/flutter_localizations.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
import 'package:maibu_satabot_v2/core/theme/AppTheme.dart';
|
||||
import 'package:maibu_satabot_v2/features/v2/waring_center/presentation/widgets/alarm_item_card.dart';
|
||||
import 'package:maibu_satabot_v2/features/v2/waring_center/data/datasources/impl/alarm_remote_datasource_impl.dart';
|
||||
import 'package:maibu_satabot_v2/features/v2/waring_center/data/repositories/alarm_repository_impl.dart';
|
||||
import 'package:maibu_satabot_v2/features/v2/waring_center/domain/usecases/get_alarm_list_usecase.dart';
|
||||
import 'package:maibu_satabot_v2/features/v2/waring_center/presentation/constants/alarm_constants.dart';
|
||||
import 'package:maibu_satabot_v2/features/device_alarms/presentation/cubit/device_alarm_history_cubit.dart';
|
||||
import 'package:maibu_satabot_v2/core/env/env_config.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_message.dart';
|
||||
import 'package:maibu_satabot_v2/features/device_alarms/data/datasources/device_alarm_mqtt_datasource.dart';
|
||||
import 'package:maibu_satabot_v2/features/device_alarms/data/datasources/device_alarm_remote_datasource.dart';
|
||||
import 'package:maibu_satabot_v2/features/device_alarms/data/repositories/device_alarm_repository_impl.dart';
|
||||
import 'package:maibu_satabot_v2/features/device_alarms/domain/usecases/device_alarm_usecases.dart';
|
||||
import 'package:maibu_satabot_v2/features/device_alarms/domain/usecases/load_site_alarm_targets_usecase.dart';
|
||||
import 'package:maibu_satabot_v2/features/device_alarms/presentation/cubit/device_alarms_cubit.dart';
|
||||
import 'package:maibu_satabot_v2/features/device_alarms/presentation/widgets/device_alarm_dialog.dart';
|
||||
import 'package:maibu_satabot_v2/features/device_alarms/presentation/widgets/device_alarm_history_tab.dart';
|
||||
import 'package:maibu_satabot_v2/features/device_alarms/presentation/widgets/device_alarm_section.dart';
|
||||
import 'package:maibu_satabot_v2/features/device_alarms/presentation/widgets/device_alarm_summary_card.dart';
|
||||
import 'package:maibu_satabot_v2/features/device_alarms/presentation/widgets/site_alarm_button.dart';
|
||||
import 'package:maibu_satabot_v2/features/v2/device_list/domain/entities/device_entity.dart';
|
||||
import 'package:maibu_satabot_v2/features/v2/device_list/domain/repositories/device_repository.dart';
|
||||
import 'package:maibu_satabot_v2/features/v2/device_list/domain/usecases/get_site_devices_usecase.dart';
|
||||
import 'package:maibu_satabot_v2/core/localization/app_localizations.dart';
|
||||
|
||||
import 'support/region_test_localizations.dart';
|
||||
|
||||
DeviceEntity _vehicle(String sn, {int siteId = 1, bool isRobot = true}) =>
|
||||
DeviceEntity(
|
||||
deviceId: 'DATABASE-ID-$sn',
|
||||
name: sn,
|
||||
type: 'robot',
|
||||
status: '离线',
|
||||
power: 0,
|
||||
todayEnergy: 0,
|
||||
isRobot: isRobot,
|
||||
siteId: siteId,
|
||||
);
|
||||
|
||||
class _Devices implements DeviceRepository {
|
||||
final rows = <int, List<DeviceEntity>>{
|
||||
1: [_vehicle('DEVICE-A')],
|
||||
2: [_vehicle('DEVICE-B', siteId: 2)],
|
||||
3: [_vehicle('DEVICE-C', siteId: 3)],
|
||||
};
|
||||
final pending = <int, Completer<List<DeviceEntity>>>{};
|
||||
final started = <int, Completer<void>>{};
|
||||
|
||||
@override
|
||||
Future<List<DeviceEntity>> getSiteDevices(int siteId) {
|
||||
final signal = started.putIfAbsent(siteId, () => Completer<void>());
|
||||
if (!signal.isCompleted) signal.complete();
|
||||
return pending[siteId]?.future ?? Future.value(rows[siteId] ?? []);
|
||||
}
|
||||
|
||||
@override
|
||||
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
|
||||
}
|
||||
|
||||
class _MqttClient implements MqttClient {
|
||||
@override
|
||||
bool get isConnected => true;
|
||||
|
||||
final messages = StreamController<MqttMessage>.broadcast(sync: true);
|
||||
final subscribed = <String>[];
|
||||
final unsubscribed = <String>[];
|
||||
|
||||
@override
|
||||
Stream<MqttMessage> get messageStream => messages.stream;
|
||||
|
||||
@override
|
||||
Future<void> subscribe(String topic) async => subscribed.add(topic);
|
||||
|
||||
@override
|
||||
Future<void> unsubscribe(String topic) async => unsubscribed.add(topic);
|
||||
|
||||
void push(List<Map<String, dynamic>> alarms, {String device = 'DEVICE-A'}) {
|
||||
messages.add(
|
||||
MqttMessage(
|
||||
topic: 'device/$device/error/post',
|
||||
payload: jsonEncode({
|
||||
'deviceId': device,
|
||||
'type': 'device_error_push',
|
||||
'alarms': alarms,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void pushRecord(Map<String, dynamic> alarm, {String device = 'DEVICE-A'}) {
|
||||
messages.add(
|
||||
MqttMessage(
|
||||
topic: 'device/$device/error/post',
|
||||
payload: jsonEncode(alarm),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
|
||||
}
|
||||
|
||||
Map<String, dynamic> _alarm(int id, {String? time, int status = 1}) => {
|
||||
'id': id,
|
||||
'alarmTitle': 'Alarm $id',
|
||||
'alarmLevel': 2,
|
||||
'alarmType': 1,
|
||||
'alarmTime': time ?? '2026-11-16 10:00:00',
|
||||
'handleStatus': status,
|
||||
};
|
||||
|
||||
Future<void> _flush() => Future<void>.delayed(Duration.zero);
|
||||
|
||||
Map<String, dynamic> _singlePush({
|
||||
String code = 'SAFETY_FAULT_HEARTBEAT_TIMEOUT',
|
||||
String content = '整车控制器心跳反馈超时',
|
||||
String device = 'DEVICE-A',
|
||||
}) => {
|
||||
'id': null,
|
||||
'alarmNo': code,
|
||||
'alarmLevel': 'WARNING',
|
||||
'alarmType': 'MOWER_FAULT',
|
||||
'alarmTitle': code,
|
||||
'alarmContent': content,
|
||||
'deviceId': device,
|
||||
'deviceName': device,
|
||||
'deviceType': 'MOWER',
|
||||
'alarmTime': [2026, 11, 17, 9, 55, 41, 833000000],
|
||||
'recoverTime': null,
|
||||
'handleStatus': null,
|
||||
};
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
setUpAll(RegionTestLocalizations.loadAssets);
|
||||
late _MqttClient mqtt;
|
||||
late _Devices devices;
|
||||
late Dio dio;
|
||||
late DeviceAlarmsCubit cubit;
|
||||
late List<RequestOptions> requests;
|
||||
late Completer<void> requestStarted;
|
||||
late dynamic responseBody;
|
||||
Completer<Map<String, dynamic>>? responseGate;
|
||||
var networkFailed = false;
|
||||
|
||||
setUp(() async {
|
||||
mqtt = _MqttClient();
|
||||
devices = _Devices();
|
||||
dio = Dio();
|
||||
requests = [];
|
||||
requestStarted = Completer<void>();
|
||||
responseBody = {'code': 200};
|
||||
responseGate = null;
|
||||
networkFailed = false;
|
||||
// 所有 HTTP 请求在本地拦截,不接触实际设备或后端。
|
||||
dio.interceptors.add(
|
||||
InterceptorsWrapper(
|
||||
onRequest: (options, handler) async {
|
||||
requests.add(options);
|
||||
if (!requestStarted.isCompleted) requestStarted.complete();
|
||||
if (networkFailed) {
|
||||
handler.reject(
|
||||
DioException(
|
||||
requestOptions: options,
|
||||
type: DioExceptionType.connectionError,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
final body = responseGate == null
|
||||
? responseBody
|
||||
: await responseGate!.future;
|
||||
handler.resolve(
|
||||
Response<dynamic>(
|
||||
requestOptions: options,
|
||||
statusCode: 200,
|
||||
data: body,
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
final repository = DeviceAlarmRepositoryImpl(
|
||||
DeviceAlarmMqttDataSource(mqtt),
|
||||
DeviceAlarmRemoteDataSource(dio),
|
||||
);
|
||||
GetIt.I.registerSingleton<GetAlarmListUseCase>(
|
||||
GetAlarmListUseCase(AlarmRepositoryImpl(AlarmRemoteDataSourceImpl(dio))),
|
||||
);
|
||||
cubit = DeviceAlarmsCubit(
|
||||
WatchDeviceAlarmsUseCase(repository),
|
||||
HandleDeviceAlarmUseCase(repository),
|
||||
LoadSiteAlarmTargetsUseCase(GetSiteDevicesUseCase(devices)),
|
||||
);
|
||||
await cubit.loadSite(1);
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
if (!cubit.isClosed) await cubit.close();
|
||||
await mqtt.messages.close();
|
||||
dio.close(force: true);
|
||||
await GetIt.I.unregister<GetAlarmListUseCase>();
|
||||
});
|
||||
|
||||
test(
|
||||
'subscribes on entry, receives every alarm and releases on exit',
|
||||
() async {
|
||||
expect(mqtt.subscribed, ['device/DEVICE-A/error/post']);
|
||||
expect(cubit.state.hasReceived, isFalse);
|
||||
mqtt.push([_alarm(99)], device: 'DEVICE-B');
|
||||
mqtt.push([_alarm(1), _alarm(2, time: '2026-11-16 11:00:00')]);
|
||||
await _flush();
|
||||
expect(cubit.state.alarms.map((alarm) => alarm.id), [2, 1]);
|
||||
expect(cubit.state.alarms.first.level, '2');
|
||||
expect(cubit.state.pendingCount, 2);
|
||||
mqtt.push([_alarm(1), _alarm(3)]);
|
||||
await _flush();
|
||||
expect(cubit.state.alarms.map((alarm) => alarm.id), [2, 3, 1]);
|
||||
await cubit.close();
|
||||
expect(mqtt.unsubscribed, ['device/DEVICE-A/error/post']);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'accepts the real single-object push with null ID and Java date array',
|
||||
() async {
|
||||
mqtt.pushRecord(_singlePush());
|
||||
await _flush();
|
||||
final alarm = cubit.state.alarms.single;
|
||||
expect(alarm.id, 0);
|
||||
expect(alarm.sourceSn, 'DEVICE-A');
|
||||
expect(alarm.content, '整车控制器心跳反馈超时');
|
||||
expect(alarm.level, 'WARNING');
|
||||
expect(alarm.type, 'MOWER_FAULT');
|
||||
expect(alarm.alarmTime, DateTime(2026, 11, 17, 9, 55, 41, 833));
|
||||
expect(cubit.state.failedSns, isEmpty);
|
||||
expect(cubit.state.hasReceived, isTrue);
|
||||
await cubit.handle(alarm.id);
|
||||
expect(requests, isEmpty);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'single pushes append distinct faults and update repeats without replacing other devices',
|
||||
() async {
|
||||
devices.rows[1] = [_vehicle('DEVICE-A'), _vehicle('DEVICE-B')];
|
||||
await cubit.loadSite(1, force: true);
|
||||
mqtt.pushRecord(_singlePush());
|
||||
mqtt.pushRecord(_singlePush(content: '重复推送更新内容'));
|
||||
mqtt.pushRecord(_singlePush(code: 'OTHER_FAULT'));
|
||||
mqtt.pushRecord(_singlePush(device: 'DEVICE-B'), device: 'DEVICE-B');
|
||||
await _flush();
|
||||
expect(cubit.state.alarms, hasLength(3));
|
||||
expect(cubit.state.forDevice('DEVICE-A').alarms, hasLength(2));
|
||||
expect(cubit.state.forDevice('DEVICE-B').alarms, hasLength(1));
|
||||
expect(
|
||||
cubit.state.alarms.where((alarm) => alarm.content == '重复推送更新内容'),
|
||||
hasLength(1),
|
||||
);
|
||||
// Missing-ID closure must not mark every other missing-ID alarm closed.
|
||||
mqtt.pushRecord({..._singlePush(), 'handleStatus': 2});
|
||||
await _flush();
|
||||
expect(cubit.state.alarms.where((alarm) => alarm.isClosed), hasLength(1));
|
||||
expect(cubit.state.closedIds, isEmpty);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'POST closes only selected alarm after success and blocks duplicate taps',
|
||||
() async {
|
||||
mqtt.push([_alarm(1), _alarm(2)]);
|
||||
await _flush();
|
||||
responseGate = Completer<Map<String, dynamic>>();
|
||||
final handling = cubit.handle(1);
|
||||
await requestStarted.future;
|
||||
await cubit.handle(1);
|
||||
expect(requests, hasLength(1));
|
||||
final request = requests.single;
|
||||
expect(request.method, 'POST');
|
||||
expect(request.uri.origin, EnvConfig.baseUrl);
|
||||
expect(request.uri.path, '/iot/alarm/handle');
|
||||
expect(request.data, {'alarmId': 1, 'handleStatus': 2});
|
||||
expect(cubit.state.alarms.every((alarm) => !alarm.isClosed), isTrue);
|
||||
expect(cubit.state.handlingIds, {1});
|
||||
responseGate!.complete({'code': 200});
|
||||
await handling;
|
||||
expect(
|
||||
cubit.state.alarms.singleWhere((alarm) => alarm.id == 1).isClosed,
|
||||
isTrue,
|
||||
);
|
||||
expect(
|
||||
cubit.state.alarms.singleWhere((alarm) => alarm.id == 2).isClosed,
|
||||
isFalse,
|
||||
);
|
||||
expect(cubit.state.handlingIds, isEmpty);
|
||||
mqtt.push([_alarm(1)]);
|
||||
await _flush();
|
||||
expect(
|
||||
cubit.state.alarms.singleWhere((alarm) => alarm.id == 1).isClosed,
|
||||
isTrue,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'rejected, malformed and network responses keep alarm pending and allow retry',
|
||||
() async {
|
||||
mqtt.push([_alarm(1)]);
|
||||
await _flush();
|
||||
for (final body in [
|
||||
{'code': 500, 'msg': '处理失败'},
|
||||
{'code': 200, 'data': false},
|
||||
{'data': true},
|
||||
'invalid response',
|
||||
]) {
|
||||
responseBody = body;
|
||||
await cubit.handle(1);
|
||||
expect(cubit.state.alarms.single.isClosed, isFalse);
|
||||
expect(cubit.state.handleErrors.containsKey(1), isTrue);
|
||||
expect(cubit.state.handlingIds, isEmpty);
|
||||
}
|
||||
networkFailed = true;
|
||||
await cubit.handle(1);
|
||||
expect(cubit.state.alarms.single.isClosed, isFalse);
|
||||
networkFailed = false;
|
||||
responseBody = {'code': '200', 'data': true};
|
||||
await cubit.handle(1);
|
||||
expect(cubit.state.alarms.single.isClosed, isTrue);
|
||||
expect(cubit.state.handleErrors, isEmpty);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'bad frame does not end reception; resubscribe retains existing records',
|
||||
() async {
|
||||
mqtt.messages.add(
|
||||
MqttMessage(topic: 'device/DEVICE-A/error/post', payload: '{bad json'),
|
||||
);
|
||||
await _flush();
|
||||
expect(cubit.state.subscriptionFailed, isTrue);
|
||||
mqtt.push([_alarm(1)]);
|
||||
await _flush();
|
||||
expect(cubit.state.subscriptionFailed, isFalse);
|
||||
await cubit.handle(1);
|
||||
await cubit.retry();
|
||||
mqtt.push([_alarm(1), _alarm(2)]);
|
||||
await _flush();
|
||||
expect(cubit.state.alarms, hasLength(2));
|
||||
expect(
|
||||
cubit.state.alarms.singleWhere((alarm) => alarm.id == 1).isClosed,
|
||||
isTrue,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'site switch releases previous topic and ignores its late HTTP completion',
|
||||
() async {
|
||||
mqtt.push([_alarm(1)]);
|
||||
await _flush();
|
||||
responseGate = Completer<Map<String, dynamic>>();
|
||||
final handling = cubit.handle(1);
|
||||
await requestStarted.future;
|
||||
await cubit.loadSite(2);
|
||||
expect(mqtt.unsubscribed, ['device/DEVICE-A/error/post']);
|
||||
expect(mqtt.subscribed.last, 'device/DEVICE-B/error/post');
|
||||
mqtt.push([_alarm(9)]);
|
||||
mqtt.push([_alarm(1)], device: 'DEVICE-B');
|
||||
await _flush();
|
||||
responseGate!.complete({'code': 200});
|
||||
await handling;
|
||||
expect(cubit.state.alarms.single.id, 1);
|
||||
expect(cubit.state.alarms.single.isClosed, isFalse);
|
||||
expect(cubit.state.handleErrors, isEmpty);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'site subscribes every vehicle by SN and scopes all/device data independently',
|
||||
() async {
|
||||
devices.rows[1] = [
|
||||
_vehicle('DEVICE-A'),
|
||||
_vehicle('DEVICE-B'),
|
||||
_vehicle('DEVICE-A'),
|
||||
_vehicle('STXZ0126101500001198D', isRobot: false),
|
||||
_vehicle('OTHER-SITE', siteId: 9),
|
||||
];
|
||||
await cubit.loadSite(1, force: true);
|
||||
expect(mqtt.subscribed, [
|
||||
'device/DEVICE-A/error/post',
|
||||
'device/DEVICE-B/error/post',
|
||||
'device/STXZ0126101500001198D/error/post',
|
||||
]);
|
||||
mqtt.push([_alarm(1)]);
|
||||
mqtt.push([_alarm(2)], device: 'DEVICE-B');
|
||||
await _flush();
|
||||
expect(cubit.state.alarms, hasLength(2));
|
||||
expect(cubit.state.forDevice('DEVICE-A').alarms.single.id, 1);
|
||||
expect(cubit.state.forDevice('DEVICE-B').alarms.single.id, 2);
|
||||
await cubit.handle(1);
|
||||
expect(cubit.state.forDevice('DEVICE-A').pendingCount, 0);
|
||||
expect(cubit.state.forDevice('DEVICE-B').pendingCount, 1);
|
||||
expect(cubit.state.pendingCount, 1);
|
||||
|
||||
devices.rows[1] = [_vehicle('DEVICE-A'), _vehicle('DEVICE-C')];
|
||||
await cubit.loadSite(1, force: true);
|
||||
expect(mqtt.unsubscribed, [
|
||||
'device/DEVICE-B/error/post',
|
||||
'device/STXZ0126101500001198D/error/post',
|
||||
]);
|
||||
expect(
|
||||
mqtt.subscribed.where((topic) => topic.contains('DEVICE-A')),
|
||||
hasLength(1),
|
||||
);
|
||||
expect(mqtt.subscribed.last, 'device/DEVICE-C/error/post');
|
||||
expect(cubit.state.alarms.single.isClosed, isTrue);
|
||||
await cubit.loadSite(null);
|
||||
await cubit.retry();
|
||||
expect(cubit.state.isLoading, isFalse);
|
||||
expect(cubit.state.alarms, isEmpty);
|
||||
expect(
|
||||
mqtt.unsubscribed,
|
||||
containsAll([
|
||||
'device/DEVICE-A/error/post',
|
||||
'device/DEVICE-C/error/post',
|
||||
]),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test('rapid site changes ignore late roster and old-site messages', () async {
|
||||
final roster = Completer<List<DeviceEntity>>();
|
||||
devices.pending[2] = roster;
|
||||
devices.started[2] = Completer<void>();
|
||||
mqtt.push([_alarm(1)]);
|
||||
await _flush();
|
||||
final oldLoad = cubit.loadSite(2);
|
||||
await devices.started[2]!.future;
|
||||
expect(cubit.state.alarms, isEmpty);
|
||||
expect(mqtt.unsubscribed, ['device/DEVICE-A/error/post']);
|
||||
await cubit.loadSite(3);
|
||||
roster.complete(devices.rows[2]!);
|
||||
await oldLoad;
|
||||
mqtt.push([_alarm(1)]);
|
||||
mqtt.push([_alarm(2)], device: 'DEVICE-B');
|
||||
mqtt.push([_alarm(3)], device: 'DEVICE-C');
|
||||
await _flush();
|
||||
expect(cubit.state.siteId, 3);
|
||||
expect(cubit.state.alarms.single.id, 3);
|
||||
expect(mqtt.subscribed, [
|
||||
'device/DEVICE-A/error/post',
|
||||
'device/DEVICE-C/error/post',
|
||||
]);
|
||||
});
|
||||
|
||||
test(
|
||||
'history reuses the old list API and filters raw device IDs across pages',
|
||||
() async {
|
||||
final history = DeviceAlarmHistoryCubit(
|
||||
GetIt.I<GetAlarmListUseCase>(),
|
||||
siteId: 1,
|
||||
deviceSn: 'DEVICE-A',
|
||||
deviceId: 'DATABASE-ID-DEVICE-A',
|
||||
);
|
||||
responseBody = {
|
||||
'code': 200,
|
||||
'rows': List.generate(
|
||||
20,
|
||||
(index) => {
|
||||
..._alarm(index + 1),
|
||||
'siteId': 1,
|
||||
'deviceId': index == 0
|
||||
? 'DATABASE-ID-DEVICE-A'
|
||||
: 'DATABASE-ID-DEVICE-B',
|
||||
'deviceName': 'Display alias',
|
||||
'handleStatus': '1',
|
||||
'alarmLevel': '1',
|
||||
},
|
||||
),
|
||||
};
|
||||
await history.refresh();
|
||||
final request = requests.single;
|
||||
expect(request.method, 'GET');
|
||||
expect(request.uri.path, '/iot/alarm/list');
|
||||
expect(request.queryParameters, {'siteId': 1, 'page': 1, 'pageSize': 20});
|
||||
expect(history.state.alarms.single.id, '1');
|
||||
expect(history.state.alarms.single.status, AlarmStatus.pending);
|
||||
expect(history.state.alarms.single.level, AlarmLevel.danger);
|
||||
expect(history.state.hasMore, isTrue);
|
||||
responseBody = {
|
||||
'code': 200,
|
||||
'rows': [
|
||||
{..._alarm(21), 'deviceId': 'DATABASE-ID-DEVICE-A', 'siteId': 1},
|
||||
{..._alarm(22), 'deviceId': 'DATABASE-ID-DEVICE-A', 'siteId': 2},
|
||||
],
|
||||
};
|
||||
await history.loadMore();
|
||||
expect(
|
||||
history.state.alarms.map((alarm) => alarm.id),
|
||||
containsAll(['1', '21']),
|
||||
);
|
||||
expect(history.state.alarms, hasLength(2));
|
||||
expect(history.state.hasMore, isFalse);
|
||||
expect(requests.last.queryParameters['page'], 2);
|
||||
await history.close();
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'history retries the failed page and keeps cached rows on refresh errors',
|
||||
() async {
|
||||
final history = DeviceAlarmHistoryCubit(
|
||||
GetIt.I<GetAlarmListUseCase>(),
|
||||
siteId: 1,
|
||||
);
|
||||
responseBody = {
|
||||
'code': 200,
|
||||
'rows': List.generate(20, (i) => _alarm(i + 1)),
|
||||
};
|
||||
await history.refresh();
|
||||
expect(history.state.alarms, hasLength(20));
|
||||
networkFailed = true;
|
||||
await history.refresh();
|
||||
expect(history.state.error, isNotNull);
|
||||
expect(history.state.alarms, hasLength(20));
|
||||
final count = requests.length;
|
||||
await history.loadMore();
|
||||
expect(requests, hasLength(count));
|
||||
networkFailed = false;
|
||||
await history.retry();
|
||||
expect(requests.last.queryParameters['page'], 1);
|
||||
expect(history.state.error, isNull);
|
||||
networkFailed = true;
|
||||
await history.loadMore();
|
||||
expect(requests.last.queryParameters['page'], 2);
|
||||
networkFailed = false;
|
||||
await history.retry();
|
||||
expect(requests.last.queryParameters['page'], 2);
|
||||
expect(history.state.error, isNull);
|
||||
await history.close();
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets(
|
||||
'history connection errors show a short retry state without raw exception or load-more',
|
||||
(tester) async {
|
||||
networkFailed = true;
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
locale: AppLocalizations.chinese,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
localizationsDelegates: const [
|
||||
RegionTestLocalizations(),
|
||||
GlobalMaterialLocalizations.delegate,
|
||||
GlobalWidgetsLocalizations.delegate,
|
||||
GlobalCupertinoLocalizations.delegate,
|
||||
],
|
||||
home: Scaffold(body: DeviceAlarmHistoryTab(cubit: cubit)),
|
||||
),
|
||||
);
|
||||
await tester.runAsync(
|
||||
() => Future<void>.delayed(const Duration(milliseconds: 40)),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('历史告警加载失败,请重试'), findsOneWidget);
|
||||
expect(find.text('重试'), findsOneWidget);
|
||||
expect(find.text('加载更多'), findsNothing);
|
||||
expect(find.textContaining('DioException'), findsNothing);
|
||||
expect(find.textContaining('/iot/alarm/list'), findsNothing);
|
||||
networkFailed = false;
|
||||
responseBody = {'code': 200, 'rows': []};
|
||||
await tester.tap(find.text('重试'));
|
||||
await tester.runAsync(
|
||||
() => Future<void>.delayed(const Duration(milliseconds: 40)),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('历史告警加载失败,请重试'), findsNothing);
|
||||
expect(find.text('暂无历史告警记录'), findsOneWidget);
|
||||
expect(requests.last.queryParameters['page'], 1);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'history-only record uses latest handle API and shares closed state',
|
||||
() async {
|
||||
expect(cubit.state.alarms, isEmpty);
|
||||
await cubit.handle(501, historySiteId: 1);
|
||||
expect(requests.single.method, 'POST');
|
||||
expect(requests.single.uri.path, '/iot/alarm/handle');
|
||||
expect(requests.single.data, {'alarmId': 501, 'handleStatus': 2});
|
||||
expect(cubit.state.closedIds, contains(501));
|
||||
expect(cubit.state.alarms, isEmpty);
|
||||
await cubit.retry();
|
||||
expect(cubit.state.closedIds, contains(501));
|
||||
await cubit.handle(501, historySiteId: 1);
|
||||
expect(requests, hasLength(1));
|
||||
await cubit.loadSite(2);
|
||||
await cubit.handle(502, historySiteId: 1);
|
||||
expect(requests, hasLength(1));
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets(
|
||||
'overview title/card open device alarms; top icon opens all site alarms',
|
||||
(tester) async {
|
||||
await tester.runAsync(() async {
|
||||
devices.rows[1] = [_vehicle('DEVICE-A'), _vehicle('DEVICE-B')];
|
||||
await cubit.loadSite(1, force: true);
|
||||
mqtt.push([_alarm(1)]);
|
||||
mqtt.push([_alarm(2)], device: 'DEVICE-B');
|
||||
await _flush();
|
||||
});
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
theme: ThemeData(extensions: const [AppColors.light]),
|
||||
locale: AppLocalizations.chinese,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
localizationsDelegates: const [
|
||||
RegionTestLocalizations(),
|
||||
GlobalMaterialLocalizations.delegate,
|
||||
GlobalWidgetsLocalizations.delegate,
|
||||
GlobalCupertinoLocalizations.delegate,
|
||||
],
|
||||
home: Scaffold(
|
||||
appBar: AppBar(actions: [SiteAlarmButton(cubit: cubit)]),
|
||||
body: DeviceAlarmSection(cubit: cubit, deviceSn: 'DEVICE-A'),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text('故障状态'));
|
||||
await tester.pumpAndSettle();
|
||||
final dialog = find.byType(DeviceAlarmDialog);
|
||||
expect(dialog, findsOneWidget);
|
||||
expect(
|
||||
find.descendant(of: dialog, matching: find.text('Alarm 1')),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(
|
||||
find.descendant(of: dialog, matching: find.text('Alarm 2')),
|
||||
findsNothing,
|
||||
);
|
||||
await tester.tap(find.byTooltip('关闭'));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.byType(DeviceAlarmSummaryCard));
|
||||
await tester.pumpAndSettle();
|
||||
expect(dialog, findsOneWidget);
|
||||
await tester.tap(find.byTooltip('关闭'));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.byType(SiteAlarmButton));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('场站故障与告警'), findsOneWidget);
|
||||
expect(
|
||||
find.descendant(of: dialog, matching: find.text('Alarm 2')),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(mqtt.subscribed, hasLength(2));
|
||||
expect(mqtt.unsubscribed, isEmpty);
|
||||
responseBody = {
|
||||
'code': 200,
|
||||
'rows': [
|
||||
{
|
||||
..._alarm(501),
|
||||
'siteId': 1,
|
||||
'deviceId': 'DATABASE-ID-DEVICE-A',
|
||||
'deviceName': 'DEVICE-A',
|
||||
},
|
||||
],
|
||||
};
|
||||
await tester.tap(find.text('历史'));
|
||||
await tester.pump(const Duration(milliseconds: 350));
|
||||
await tester.runAsync(() async {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 40));
|
||||
});
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byType(AlarmItemCard), findsOneWidget);
|
||||
expect(find.text('去处理'), findsOneWidget);
|
||||
await tester.tap(find.byKey(const ValueKey('history-handle-501')));
|
||||
await tester.runAsync(() async {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 40));
|
||||
});
|
||||
await tester.pumpAndSettle();
|
||||
expect(cubit.state.closedIds, contains(501));
|
||||
expect(requests.last.method, 'POST');
|
||||
expect(requests.last.uri.path, '/iot/alarm/handle');
|
||||
expect(requests.last.data, {'alarmId': 501, 'handleStatus': 2});
|
||||
expect(find.text('去处理'), findsNothing);
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
},
|
||||
);
|
||||
}
|
||||
313
test/mower_task_status_test.dart
Normal file
313
test/mower_task_status_test.dart
Normal file
@@ -0,0 +1,313 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_localizations/flutter_localizations.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:maibu_satabot_v2/core/localization/app_localizations.dart';
|
||||
import 'package:maibu_satabot_v2/core/network/mqtt/data/datasources/mower_realtime_datasource.dart';
|
||||
import 'package:maibu_satabot_v2/core/network/mqtt/data/repositories/mower_realtime_repository_impl.dart';
|
||||
import 'package:maibu_satabot_v2/core/network/mqtt/domain/entities/mower_task_status_entity.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_message.dart';
|
||||
import 'package:maibu_satabot_v2/features/autonomous_work/data/site_device_realtime_subscriptions.dart';
|
||||
import 'package:maibu_satabot_v2/features/v2/device_list/presentation/widgets/autonomous/work_task_status_card.dart';
|
||||
|
||||
import 'support/region_test_localizations.dart';
|
||||
|
||||
const _sn = 'STXZ0126101500001198D';
|
||||
const _topic = 'mower/$_sn/task/status/post';
|
||||
|
||||
Map<String, dynamic> _sample() => {
|
||||
'protocol_version': '1.4.7',
|
||||
'message_id': '$_sn-00009349',
|
||||
'sn': _sn,
|
||||
'task_id': '33394',
|
||||
'command_id': '33394_1794815329286',
|
||||
'mode': 'coverage',
|
||||
'status': 'running',
|
||||
'timestamp': 1794815389009,
|
||||
'data': {
|
||||
'distance_remaining': 91.3607406616211,
|
||||
'number_of_recoveries': 1,
|
||||
'elapsed_s': 57.541494845,
|
||||
'eta_s': 569.789080477,
|
||||
'progress': 0.09172400832176208,
|
||||
'current_cell_index': 0,
|
||||
'total_cells': 1,
|
||||
'distance_traveled': 13.053206443786621,
|
||||
'speed': 0.13422368466854095,
|
||||
'phase': 3,
|
||||
'task_phase': 3,
|
||||
'phase_name': 'COVERING',
|
||||
},
|
||||
};
|
||||
|
||||
class _Mqtt extends Fake implements MqttClient {
|
||||
final messages = StreamController<MqttMessage>.broadcast();
|
||||
final subscribed = <String>[];
|
||||
final unsubscribed = <String>[];
|
||||
|
||||
@override
|
||||
Stream<MqttMessage> get messageStream => messages.stream;
|
||||
@override
|
||||
Future<void> subscribe(String topic) async => subscribed.add(topic);
|
||||
@override
|
||||
Future<void> unsubscribe(String topic) async {
|
||||
unsubscribed.add(topic);
|
||||
}
|
||||
|
||||
void send(Map<String, dynamic> json, {String topic = _topic, DateTime? at}) {
|
||||
messages.add(
|
||||
MqttMessage(topic: topic, payload: jsonEncode(json), timestamp: at),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _UiSubscriptions extends Fake implements SiteDeviceRealtimeSubscriptions {
|
||||
_UiSubscriptions(this.repository);
|
||||
final MowerRealtimeRepositoryImpl repository;
|
||||
|
||||
@override
|
||||
Stream<MowerTaskStatusEntity?> watchTaskStatus({
|
||||
required int? siteId,
|
||||
required String deviceSn,
|
||||
}) => repository.watchTaskStatus(deviceSn);
|
||||
}
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
setUpAll(RegionTestLocalizations.loadAssets);
|
||||
|
||||
test('parses the supplied protocol sample without losing precision', () {
|
||||
final status = MowerTaskStatusEntity.fromJson(_sample());
|
||||
expect(status.protocolVersion, '1.4.7');
|
||||
expect(status.sn, _sn);
|
||||
expect(status.taskId, '33394');
|
||||
expect(status.status, 'running');
|
||||
expect(status.phaseName, 'COVERING');
|
||||
expect(status.progress, closeTo(0.091724, 0.000001));
|
||||
expect(status.distanceRemaining, closeTo(91.36074, 0.00001));
|
||||
expect(status.currentCellIndex, 0);
|
||||
expect(status.numberOfRecoveries, 1);
|
||||
expect(status.timestamp, 1794815389009);
|
||||
expect(status.raw, _sample());
|
||||
});
|
||||
|
||||
test('missing and invalid values stay unknown while real zeros survive', () {
|
||||
for (final data in [null, [], 'bad', <String, dynamic>{}]) {
|
||||
final status = MowerTaskStatusEntity.fromJson({'data': data});
|
||||
expect(status.taskId, isNull);
|
||||
expect(status.progress, isNull);
|
||||
expect(status.elapsedSeconds, isNull);
|
||||
expect(status.numberOfRecoveries, isNull);
|
||||
expect(status.currentCellIndex, isNull);
|
||||
expect(status.speed, isNull);
|
||||
}
|
||||
final zeros = MowerTaskStatusEntity.fromJson({
|
||||
'data': {'progress': 0, 'speed': 0, 'number_of_recoveries': 0},
|
||||
});
|
||||
expect(zeros.progress, 0);
|
||||
expect(zeros.speed, 0);
|
||||
expect(zeros.numberOfRecoveries, 0);
|
||||
final invalid = MowerTaskStatusEntity.fromJson({
|
||||
'sn': '',
|
||||
'status': {},
|
||||
'data': {
|
||||
'progress': 9.17,
|
||||
'speed': 'NaN',
|
||||
'elapsed_s': -1,
|
||||
'total_cells': 1.5,
|
||||
'eta_s': true,
|
||||
},
|
||||
});
|
||||
expect(invalid.sn, isNull);
|
||||
expect(invalid.status, isNull);
|
||||
expect(invalid.progress, isNull);
|
||||
expect(invalid.speed, isNull);
|
||||
expect(invalid.elapsedSeconds, isNull);
|
||||
expect(invalid.totalCells, isNull);
|
||||
expect(invalid.etaSeconds, isNull);
|
||||
});
|
||||
|
||||
test(
|
||||
'subscribes by SN, ignores foreign/malformed messages and releases topic',
|
||||
() async {
|
||||
final mqtt = _Mqtt();
|
||||
final source = MowerRealtimeDataSourceImpl(mqtt);
|
||||
final reports = <MowerTaskStatusEntity>[];
|
||||
final subscription = source.watchTaskStatus(_sn).listen(reports.add);
|
||||
expect(mqtt.subscribed, [_topic]);
|
||||
mqtt.send(_sample(), topic: 'mower/other/task/status/post');
|
||||
mqtt.send({..._sample(), 'sn': 'other'});
|
||||
mqtt.messages.add(MqttMessage(topic: _topic, payload: '{broken'));
|
||||
mqtt.messages.add(MqttMessage(topic: _topic, payload: '[]'));
|
||||
mqtt.send(_sample());
|
||||
// A partial frame replaces the previous values instead of retaining them.
|
||||
mqtt.send({
|
||||
'task_id': '33394',
|
||||
'data': {'speed': 0},
|
||||
});
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
expect(reports, hasLength(2));
|
||||
expect(reports.last.speed, 0);
|
||||
expect(reports.last.progress, isNull);
|
||||
await subscription.cancel();
|
||||
expect(mqtt.unsubscribed, [_topic]);
|
||||
source.dispose();
|
||||
await mqtt.messages.close();
|
||||
},
|
||||
);
|
||||
|
||||
late _Mqtt mqtt;
|
||||
late MowerRealtimeDataSourceImpl source;
|
||||
late MowerRealtimeRepositoryImpl repository;
|
||||
late _UiSubscriptions subscriptions;
|
||||
|
||||
setUp(() {
|
||||
mqtt = _Mqtt();
|
||||
source = MowerRealtimeDataSourceImpl(mqtt);
|
||||
repository = MowerRealtimeRepositoryImpl(source);
|
||||
subscriptions = _UiSubscriptions(repository);
|
||||
});
|
||||
tearDown(() async {
|
||||
source.dispose();
|
||||
await mqtt.messages.close();
|
||||
});
|
||||
|
||||
Future<void> mount(
|
||||
WidgetTester tester, {
|
||||
String taskId = '33394',
|
||||
bool compact = false,
|
||||
Locale locale = AppLocalizations.chinese,
|
||||
}) async {
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
locale: locale,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
localizationsDelegates: const [
|
||||
RegionTestLocalizations(),
|
||||
GlobalMaterialLocalizations.delegate,
|
||||
GlobalWidgetsLocalizations.delegate,
|
||||
GlobalCupertinoLocalizations.delegate,
|
||||
],
|
||||
home: Scaffold(
|
||||
body: Align(
|
||||
alignment: Alignment.topLeft,
|
||||
child: SizedBox(
|
||||
width: compact ? 178 : 248,
|
||||
child: WorkTaskStatusCard(
|
||||
subscriptions: subscriptions,
|
||||
siteId: 1,
|
||||
deviceSn: _sn,
|
||||
expectedTaskId: taskId,
|
||||
compact: compact,
|
||||
maxHeight: compact ? 200 : 540,
|
||||
onCollapse: () {},
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
testWidgets(
|
||||
'shows unknown before reports and clears values omitted in the next frame',
|
||||
(tester) async {
|
||||
await mount(tester);
|
||||
expect(find.text('等待任务状态上报'), findsOneWidget);
|
||||
expect(find.text('未知'), findsWidgets);
|
||||
mqtt.send(_sample());
|
||||
await tester.pump();
|
||||
await tester.pump();
|
||||
expect(find.text('9.17%'), findsOneWidget);
|
||||
expect(find.text('执行中'), findsOneWidget);
|
||||
expect(find.text('正在覆盖'), findsOneWidget);
|
||||
expect(find.text('91.36 m'), findsOneWidget);
|
||||
expect(find.text('09:30'), findsOneWidget);
|
||||
mqtt.send({
|
||||
'task_id': '33394',
|
||||
'data': {'progress': 0, 'speed': 0},
|
||||
});
|
||||
await tester.pump();
|
||||
await tester.pump();
|
||||
expect(find.text('0.00%'), findsOneWidget);
|
||||
expect(find.text('0.00 m/s'), findsOneWidget);
|
||||
expect(find.text('91.36 m'), findsNothing);
|
||||
expect(find.text('执行中'), findsNothing);
|
||||
expect(find.text('未知'), findsWidgets);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
expect(find.byType(WorkTaskStatusCard), findsNothing);
|
||||
await tester.pump();
|
||||
await tester.pump();
|
||||
// Widget disposal removes its stream listener immediately. The data-source
|
||||
// test above awaits cancellation and verifies the eventual MQTT release.
|
||||
expect(mqtt.messages.hasListener, isFalse);
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets(
|
||||
'does not show another task or accept older frames; switching clears the old task',
|
||||
(tester) async {
|
||||
await mount(tester);
|
||||
mqtt.send({..._sample(), 'task_id': 'other'});
|
||||
await tester.pump();
|
||||
await tester.pump();
|
||||
expect(find.text('9.17%'), findsNothing);
|
||||
mqtt.send(_sample());
|
||||
await tester.pump();
|
||||
await tester.pump();
|
||||
mqtt.send({..._sample(), 'status': 'paused', 'timestamp': 1794815388000});
|
||||
await tester.pump();
|
||||
await tester.pump();
|
||||
expect(find.text('执行中'), findsOneWidget);
|
||||
expect(find.text('已暂停'), findsNothing);
|
||||
await mount(tester, taskId: 'new-task');
|
||||
expect(find.text('9.17%'), findsNothing);
|
||||
expect(find.text('等待任务状态上报'), findsOneWidget);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets(
|
||||
'compact card scrolls without overflow, marks stale reports and exposes raw fields',
|
||||
(tester) async {
|
||||
await mount(tester, compact: true);
|
||||
mqtt.send(
|
||||
_sample(),
|
||||
at: DateTime.now().subtract(const Duration(seconds: 20)),
|
||||
);
|
||||
await tester.pump();
|
||||
await tester.pump();
|
||||
expect(find.text('数据暂未更新,以下为最后一次上报'), findsOneWidget);
|
||||
expect(tester.takeException(), isNull);
|
||||
await tester.ensureVisible(find.text('报文详情'));
|
||||
await tester.tap(find.text('报文详情'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('phase'), findsOneWidget);
|
||||
expect(find.text('task_phase'), findsOneWidget);
|
||||
expect(find.text('current_cell_index'), findsOneWidget);
|
||||
expect(tester.takeException(), isNull);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets(
|
||||
'English compact layout keeps unknown fields and long IDs readable',
|
||||
(tester) async {
|
||||
await mount(tester, compact: true, locale: AppLocalizations.english);
|
||||
expect(find.text('Unknown'), findsWidgets);
|
||||
mqtt.send(_sample());
|
||||
await tester.pump();
|
||||
await tester.pump();
|
||||
await tester.ensureVisible(find.text('Report details'));
|
||||
await tester.tap(find.text('Report details'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('$_sn-00009349'), findsOneWidget);
|
||||
expect(tester.takeException(), isNull);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
},
|
||||
);
|
||||
}
|
||||
193
test/pv_task_progress_test.dart
Normal file
193
test/pv_task_progress_test.dart
Normal file
@@ -0,0 +1,193 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_localizations/flutter_localizations.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:maibu_satabot_v2/core/localization/app_localizations.dart';
|
||||
import 'package:maibu_satabot_v2/core/network/mqtt/domain/entities/mower_task_status_entity.dart';
|
||||
import 'package:maibu_satabot_v2/features/autonomous_work/data/site_device_realtime_subscriptions.dart';
|
||||
import 'package:maibu_satabot_v2/features/pv_control/presentation/widgets/pv_task_progress_content.dart';
|
||||
|
||||
import 'support/region_test_localizations.dart';
|
||||
|
||||
class _Subscriptions extends Fake implements SiteDeviceRealtimeSubscriptions {
|
||||
final controllers = <String, StreamController<MowerTaskStatusEntity?>>{};
|
||||
final requests = <String>[];
|
||||
|
||||
@override
|
||||
Stream<MowerTaskStatusEntity?> watchTaskStatus({
|
||||
required int? siteId,
|
||||
required String deviceSn,
|
||||
}) {
|
||||
final key = '$siteId/$deviceSn';
|
||||
requests.add(key);
|
||||
return controllers
|
||||
.putIfAbsent(key, () => StreamController.broadcast())
|
||||
.stream;
|
||||
}
|
||||
|
||||
void send(
|
||||
String sn,
|
||||
Map<String, dynamic> data, {
|
||||
int site = 1,
|
||||
DateTime? receivedAt,
|
||||
}) => controllers['$site/$sn']!.add(
|
||||
MowerTaskStatusEntity.fromJson({
|
||||
'sn': sn,
|
||||
'task_id': '33394',
|
||||
'data': data,
|
||||
}, receivedAt: receivedAt),
|
||||
);
|
||||
|
||||
Future<void> close() async {
|
||||
for (final controller in controllers.values) {
|
||||
await controller.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
setUpAll(RegionTestLocalizations.loadAssets);
|
||||
late _Subscriptions subscriptions;
|
||||
setUp(() => subscriptions = _Subscriptions());
|
||||
tearDown(() => subscriptions.close());
|
||||
|
||||
Future<void> mount(
|
||||
WidgetTester tester, {
|
||||
String sn = 'A',
|
||||
int site = 1,
|
||||
bool compact = false,
|
||||
Locale locale = AppLocalizations.chinese,
|
||||
}) async {
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
locale: locale,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
localizationsDelegates: const [
|
||||
RegionTestLocalizations(),
|
||||
GlobalMaterialLocalizations.delegate,
|
||||
GlobalWidgetsLocalizations.delegate,
|
||||
GlobalCupertinoLocalizations.delegate,
|
||||
],
|
||||
home: Scaffold(
|
||||
body: Align(
|
||||
alignment: Alignment.topLeft,
|
||||
child: SizedBox(
|
||||
width: compact ? 100 : 200,
|
||||
child: PvTaskProgressContent(
|
||||
subscriptions: subscriptions,
|
||||
siteId: site,
|
||||
deviceSn: sn,
|
||||
scale: compact ? 0.64 : 1,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
Future<void> flush(WidgetTester tester) async {
|
||||
await tester.pump();
|
||||
await tester.pump();
|
||||
}
|
||||
|
||||
testWidgets(
|
||||
'remote work card replaces demo values with real progress, time and distance',
|
||||
(tester) async {
|
||||
await mount(tester);
|
||||
expect(find.text('未知'), findsWidgets);
|
||||
expect(find.text('68%'), findsNothing);
|
||||
expect(find.text('01:42:18'), findsNothing);
|
||||
subscriptions.send('A', {
|
||||
'progress': 0.091724,
|
||||
'elapsed_s': 57.54,
|
||||
'eta_s': 569.789,
|
||||
'distance_remaining': 91.36074,
|
||||
});
|
||||
await flush(tester);
|
||||
expect(find.text('9.17%'), findsOneWidget);
|
||||
expect(find.text('00:00:57'), findsOneWidget);
|
||||
expect(find.text('00:09:29'), findsOneWidget);
|
||||
expect(find.text('91.36 m'), findsOneWidget);
|
||||
expect(find.text('作业面积'), findsOneWidget);
|
||||
// Area is absent in the protocol and must remain unknown.
|
||||
expect(find.text('未知'), findsOneWidget);
|
||||
expect(find.byType(LinearProgressIndicator), findsOneWidget);
|
||||
expect(
|
||||
tester
|
||||
.widget<LinearProgressIndicator>(
|
||||
find.byType(LinearProgressIndicator),
|
||||
)
|
||||
.value,
|
||||
closeTo(0.091724, 0.000001),
|
||||
);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets(
|
||||
'partial reports clear omitted values and real zero values remain visible',
|
||||
(tester) async {
|
||||
await mount(tester);
|
||||
subscriptions.send('A', {'progress': 0.5, 'elapsed_s': 60});
|
||||
await flush(tester);
|
||||
subscriptions.send('A', {'progress': 0, 'elapsed_s': 0});
|
||||
await flush(tester);
|
||||
expect(find.text('0.00%'), findsOneWidget);
|
||||
expect(find.text('00:00:00'), findsOneWidget);
|
||||
subscriptions.send('A', {});
|
||||
await flush(tester);
|
||||
expect(find.text('0.00%'), findsNothing);
|
||||
expect(find.text('00:00:00'), findsNothing);
|
||||
expect(find.text('未知'), findsWidgets);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets(
|
||||
'switching device or site clears old task data and detaches old UI listeners',
|
||||
(tester) async {
|
||||
await mount(tester);
|
||||
subscriptions.send('A', {'progress': 0.25});
|
||||
await flush(tester);
|
||||
expect(find.text('25.00%'), findsOneWidget);
|
||||
await mount(tester, sn: 'B');
|
||||
expect(find.text('25.00%'), findsNothing);
|
||||
subscriptions.send('A', {'progress': 0.75});
|
||||
await flush(tester);
|
||||
expect(find.text('75.00%'), findsNothing);
|
||||
subscriptions.send('B', {'progress': 0.5});
|
||||
await flush(tester);
|
||||
expect(find.text('50.00%'), findsOneWidget);
|
||||
await mount(tester, sn: 'B', site: 2);
|
||||
expect(find.text('50.00%'), findsNothing);
|
||||
expect(subscriptions.controllers['1/B']!.hasListener, isFalse);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
expect(subscriptions.controllers['2/B']!.hasListener, isFalse);
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets(
|
||||
'compact English card fits the HUD and labels stale cached data',
|
||||
(tester) async {
|
||||
await mount(tester, compact: true, locale: AppLocalizations.english);
|
||||
subscriptions.send('A', {
|
||||
'progress': 0.25,
|
||||
'elapsed_s': 36001,
|
||||
'eta_s': 1234,
|
||||
'distance_remaining': 123.45,
|
||||
}, receivedAt: DateTime.now().subtract(const Duration(seconds: 20)));
|
||||
await flush(tester);
|
||||
expect(
|
||||
find.text('No recent update. Showing the last report.'),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(find.text('25.00%'), findsOneWidget);
|
||||
expect(tester.takeException(), isNull);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
},
|
||||
);
|
||||
}
|
||||
304
test/site_device_realtime_subscriptions_test.dart
Normal file
304
test/site_device_realtime_subscriptions_test.dart
Normal file
@@ -0,0 +1,304 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:maibu_satabot_v2/core/network/mqtt/data/datasources/mower_realtime_datasource.dart';
|
||||
import 'package:maibu_satabot_v2/core/network/mqtt/data/repositories/mower_realtime_repository_impl.dart';
|
||||
import 'package:maibu_satabot_v2/core/network/mqtt/domain/entities/mower_task_status_entity.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_message.dart';
|
||||
import 'package:maibu_satabot_v2/features/autonomous_work/data/site_device_realtime_subscriptions.dart';
|
||||
import 'package:maibu_satabot_v2/features/device_alarms/data/datasources/device_alarm_mqtt_datasource.dart';
|
||||
import 'package:maibu_satabot_v2/features/device_alarms/data/datasources/device_alarm_remote_datasource.dart';
|
||||
import 'package:maibu_satabot_v2/features/device_alarms/data/repositories/device_alarm_repository_impl.dart';
|
||||
import 'package:maibu_satabot_v2/features/device_alarms/domain/usecases/device_alarm_usecases.dart';
|
||||
import 'package:maibu_satabot_v2/features/device_alarms/domain/usecases/load_site_alarm_targets_usecase.dart';
|
||||
import 'package:maibu_satabot_v2/features/device_alarms/presentation/cubit/device_alarms_cubit.dart';
|
||||
import 'package:maibu_satabot_v2/features/v2/device_list/domain/entities/device_entity.dart';
|
||||
import 'package:maibu_satabot_v2/features/v2/device_list/domain/repositories/device_repository.dart';
|
||||
import 'package:maibu_satabot_v2/features/v2/device_list/domain/usecases/get_site_devices_usecase.dart';
|
||||
|
||||
DeviceEntity _device(String sn, {int siteId = 1, bool robot = true}) =>
|
||||
DeviceEntity(
|
||||
deviceId: 'DB-$sn',
|
||||
name: sn,
|
||||
type: 'robot',
|
||||
status: '离线',
|
||||
power: 0,
|
||||
todayEnergy: 0,
|
||||
isRobot: robot,
|
||||
siteId: siteId,
|
||||
);
|
||||
|
||||
class _Devices extends Fake implements DeviceRepository {
|
||||
final rows = <int, List<DeviceEntity>>{
|
||||
1: [
|
||||
_device('A'),
|
||||
_device('B'),
|
||||
_device('A'),
|
||||
_device('PV', robot: false),
|
||||
_device('FOREIGN', siteId: 2),
|
||||
],
|
||||
2: [_device('C', siteId: 2)],
|
||||
3: [_device('D', siteId: 3)],
|
||||
};
|
||||
final calls = <int>[];
|
||||
final pending = <int, Completer<List<DeviceEntity>>>{};
|
||||
@override
|
||||
Future<List<DeviceEntity>> getSiteDevices(int siteId) {
|
||||
calls.add(siteId);
|
||||
return pending[siteId]?.future ?? Future.value(rows[siteId] ?? []);
|
||||
}
|
||||
}
|
||||
|
||||
class _Mqtt extends Fake implements MqttClient {
|
||||
final messages = StreamController<MqttMessage>.broadcast(sync: true);
|
||||
final subscribed = <String>[];
|
||||
final unsubscribed = <String>[];
|
||||
final failNext = <String>{};
|
||||
@override
|
||||
bool get isConnected => true;
|
||||
@override
|
||||
Stream<MqttMessage> get messageStream => messages.stream;
|
||||
@override
|
||||
Future<void> subscribe(String topic) async {
|
||||
subscribed.add(topic);
|
||||
if (failNext.remove(topic)) throw StateError('Subscribe failed');
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> unsubscribe(String topic) async => unsubscribed.add(topic);
|
||||
|
||||
void task(String sn, {String id = 'task-1', double progress = 0.25}) =>
|
||||
messages.add(
|
||||
MqttMessage(
|
||||
topic: 'mower/$sn/task/status/post',
|
||||
payload: jsonEncode({
|
||||
'sn': sn,
|
||||
'task_id': id,
|
||||
'data': {'progress': progress},
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class _Remote extends Fake implements DeviceAlarmRemoteDataSource {}
|
||||
|
||||
Future<void> _flush() => Future<void>.delayed(Duration.zero);
|
||||
|
||||
void main() {
|
||||
late _Devices devices;
|
||||
late _Mqtt mqtt;
|
||||
late MowerRealtimeDataSourceImpl source;
|
||||
late DeviceAlarmsCubit alarms;
|
||||
late SiteDeviceRealtimeSubscriptions subscriptions;
|
||||
|
||||
setUp(() {
|
||||
devices = _Devices();
|
||||
mqtt = _Mqtt();
|
||||
source = MowerRealtimeDataSourceImpl(mqtt);
|
||||
final alarmRepository = DeviceAlarmRepositoryImpl(
|
||||
DeviceAlarmMqttDataSource(mqtt),
|
||||
_Remote(),
|
||||
);
|
||||
alarms = DeviceAlarmsCubit(
|
||||
WatchDeviceAlarmsUseCase(alarmRepository),
|
||||
HandleDeviceAlarmUseCase(alarmRepository),
|
||||
LoadSiteAlarmTargetsUseCase(GetSiteDevicesUseCase(devices)),
|
||||
);
|
||||
subscriptions = SiteDeviceRealtimeSubscriptions(
|
||||
alarms,
|
||||
MowerRealtimeRepositoryImpl(source),
|
||||
);
|
||||
});
|
||||
tearDown(() async {
|
||||
await subscriptions.dispose();
|
||||
await alarms.close();
|
||||
source.dispose();
|
||||
await mqtt.messages.close();
|
||||
});
|
||||
|
||||
test(
|
||||
'device Tab subscribes both topics for every site vehicle, including offline vehicles',
|
||||
() async {
|
||||
await subscriptions.ensureSubscriptions(1);
|
||||
expect(devices.calls, [1]);
|
||||
expect(
|
||||
mqtt.subscribed,
|
||||
unorderedEquals([
|
||||
'device/A/error/post',
|
||||
'device/B/error/post',
|
||||
'device/PV/error/post',
|
||||
'mower/A/task/status/post',
|
||||
'mower/B/task/status/post',
|
||||
'mower/PV/task/status/post',
|
||||
]),
|
||||
);
|
||||
await subscriptions.ensureSubscriptions(1);
|
||||
await subscriptions.ensureSubscriptions(1, refresh: true);
|
||||
expect(devices.calls, [1, 1]);
|
||||
expect(mqtt.subscribed, hasLength(6));
|
||||
expect(mqtt.unsubscribed, isEmpty);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'reports arrive before opening details and survive closing/reopening the panel',
|
||||
() async {
|
||||
await subscriptions.ensureSubscriptions(1);
|
||||
mqtt.task('A');
|
||||
await _flush();
|
||||
final report = await subscriptions
|
||||
.watchTaskStatus(siteId: 1, deviceSn: 'A')
|
||||
.first;
|
||||
expect(report?.progress, 0.25);
|
||||
await _flush();
|
||||
expect(mqtt.unsubscribed, isEmpty);
|
||||
mqtt.task('A', progress: 0.5);
|
||||
await _flush();
|
||||
final next = await subscriptions
|
||||
.watchTaskStatus(siteId: 1, deviceSn: 'A')
|
||||
.first;
|
||||
expect(next?.progress, 0.5);
|
||||
await _flush();
|
||||
expect(mqtt.subscribed, hasLength(6));
|
||||
expect(mqtt.unsubscribed, isEmpty);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'refresh finds new vehicles and retires removed vehicles without resubscribing healthy ones',
|
||||
() async {
|
||||
await subscriptions.ensureSubscriptions(1);
|
||||
devices.rows[1] = [_device('A'), _device('NEW')];
|
||||
await subscriptions.ensureSubscriptions(1, refresh: true);
|
||||
expect(
|
||||
mqtt.subscribed.where((topic) => topic == 'mower/A/task/status/post'),
|
||||
hasLength(1),
|
||||
);
|
||||
expect(
|
||||
mqtt.subscribed,
|
||||
containsAll(['device/NEW/error/post', 'mower/NEW/task/status/post']),
|
||||
);
|
||||
expect(
|
||||
mqtt.unsubscribed,
|
||||
containsAll(['device/B/error/post', 'mower/B/task/status/post']),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'use-time check repairs failed task and alarm listeners while reusing healthy topics',
|
||||
() async {
|
||||
mqtt.failNext.add('mower/A/task/status/post');
|
||||
mqtt.failNext.add('device/A/error/post');
|
||||
await subscriptions.ensureSubscriptions(1);
|
||||
await _flush();
|
||||
await subscriptions.ensureSubscriptions(1);
|
||||
expect(
|
||||
mqtt.subscribed.where((topic) => topic == 'device/A/error/post').length,
|
||||
greaterThanOrEqualTo(2),
|
||||
);
|
||||
expect(
|
||||
mqtt.subscribed.where((topic) => topic == 'mower/A/task/status/post'),
|
||||
hasLength(2),
|
||||
);
|
||||
expect(
|
||||
mqtt.subscribed.where((topic) => topic == 'mower/B/task/status/post'),
|
||||
hasLength(1),
|
||||
);
|
||||
expect(
|
||||
mqtt.subscribed.where((topic) => topic == 'device/B/error/post'),
|
||||
hasLength(1),
|
||||
);
|
||||
mqtt.task('A');
|
||||
await _flush();
|
||||
expect(
|
||||
(await subscriptions.watchTaskStatus(siteId: 1, deviceSn: 'A').first)
|
||||
?.progress,
|
||||
0.25,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'site switch clears old panel data and ignores a late device list from an old site',
|
||||
() async {
|
||||
await subscriptions.ensureSubscriptions(1);
|
||||
final values = <MowerTaskStatusEntity?>[];
|
||||
final panel = subscriptions
|
||||
.watchTaskStatus(siteId: 1, deviceSn: 'A')
|
||||
.listen(values.add);
|
||||
mqtt.task('A');
|
||||
await _flush();
|
||||
expect(values.last?.progress, 0.25);
|
||||
devices.pending[2] = Completer();
|
||||
final oldLoad = subscriptions.ensureSubscriptions(2);
|
||||
await _flush();
|
||||
await subscriptions.ensureSubscriptions(3);
|
||||
devices.pending[2]!.complete(devices.rows[2]);
|
||||
await oldLoad;
|
||||
await _flush();
|
||||
expect(values.last, isNull);
|
||||
expect(
|
||||
mqtt.unsubscribed,
|
||||
containsAll(['device/A/error/post', 'mower/A/task/status/post']),
|
||||
);
|
||||
expect(
|
||||
mqtt.subscribed,
|
||||
containsAll(['device/D/error/post', 'mower/D/task/status/post']),
|
||||
);
|
||||
expect(mqtt.subscribed, isNot(contains('mower/C/task/status/post')));
|
||||
final rosterCalls = devices.calls.length;
|
||||
expect(
|
||||
await subscriptions.watchTaskStatus(siteId: 1, deviceSn: 'A').first,
|
||||
isNull,
|
||||
);
|
||||
expect(devices.calls, hasLength(rosterCalls));
|
||||
await panel.cancel();
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'opening a newly added device repairs the complete site roster',
|
||||
() async {
|
||||
await subscriptions.ensureSubscriptions(1);
|
||||
devices.rows[1] = [_device('A'), _device('B'), _device('NEW')];
|
||||
final panel = subscriptions
|
||||
.watchTaskStatus(siteId: 1, deviceSn: 'NEW')
|
||||
.listen((_) {});
|
||||
await subscriptions.ensureSubscriptions(1);
|
||||
expect(
|
||||
mqtt.subscribed,
|
||||
containsAll(['mower/NEW/task/status/post', 'device/NEW/error/post']),
|
||||
);
|
||||
expect(
|
||||
mqtt.subscribed.where((topic) => topic == 'mower/A/task/status/post'),
|
||||
hasLength(1),
|
||||
);
|
||||
await panel.cancel();
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'concurrent entry and detail checks share the same in-flight site load',
|
||||
() async {
|
||||
devices.pending[1] = Completer();
|
||||
final first = subscriptions.ensureSubscriptions(1);
|
||||
final second = subscriptions.ensureSubscriptions(1, refresh: true);
|
||||
final panel = subscriptions
|
||||
.watchTaskStatus(siteId: 1, deviceSn: 'A')
|
||||
.listen((_) {});
|
||||
await _flush();
|
||||
expect(devices.calls, [1]);
|
||||
devices.pending[1]!.complete(devices.rows[1]);
|
||||
await Future.wait([first, second]);
|
||||
await _flush();
|
||||
expect(mqtt.subscribed, hasLength(6));
|
||||
await panel.cancel();
|
||||
await subscriptions.ensureSubscriptions(null);
|
||||
expect(mqtt.unsubscribed, hasLength(6));
|
||||
expect(alarms.state.siteId, isNull);
|
||||
},
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user