import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:busylight_buddy/models/busylight_color.dart'; import 'package:busylight_buddy/models/busylight_status.dart'; import 'package:busylight_buddy/providers/busylight_provider.dart'; import 'package:busylight_buddy/services/busylight_service.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; class FakeBusylightService extends BusylightService { FakeBusylightService() : super(baseUrl: 'http://localhost'); final updates = StreamController.broadcast(); int connections = 0; int statusRequests = 0; int colorRequests = 0; @override Stream watchStatus() { connections++; return updates.stream; } @override Future getStatus() async { statusRequests++; return BusylightStatus.off; } @override Future getColor() async { colorRequests++; return BusylightColor.white; } @override Future setStatus(BusylightStatus status) async => status; } Future waitUntil(bool Function() condition) async { final deadline = DateTime.now().add(const Duration(seconds: 3)); while (!condition()) { if (DateTime.now().isAfter(deadline)) fail('Condition was not reached'); await Future.delayed(const Duration(milliseconds: 5)); } } const update = BusylightUpdate( status: BusylightStatus.colored, color: BusylightColor(r: 12, g: 34, b: 56, brightness: 0.7), ); void main() { test('decodes initial and subsequent messages from /ws/status', () async { final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); final sockets = []; addTearDown(() async { for (final socket in sockets) { await socket.close(); } await server.close(force: true); }); server.listen((request) async { expect(request.uri.path, '/ws/status'); final socket = await WebSocketTransformer.upgrade(request); sockets.add(socket); socket.add(jsonEncode({ 'status': 'available', 'color': [0, 255, 0], 'brightness': 0.3, })); socket.add(utf8.encode(jsonEncode({ 'status': 'colored', 'color': [12, 34, 56], 'brightness': 0.7, }))); await socket.close(); }); final service = BusylightService( baseUrl: 'http://127.0.0.1:${server.port}', ); final messages = await service.watchStatus().toList(); expect(messages.map((message) => message.status), [BusylightStatus.available, BusylightStatus.colored]); expect(messages.last.color.r, 12); expect(messages.last.color.g, 34); expect(messages.last.color.b, 56); expect(messages.last.color.brightness, 0.7); }); test('live updates initialize without REST and reconnect after errors', () async { final service = FakeBusylightService(); final container = ProviderContainer(overrides: [ busylightServiceProvider.overrideWithValue(service), busylightSnapshotProvider.overrideWith((ref) => LiveStatusNotifier( ref.watch(busylightServiceProvider), reconnectDelay: const Duration(milliseconds: 5), )), ]); addTearDown(() async { container.dispose(); await service.updates.close(); }); expect(container.read(busylightStatusProvider).isLoading, isTrue); await waitUntil(() => service.updates.hasListener); service.updates.add(update); await waitUntil(() => container.read(brightnessProvider) == 0.7); expect(container.read(busylightStatusProvider).value, update.status); expect(container.read(colorProvider).r, 12); expect(container.read(colorProvider).g, 34); expect(container.read(colorProvider).b, 56); service.updates.addError(StateError('Disconnected')); await waitUntil(() => service.connections == 2); service.updates.add(const BusylightUpdate( status: BusylightStatus.busy, color: BusylightColor.red, )); await waitUntil(() => container.read(busylightStatusProvider).value == BusylightStatus.busy); expect(service.statusRequests, 0); expect(service.colorRequests, 0); }); test('socket closure retains the last state without REST polling', () async { final service = FakeBusylightService(); final container = ProviderContainer(overrides: [ busylightServiceProvider.overrideWithValue(service), ]); addTearDown(container.dispose); container.read(busylightSnapshotProvider); await waitUntil(() => service.updates.hasListener); service.updates.add(update); await waitUntil(() => container.read(brightnessProvider) == 0.7); await service.updates.close(); await waitUntil(() => container.read(busylightSnapshotProvider).hasError); expect(container.read(busylightStatusProvider).value, update.status); expect(container.read(brightnessProvider), 0.7); expect(service.statusRequests, 0); expect(service.colorRequests, 0); }); test('changing the device cancels the old subscription', () async { final first = FakeBusylightService(); final second = FakeBusylightService(); final container = ProviderContainer(overrides: [ deviceHostProvider.overrideWith((ref) => 'first'), busylightServiceProvider.overrideWith((ref) => ref.watch(deviceHostProvider) == 'first' ? first : second), ]); addTearDown(() async { container.dispose(); await first.updates.close(); await second.updates.close(); }); final subscription = container.listen(busylightSnapshotProvider, (_, next) {}); addTearDown(subscription.close); await waitUntil(() => first.updates.hasListener); container.read(deviceHostProvider.notifier).state = 'second'; await waitUntil(() => second.updates.hasListener); expect(first.updates.hasListener, isFalse); second.updates.add(update); await waitUntil(() => container.read(brightnessProvider) == 0.7); container.dispose(); expect(second.updates.hasListener, isFalse); }); test('a stale command response cannot overwrite a pushed status', () async { final notifier = BusylightStateNotifier( FakeBusylightService(), BusylightStatus.off, ); addTearDown(notifier.dispose); final command = notifier.setStatus(BusylightStatus.available); notifier.setLocalStatus(BusylightStatus.busy); await command; expect(notifier.state.value, BusylightStatus.busy); }); }