import 'dart:async'; import 'dart:convert'; import 'package:web_socket_channel/web_socket_channel.dart'; /// A deterministic websocket channel for the Settings tests. It records every /// outgoing request and lets the test complete readiness and deliver replies. class FakeChannel implements WebSocketChannel { FakeChannel(this.uri); final Uri uri; final StreamController incoming = StreamController(); final List outgoing = []; final Completer readyCompleter = Completer(); bool _closed = false; void markReady() { if (!readyCompleter.isCompleted) readyCompleter.complete(); } void reply(Map message) { if (!incoming.isClosed) incoming.add(jsonEncode(message)); } void fail(String message) { if (!incoming.isClosed) incoming.addError(StateError(message)); } void closeStream() { if (!incoming.isClosed) { _closed = true; incoming.close(); } } List> get decodedOutgoing => outgoing .map((item) => jsonDecode(item) as Map) .toList(growable: false); @override Stream get stream => incoming.stream; @override WebSocketSink get sink => _FakeSink(this); @override Future get ready => readyCompleter.future; @override String? get protocol => null; @override int? get closeCode => _closed ? 1000 : null; @override String? get closeReason => null; @override noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); } class _FakeSink implements WebSocketSink { _FakeSink(this.channel); final FakeChannel channel; @override void add(dynamic event) { if (event is String) channel.outgoing.add(event); } @override void addError(Object error, [StackTrace? stackTrace]) => throw error; @override Future addStream(Stream stream) async { await for (final item in stream) { add(item); } } @override Future close([int? closeCode, String? closeReason]) async { channel.closeStream(); } @override Future get done async {} @override noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); } /// Records every channel the client asks for, so tests can prove that a rebuild /// or an invalid URL opened no socket at all. class FakeChannelFactory { final List channels = []; final List uris = []; FakeChannel get last => channels.last; WebSocketChannel call(Uri uri) { uris.add(uri); final channel = FakeChannel(uri); channels.add(channel); return channel; } } /// Let queued microtasks (state events, request sends, replies) run. Future settle() async { for (var i = 0; i < 4; i++) { await Future.delayed(Duration.zero); } }