Migrate to ChannelBuffers.push (#81235)
This commit is contained in:
@@ -13,8 +13,8 @@ import 'package:path/path.dart' as path;
|
||||
// ignore: deprecated_member_use
|
||||
import 'package:test_api/test_api.dart' as test_package;
|
||||
|
||||
|
||||
import 'binding.dart';
|
||||
import 'deprecated.dart';
|
||||
|
||||
/// Ensure the [WidgetsBinding] is initialized.
|
||||
WidgetsBinding ensureInitialized([@visibleForTesting Map<String, String>? environment]) {
|
||||
|
||||
@@ -15,8 +15,7 @@ import 'package:flutter/services.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:flutter_test/flutter_test.dart' show TestWindow;
|
||||
import 'package:stack_trace/stack_trace.dart' as stack_trace;
|
||||
// ignore: deprecated_member_use
|
||||
import 'package:test_api/test_api.dart' as test_package;
|
||||
import 'package:test_api/test_api.dart' as test_package; // ignore: deprecated_member_use
|
||||
import 'package:vector_math/vector_math_64.dart';
|
||||
|
||||
import '_binding_io.dart' if (dart.library.html) '_binding_web.dart' as binding;
|
||||
@@ -25,6 +24,7 @@ import 'platform.dart';
|
||||
import 'restoration.dart';
|
||||
import 'stack_manipulation.dart';
|
||||
import 'test_async_utils.dart';
|
||||
import 'test_default_binary_messenger.dart';
|
||||
import 'test_exception_reporter.dart';
|
||||
import 'test_text_input.dart';
|
||||
|
||||
@@ -79,74 +79,29 @@ enum TestBindingEventSource {
|
||||
|
||||
const Size _kDefaultTestViewportSize = Size(800.0, 600.0);
|
||||
|
||||
/// A [BinaryMessenger] subclass that is used as the default binary messenger
|
||||
/// under testing environment.
|
||||
/// Overrides the [ServicesBinding]'s binary messenger logic to use
|
||||
/// [TestDefaultBinaryMessenger].
|
||||
///
|
||||
/// It tracks status of data sent across the Flutter platform barrier, which is
|
||||
/// useful for testing frameworks to monitor and synchronize against the
|
||||
/// platform messages.
|
||||
class TestDefaultBinaryMessenger extends BinaryMessenger {
|
||||
/// Creates a [TestDefaultBinaryMessenger] instance.
|
||||
///
|
||||
/// The [delegate] instance must not be null.
|
||||
TestDefaultBinaryMessenger(this.delegate): assert(delegate != null);
|
||||
|
||||
/// The delegate [BinaryMessenger].
|
||||
final BinaryMessenger delegate;
|
||||
|
||||
final List<Future<ByteData?>> _pendingMessages = <Future<ByteData?>>[];
|
||||
|
||||
/// The number of incomplete/pending calls sent to the platform channels.
|
||||
int get pendingMessageCount => _pendingMessages.length;
|
||||
|
||||
/// Test bindings that are used by tests that mock message handlers for plugins
|
||||
/// should mix in this binding to enable the use of the
|
||||
/// [TestDefaultBinaryMessenger] APIs.
|
||||
mixin TestDefaultBinaryMessengerBinding on BindingBase, ServicesBinding {
|
||||
@override
|
||||
Future<ByteData?>? send(String channel, ByteData? message) {
|
||||
final Future<ByteData?>? resultFuture = delegate.send(channel, message);
|
||||
if (resultFuture != null) {
|
||||
_pendingMessages.add(resultFuture);
|
||||
resultFuture
|
||||
.catchError((Object error) { /* errors are the responsibility of the caller */ })
|
||||
.whenComplete(() => _pendingMessages.remove(resultFuture));
|
||||
}
|
||||
return resultFuture;
|
||||
void initInstances() {
|
||||
super.initInstances();
|
||||
_instance = this;
|
||||
}
|
||||
|
||||
/// Returns a Future that completes after all the platform calls are finished.
|
||||
///
|
||||
/// If a new platform message is sent after this method is called, this new
|
||||
/// message is not tracked. Use with [pendingMessageCount] to guarantee no
|
||||
/// pending message calls.
|
||||
Future<void> get platformMessagesFinished {
|
||||
return Future.wait<void>(_pendingMessages);
|
||||
}
|
||||
/// The current [TestDefaultBinaryMessengerBinding], if one has been created.
|
||||
static TestDefaultBinaryMessengerBinding? get instance => _instance;
|
||||
static TestDefaultBinaryMessengerBinding? _instance;
|
||||
|
||||
@override
|
||||
Future<void> handlePlatformMessage(
|
||||
String channel,
|
||||
ByteData? data,
|
||||
ui.PlatformMessageResponseCallback? callback,
|
||||
) {
|
||||
return delegate.handlePlatformMessage(channel, data, callback);
|
||||
}
|
||||
TestDefaultBinaryMessenger get defaultBinaryMessenger => super.defaultBinaryMessenger as TestDefaultBinaryMessenger;
|
||||
|
||||
@override
|
||||
void setMessageHandler(String channel, MessageHandler? handler) {
|
||||
delegate.setMessageHandler(channel, handler);
|
||||
}
|
||||
|
||||
@override
|
||||
bool checkMessageHandler(String channel, MessageHandler? handler) {
|
||||
return delegate.checkMessageHandler(channel, handler);
|
||||
}
|
||||
|
||||
@override
|
||||
void setMockMessageHandler(String channel, MessageHandler? handler) {
|
||||
delegate.setMockMessageHandler(channel, handler);
|
||||
}
|
||||
|
||||
@override
|
||||
bool checkMockMessageHandler(String channel, MessageHandler? handler) {
|
||||
return delegate.checkMockMessageHandler(channel, handler);
|
||||
TestDefaultBinaryMessenger createBinaryMessenger() {
|
||||
return TestDefaultBinaryMessenger(super.createBinaryMessenger());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -171,7 +126,8 @@ abstract class TestWidgetsFlutterBinding extends BindingBase
|
||||
SemanticsBinding,
|
||||
RendererBinding,
|
||||
PaintingBinding,
|
||||
WidgetsBinding {
|
||||
WidgetsBinding,
|
||||
TestDefaultBinaryMessengerBinding {
|
||||
|
||||
/// Constructor for [TestWidgetsFlutterBinding].
|
||||
///
|
||||
@@ -195,9 +151,15 @@ abstract class TestWidgetsFlutterBinding extends BindingBase
|
||||
|
||||
/// Called by the test framework at the beginning of a widget test to
|
||||
/// prepare the binding for the next test.
|
||||
///
|
||||
/// If [registerTestTextInput] returns true when this method is called,
|
||||
/// the [testTextInput] is configured to simulate the keyboard.
|
||||
void reset() {
|
||||
_restorationManager = null;
|
||||
resetGestureBinding();
|
||||
testTextInput.reset();
|
||||
if (registerTestTextInput)
|
||||
_testTextInput.register();
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -237,7 +199,8 @@ abstract class TestWidgetsFlutterBinding extends BindingBase
|
||||
@protected
|
||||
bool get overrideHttpClient => true;
|
||||
|
||||
/// Determines whether the binding automatically registers [testTextInput].
|
||||
/// Determines whether the binding automatically registers [testTextInput] as
|
||||
/// a fake keyboard implementation.
|
||||
///
|
||||
/// Unit tests make use of this to mock out text input communication for
|
||||
/// widgets. An integration test would set this to false, to test real IME
|
||||
@@ -245,6 +208,19 @@ abstract class TestWidgetsFlutterBinding extends BindingBase
|
||||
///
|
||||
/// [TestTextInput.isRegistered] reports whether the text input mock is
|
||||
/// registered or not.
|
||||
///
|
||||
/// Some of the properties and methods on [testTextInput] are only valid if
|
||||
/// [registerTestTextInput] returns true when a test starts. If those
|
||||
/// members are accessed when using a binding that sets this flag to false,
|
||||
/// they will throw.
|
||||
///
|
||||
/// If this property returns true when a test ends, the [testTextInput] is
|
||||
/// unregistered.
|
||||
///
|
||||
/// This property should not change the value it returns during the lifetime
|
||||
/// of the binding. Changing the value of this property risks very confusing
|
||||
/// behavior as the [TestTextInput] may be inconsistently registered or
|
||||
/// unregistered.
|
||||
@protected
|
||||
bool get registerTestTextInput => true;
|
||||
|
||||
@@ -319,9 +295,6 @@ abstract class TestWidgetsFlutterBinding extends BindingBase
|
||||
binding.setupHttpOverrides();
|
||||
}
|
||||
_testTextInput = TestTextInput(onCleared: _resetFocusedEditable);
|
||||
if (registerTestTextInput) {
|
||||
_testTextInput.register();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -331,11 +304,6 @@ abstract class TestWidgetsFlutterBinding extends BindingBase
|
||||
// doesn't get generated for tests.
|
||||
}
|
||||
|
||||
@override
|
||||
BinaryMessenger createBinaryMessenger() {
|
||||
return TestDefaultBinaryMessenger(super.createBinaryMessenger());
|
||||
}
|
||||
|
||||
/// Whether there is currently a test executing.
|
||||
bool get inTest;
|
||||
|
||||
@@ -515,12 +483,20 @@ abstract class TestWidgetsFlutterBinding extends BindingBase
|
||||
TestTextInput get testTextInput => _testTextInput;
|
||||
late TestTextInput _testTextInput;
|
||||
|
||||
/// The current client of the onscreen keyboard. Callers must pump
|
||||
/// an additional frame after setting this property to complete the
|
||||
/// focus change.
|
||||
/// The [State] of the current [EditableText] client of the onscreen keyboard.
|
||||
///
|
||||
/// Setting this property to a new value causes the given [EditableTextState]
|
||||
/// to focus itself and request the keyboard to establish a
|
||||
/// [TextInputConnection].
|
||||
///
|
||||
/// Callers must pump an additional frame after setting this property to
|
||||
/// complete the focus change.
|
||||
///
|
||||
/// Instead of setting this directly, consider using
|
||||
/// [WidgetTester.showKeyboard].
|
||||
//
|
||||
// TODO(ianh): We should just remove this property and move the call to
|
||||
// requestKeyboard to the WidgetTester.showKeyboard method.
|
||||
EditableTextState? get focusedEditable => _focusedEditable;
|
||||
EditableTextState? _focusedEditable;
|
||||
set focusedEditable(EditableTextState? value) {
|
||||
@@ -799,6 +775,8 @@ abstract class TestWidgetsFlutterBinding extends BindingBase
|
||||
// alone so that we don't cause more spurious errors.
|
||||
runApp(Container(key: UniqueKey(), child: _postTestMessage)); // Unmount any remaining widgets.
|
||||
await pump();
|
||||
if (registerTestTextInput)
|
||||
_testTextInput.unregister();
|
||||
invariantTester();
|
||||
_verifyAutoUpdateGoldensUnset(autoUpdateGoldensBeforeTest && !isBrowser);
|
||||
_verifyReportTestExceptionUnset(reportTestExceptionBeforeTest);
|
||||
|
||||
109
packages/flutter_test/lib/src/deprecated.dart
Normal file
109
packages/flutter_test/lib/src/deprecated.dart
Normal file
@@ -0,0 +1,109 @@
|
||||
// Copyright 2014 The Flutter Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import 'binding.dart';
|
||||
|
||||
// TODO(ianh): Once https://github.com/dart-lang/dartdoc/issues/2033 is fixed, update the hyperlinks marked HYPERLINK below.
|
||||
// TODO(ianh): Once cocoon and other customer_tests are migrated, deprecate these transitional APIs
|
||||
|
||||
/// Shim to support the obsolete [setMockMessageHandler] and
|
||||
/// [checkMockMessageHandler] methods on [BinaryMessenger] in tests.
|
||||
///
|
||||
/// The implementations defer to [TestDefaultBinaryMessengerBinding.defaultBinaryMessenger].
|
||||
///
|
||||
/// Rather than calling [setMockMessageHandler] on the
|
||||
/// `ServicesBinding.defaultBinaryMessenger`, use
|
||||
/// `tester.binding.defaultBinaryMessenger.setMockMessageHandler` directly. This
|
||||
/// more accurately represents the actual method invocation.
|
||||
extension TestBinaryMessengerExtension on BinaryMessenger {
|
||||
/// Shim for `TestDefaultBinaryMessenger.setMockMessageHandler`.
|
||||
// HYPERLINK ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
// TODO(ianh): deprecate this method: @NotYetDeprecated(
|
||||
// 'Use tester.binding.defaultBinaryMessenger.setMockMessageHandler or '
|
||||
// 'TestDefaultBinaryMessenger.instance.defaultBinaryMessenger.setMockMessageHandler instead. '
|
||||
// 'This feature was deprecated after v2.1.0-10.0.pre.'
|
||||
// )
|
||||
void setMockMessageHandler(String channel, MessageHandler? handler) {
|
||||
TestDefaultBinaryMessengerBinding.instance!.defaultBinaryMessenger.setMockMessageHandler(channel, handler);
|
||||
}
|
||||
|
||||
/// Shim for `TestDefaultBinaryMessenger.checkMockMessageHandler`.
|
||||
// HYPERLINK ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
// TODO(ianh): deprecate this method: @NotYetDeprecated(
|
||||
// 'Use tester.binding.defaultBinaryMessenger.checkMockMessageHandler or '
|
||||
// 'TestDefaultBinaryMessenger.instance.defaultBinaryMessenger.checkMockMessageHandler instead.'
|
||||
// 'This feature was deprecated after v2.1.0-10.0.pre.'
|
||||
// )
|
||||
bool checkMockMessageHandler(String channel, Object? handler) {
|
||||
return TestDefaultBinaryMessengerBinding.instance!.defaultBinaryMessenger.checkMockMessageHandler(channel, handler);
|
||||
}
|
||||
}
|
||||
|
||||
/// Shim to support the obsolete [setMockMessageHandler] and
|
||||
/// [checkMockMessageHandler] methods on [BasicMessageChannel] in tests.
|
||||
///
|
||||
/// The implementations defer to [TestDefaultBinaryMessengerBinding.defaultBinaryMessenger].
|
||||
///
|
||||
/// Rather than calling [setMockMessageHandler] on the message channel, use
|
||||
/// `tester.binding.defaultBinaryMessenger.setMockDecodedMessageHandler`
|
||||
/// directly. This more accurately represents the actual method invocation.
|
||||
extension TestBasicMessageChannelExtension<T> on BasicMessageChannel<T> {
|
||||
/// Shim for `TestDefaultBinaryMessenger.setMockDecodedMessageHandler`.
|
||||
// HYPERLINK ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
// TODO(ianh): deprecate this method: @NotYetDeprecated(
|
||||
// 'Use tester.binding.defaultBinaryMessenger.setMockDecodedMessageHandler or '
|
||||
// 'TestDefaultBinaryMessenger.instance.defaultBinaryMessenger.setMockDecodedMessageHandler instead. '
|
||||
// 'This feature was deprecated after v2.1.0-10.0.pre.'
|
||||
// )
|
||||
void setMockMessageHandler(Future<T> Function(T? message)? handler) {
|
||||
TestDefaultBinaryMessengerBinding.instance!.defaultBinaryMessenger.setMockDecodedMessageHandler<T>(this, handler);
|
||||
}
|
||||
|
||||
/// Shim for `TestDefaultBinaryMessenger.checkMockMessageHandler`.
|
||||
// HYPERLINK ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
// TODO(ianh): deprecate this method: @NotYetDeprecated(
|
||||
// 'Use tester.binding.defaultBinaryMessenger.checkMockMessageHandler or '
|
||||
// 'TestDefaultBinaryMessenger.instance.defaultBinaryMessenger.checkMockMessageHandler instead. '
|
||||
// 'For the first argument, pass channel.name. '
|
||||
// 'This feature was deprecated after v2.1.0-10.0.pre.'
|
||||
// )
|
||||
bool checkMockMessageHandler(Object? handler) {
|
||||
return TestDefaultBinaryMessengerBinding.instance!.defaultBinaryMessenger.checkMockMessageHandler(name, handler);
|
||||
}
|
||||
}
|
||||
|
||||
/// Shim to support the obsolete [setMockMethodCallHandler] and
|
||||
/// [checkMockMethodCallHandler] methods on [MethodChannel] in tests.
|
||||
///
|
||||
/// The implementations defer to [TestDefaultBinaryMessengerBinding.defaultBinaryMessenger].
|
||||
///
|
||||
/// Rather than calling [setMockMethodCallHandler] on the method channel, use
|
||||
/// `tester.binding.defaultBinaryMessenger.setMockMethodCallHandler` directly.
|
||||
/// This more accurately represents the actual method invocation.
|
||||
extension TestMethodChannelExtension on MethodChannel {
|
||||
/// Shim for `TestDefaultBinaryMessenger.setMockMethodCallHandler`.
|
||||
// HYPERLINK ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
// TODO(ianh): deprecate this method: @NotYetDeprecated(
|
||||
// 'Use tester.binding.defaultBinaryMessenger.setMockMethodCallHandler or '
|
||||
// 'TestDefaultBinaryMessenger.instance.defaultBinaryMessenger.setMockMethodCallHandler instead. '
|
||||
// 'This feature was deprecated after v2.1.0-10.0.pre.'
|
||||
// )
|
||||
void setMockMethodCallHandler(Future<dynamic>? Function(MethodCall call)? handler) {
|
||||
TestDefaultBinaryMessengerBinding.instance!.defaultBinaryMessenger.setMockMethodCallHandler(this, handler);
|
||||
}
|
||||
|
||||
/// Shim for `TestDefaultBinaryMessenger.checkMockMessageHandler`.
|
||||
// HYPERLINK ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
// TODO(ianh): deprecate this method: @NotYetDeprecated(
|
||||
// 'Use tester.binding.defaultBinaryMessenger.checkMockMessageHandler or '
|
||||
// 'TestDefaultBinaryMessenger.instance.defaultBinaryMessenger.checkMockMessageHandler instead. '
|
||||
// 'For the first argument, pass channel.name. '
|
||||
// 'This feature was deprecated after v2.1.0-10.0.pre.'
|
||||
// )
|
||||
bool checkMockMethodCallHandler(Object? handler) {
|
||||
return TestDefaultBinaryMessengerBinding.instance!.defaultBinaryMessenger.checkMockMessageHandler(name, handler);
|
||||
}
|
||||
}
|
||||
@@ -2,10 +2,13 @@
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/foundation.dart' show kIsWeb;
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import 'binding.dart';
|
||||
import 'test_async_utils.dart';
|
||||
|
||||
// TODO(gspencergoog): Replace this with more robust key simulation code once
|
||||
@@ -637,21 +640,20 @@ class KeyEventSimulator {
|
||||
assert(_osIsSupported(platform!), 'Platform $platform not supported for key simulation');
|
||||
|
||||
final Map<String, dynamic> data = getKeyData(key, platform: platform!, isDown: true, physicalKey: physicalKey);
|
||||
bool result = false;
|
||||
await ServicesBinding.instance!.defaultBinaryMessenger.handlePlatformMessage(
|
||||
final Completer<bool> result = Completer<bool>();
|
||||
await TestDefaultBinaryMessengerBinding.instance!.defaultBinaryMessenger.handlePlatformMessage(
|
||||
SystemChannels.keyEvent.name,
|
||||
SystemChannels.keyEvent.codec.encodeMessage(data),
|
||||
(ByteData? data) {
|
||||
if (data == null) {
|
||||
result.complete(false);
|
||||
return;
|
||||
}
|
||||
final Map<String, dynamic> decoded = SystemChannels.keyEvent.codec.decodeMessage(data) as Map<String, dynamic>;
|
||||
if (decoded['handled'] as bool) {
|
||||
result = true;
|
||||
}
|
||||
result.complete(decoded['handled'] as bool);
|
||||
}
|
||||
);
|
||||
return result;
|
||||
return result.future;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -677,7 +679,7 @@ class KeyEventSimulator {
|
||||
|
||||
final Map<String, dynamic> data = getKeyData(key, platform: platform!, isDown: false, physicalKey: physicalKey);
|
||||
bool result = false;
|
||||
await ServicesBinding.instance!.defaultBinaryMessenger.handlePlatformMessage(
|
||||
await TestDefaultBinaryMessengerBinding.instance!.defaultBinaryMessenger.handlePlatformMessage(
|
||||
SystemChannels.keyEvent.name,
|
||||
SystemChannels.keyEvent.codec.encodeMessage(data),
|
||||
(ByteData? data) {
|
||||
|
||||
306
packages/flutter_test/lib/src/test_default_binary_messenger.dart
Normal file
306
packages/flutter_test/lib/src/test_default_binary_messenger.dart
Normal file
@@ -0,0 +1,306 @@
|
||||
// Copyright 2014 The Flutter Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:ui' as ui;
|
||||
|
||||
import 'package:fake_async/fake_async.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
/// A [BinaryMessenger] subclass that is used as the default binary messenger
|
||||
/// under testing environment.
|
||||
///
|
||||
/// It tracks status of data sent across the Flutter platform barrier, which is
|
||||
/// useful for testing frameworks to monitor and synchronize against the
|
||||
/// platform messages.
|
||||
///
|
||||
/// ## Messages from the framework to the platform
|
||||
///
|
||||
/// Messages are sent from the framework to the platform via the
|
||||
/// [send] method.
|
||||
///
|
||||
/// To intercept a message sent from the framework to the platform,
|
||||
/// consider using [setMockMessageHandler],
|
||||
/// [setMockDecodedMessageHandler], and [setMockMethodCallHandler]
|
||||
/// (see also [checkMockMessageHandler]).
|
||||
///
|
||||
/// To wait for all pending framework-to-platform messages, the
|
||||
/// [platformMessagesFinished] getter provides an appropriate
|
||||
/// [Future]. The [pendingMessageCount] getter returns the current
|
||||
/// number of outstanding messages.
|
||||
///
|
||||
/// ## Messages from the platform to the framework
|
||||
///
|
||||
/// The platform sends messages via the [ChannelBuffers] API. Mock
|
||||
/// messages can be sent to the framework using
|
||||
/// [handlePlatformMessage].
|
||||
///
|
||||
/// Listeners for these messages are configured using [setMessageHandler].
|
||||
class TestDefaultBinaryMessenger extends BinaryMessenger {
|
||||
/// Creates a [TestDefaultBinaryMessenger] instance.
|
||||
///
|
||||
/// The [delegate] instance must not be null.
|
||||
TestDefaultBinaryMessenger(this.delegate): assert(delegate != null);
|
||||
|
||||
/// The delegate [BinaryMessenger].
|
||||
final BinaryMessenger delegate;
|
||||
|
||||
// The handlers for messages from the engine (including fake
|
||||
// messages sent by handlePlatformMessage).
|
||||
final Map<String, MessageHandler> _inboundHandlers = <String, MessageHandler>{};
|
||||
|
||||
/// Send a mock message to the framework as if it came from the platform.
|
||||
///
|
||||
/// If a listener has been set using [setMessageHandler], that listener is
|
||||
/// invoked to handle the message, and this method returns a future that
|
||||
/// completes with that handler's result.
|
||||
///
|
||||
/// {@template flutter.flutter_test.TestDefaultBinaryMessenger.handlePlatformMessage.asyncHandlers}
|
||||
/// It is strongly recommended that all handlers used with this API be
|
||||
/// synchronous (not requiring any microtasks to complete), because
|
||||
/// [testWidgets] tests run in a [FakeAsync] zone in which microtasks do not
|
||||
/// progress except when time is explicitly advanced (e.g. with
|
||||
/// [WidgetTester.pump]), which means that `await`ing a [Future] will result
|
||||
/// in the test hanging.
|
||||
/// {@endtemplate}
|
||||
///
|
||||
/// If no listener is configured, this method returns right away with null.
|
||||
///
|
||||
/// The `callback` argument, if non-null, will be called just before this
|
||||
/// method's future completes, either with the result of the listener
|
||||
/// registered with [setMessageHandler], or with null if no listener has
|
||||
/// been registered.
|
||||
///
|
||||
/// Messages can also be sent via [ChannelBuffers.push] (see
|
||||
/// [ServicesBinding.channelBuffers]); the effect is the same, though that API
|
||||
/// will not wait for a response.
|
||||
// TODO(ianh): When the superclass `handlePlatformMessage` is removed,
|
||||
// remove this @override (but leave the method).
|
||||
@override
|
||||
Future<ByteData?> handlePlatformMessage(
|
||||
String channel,
|
||||
ByteData? data,
|
||||
ui.PlatformMessageResponseCallback? callback,
|
||||
) {
|
||||
Future<ByteData?>? result;
|
||||
if (_inboundHandlers.containsKey(channel))
|
||||
result = _inboundHandlers[channel]!(data);
|
||||
result ??= Future<ByteData?>.value(null);
|
||||
if (callback != null)
|
||||
result = result.then((ByteData? result) { callback(result); return result; });
|
||||
return result;
|
||||
}
|
||||
|
||||
@override
|
||||
void setMessageHandler(String channel, MessageHandler? handler) {
|
||||
if (handler == null) {
|
||||
_inboundHandlers.remove(channel);
|
||||
delegate.setMessageHandler(channel, null);
|
||||
} else {
|
||||
_inboundHandlers[channel] = handler; // used to handle fake messages sent via handlePlatformMessage
|
||||
delegate.setMessageHandler(channel, handler); // used to handle real messages from the engine
|
||||
}
|
||||
}
|
||||
|
||||
final List<Future<ByteData?>> _pendingMessages = <Future<ByteData?>>[];
|
||||
|
||||
/// The number of incomplete/pending calls sent to the platform channels.
|
||||
int get pendingMessageCount => _pendingMessages.length;
|
||||
|
||||
// Handlers that intercept and respond to outgoing messages,
|
||||
// pretending to be the platform.
|
||||
final Map<String, MessageHandler> _outboundHandlers = <String, MessageHandler>{};
|
||||
|
||||
// The outbound callbacks that were actually registered, so that we
|
||||
// can implement the [checkMockMessageHandler] method.
|
||||
final Map<String, Object> _outboundHandlerIdentities = <String, Object>{};
|
||||
|
||||
@override
|
||||
Future<ByteData?>? send(String channel, ByteData? message) {
|
||||
final Future<ByteData?>? resultFuture;
|
||||
final MessageHandler? handler = _outboundHandlers[channel];
|
||||
if (handler != null) {
|
||||
resultFuture = handler(message);
|
||||
} else {
|
||||
resultFuture = delegate.send(channel, message);
|
||||
}
|
||||
if (resultFuture != null) {
|
||||
_pendingMessages.add(resultFuture);
|
||||
resultFuture
|
||||
.catchError((Object error) { /* errors are the responsibility of the caller */ })
|
||||
.whenComplete(() => _pendingMessages.remove(resultFuture));
|
||||
}
|
||||
return resultFuture;
|
||||
}
|
||||
|
||||
/// Returns a Future that completes after all the platform calls are finished.
|
||||
///
|
||||
/// If a new platform message is sent after this method is called, this new
|
||||
/// message is not tracked. Use with [pendingMessageCount] to guarantee no
|
||||
/// pending message calls.
|
||||
Future<void> get platformMessagesFinished {
|
||||
return Future.wait<void>(_pendingMessages);
|
||||
}
|
||||
|
||||
/// Set a callback for intercepting messages sent to the platform on
|
||||
/// the given channel, without decoding them.
|
||||
///
|
||||
/// Intercepted messages are not forwarded to the platform.
|
||||
///
|
||||
/// The given callback will replace the currently registered
|
||||
/// callback for that channel, if any. To stop intercepting messages
|
||||
/// at all, pass null as the handler.
|
||||
///
|
||||
/// The handler's return value, if non-null, is used as a response,
|
||||
/// unencoded.
|
||||
///
|
||||
/// {@macro flutter.flutter_test.TestDefaultBinaryMessenger.handlePlatformMessage.asyncHandlers}
|
||||
///
|
||||
/// The `identity` argument, if non-null, is used to identify the
|
||||
/// callback when checked by [checkMockMessageHandler]. If null, the
|
||||
/// `handler` is used instead. (This allows closures to be passed as
|
||||
/// the `handler` with an alias used as the `identity` so that a
|
||||
/// reference to the closure need not be used. In practice, this is
|
||||
/// used by [setMockDecodedMessageHandler] and
|
||||
/// [setMockMethodCallHandler] to allow [checkMockMessageHandler] to
|
||||
/// recognize the closures that were passed to those methods even
|
||||
/// though those methods wrap those closures when passing them to
|
||||
/// this method.)
|
||||
///
|
||||
/// Registered callbacks are cleared after each test.
|
||||
///
|
||||
/// See also:
|
||||
///
|
||||
/// * [checkMockMessageHandler], which can verify if a handler is still
|
||||
/// registered, which is useful in tests to ensure that no unexpected
|
||||
/// handlers are being registered.
|
||||
///
|
||||
/// * [setMockDecodedMessageHandler], which wraps this method but
|
||||
/// decodes the messages using a [MessageCodec].
|
||||
///
|
||||
/// * [setMockMethodCallHandler], which wraps this method but decodes
|
||||
/// the messages using a [MethodCodec].
|
||||
void setMockMessageHandler(String channel, MessageHandler? handler, [ Object? identity ]) {
|
||||
if (handler == null) {
|
||||
_outboundHandlers.remove(channel);
|
||||
_outboundHandlerIdentities.remove(channel);
|
||||
} else {
|
||||
identity ??= handler;
|
||||
_outboundHandlers[channel] = handler;
|
||||
_outboundHandlerIdentities[channel] = identity;
|
||||
}
|
||||
}
|
||||
|
||||
/// Set a callback for intercepting messages sent to the platform on
|
||||
/// the given channel.
|
||||
///
|
||||
/// Intercepted messages are not forwarded to the platform.
|
||||
///
|
||||
/// The given callback will replace the currently registered
|
||||
/// callback for that channel, if any. To stop intercepting messages
|
||||
/// at all, pass null as the handler.
|
||||
///
|
||||
/// Messages are decoded using the codec of the channel.
|
||||
///
|
||||
/// The handler's return value, if non-null, is used as a response,
|
||||
/// after encoding it using the channel's codec.
|
||||
///
|
||||
/// {@macro flutter.flutter_test.TestDefaultBinaryMessenger.handlePlatformMessage.asyncHandlers}
|
||||
///
|
||||
/// Registered callbacks are cleared after each test.
|
||||
///
|
||||
/// See also:
|
||||
///
|
||||
/// * [checkMockMessageHandler], which can verify if a handler is still
|
||||
/// registered, which is useful in tests to ensure that no unexpected
|
||||
/// handlers are being registered.
|
||||
///
|
||||
/// * [setMockMessageHandler], which is similar but provides raw
|
||||
/// access to the underlying bytes.
|
||||
///
|
||||
/// * [setMockMethodCallHandler], which is similar but decodes
|
||||
/// the messages using a [MethodCodec].
|
||||
void setMockDecodedMessageHandler<T>(BasicMessageChannel<T> channel, Future<T> Function(T? message)? handler) {
|
||||
if (handler == null) {
|
||||
setMockMessageHandler(channel.name, null);
|
||||
return;
|
||||
}
|
||||
setMockMessageHandler(channel.name, (ByteData? message) async {
|
||||
return channel.codec.encodeMessage(await handler(channel.codec.decodeMessage(message)));
|
||||
}, handler);
|
||||
}
|
||||
|
||||
/// Set a callback for intercepting method calls sent to the
|
||||
/// platform on the given channel.
|
||||
///
|
||||
/// Intercepted method calls are not forwarded to the platform.
|
||||
///
|
||||
/// The given callback will replace the currently registered
|
||||
/// callback for that channel, if any. To stop intercepting messages
|
||||
/// at all, pass null as the handler.
|
||||
///
|
||||
/// Methods are decoded using the codec of the channel.
|
||||
///
|
||||
/// The handler's return value, if non-null, is used as a response,
|
||||
/// after re-encoding it using the channel's codec.
|
||||
///
|
||||
/// To send an error, throw a [PlatformException] in the handler.
|
||||
/// Other exceptions are not caught.
|
||||
///
|
||||
/// {@macro flutter.flutter_test.TestDefaultBinaryMessenger.handlePlatformMessage.asyncHandlers}
|
||||
///
|
||||
/// Registered callbacks are cleared after each test.
|
||||
///
|
||||
/// See also:
|
||||
///
|
||||
/// * [checkMockMessageHandler], which can verify if a handler is still
|
||||
/// registered, which is useful in tests to ensure that no unexpected
|
||||
/// handlers are being registered.
|
||||
///
|
||||
/// * [setMockMessageHandler], which is similar but provides raw
|
||||
/// access to the underlying bytes.
|
||||
///
|
||||
/// * [setMockDecodedMessageHandler], which is similar but decodes
|
||||
/// the messages using a [MessageCodec].
|
||||
void setMockMethodCallHandler(MethodChannel channel, Future<Object?>? Function(MethodCall message)? handler) {
|
||||
if (handler == null) {
|
||||
setMockMessageHandler(channel.name, null);
|
||||
return;
|
||||
}
|
||||
setMockMessageHandler(channel.name, (ByteData? message) async {
|
||||
final MethodCall call = channel.codec.decodeMethodCall(message);
|
||||
try {
|
||||
return channel.codec.encodeSuccessEnvelope(await handler(call));
|
||||
} on PlatformException catch (error) {
|
||||
return channel.codec.encodeErrorEnvelope(
|
||||
code: error.code,
|
||||
message: error.message,
|
||||
details: error.details,
|
||||
);
|
||||
} on MissingPluginException {
|
||||
return null;
|
||||
} catch (error) {
|
||||
return channel.codec.encodeErrorEnvelope(code: 'error', message: '$error', details: null);
|
||||
}
|
||||
}, handler);
|
||||
}
|
||||
|
||||
/// Returns true if the `handler` argument matches the `handler`
|
||||
/// previously passed to [setMockMessageHandler],
|
||||
/// [setMockDecodedMessageHandler], or [setMockMethodCallHandler].
|
||||
///
|
||||
/// Specifically, it compares the argument provided to the `identity`
|
||||
/// argument provided to [setMockMessageHandler], defaulting to the
|
||||
/// `handler` argument passed to that method is `identity` was null.
|
||||
///
|
||||
/// This method is useful for tests or test harnesses that want to assert the
|
||||
/// mock handler for the specified channel has not been altered by a previous
|
||||
/// test.
|
||||
///
|
||||
/// Passing null for the `handler` returns true if the handler for the
|
||||
/// `channel` is not set.
|
||||
///
|
||||
/// Registered callbacks are cleared after each test.
|
||||
bool checkMockMessageHandler(String channel, Object? handler) => _outboundHandlerIdentities[channel] == handler;
|
||||
}
|
||||
@@ -8,12 +8,28 @@ import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'binding.dart' show TestDefaultBinaryMessengerBinding;
|
||||
import 'deprecated.dart';
|
||||
import 'test_async_utils.dart';
|
||||
|
||||
export 'package:flutter/services.dart' show TextEditingValue, TextInputAction;
|
||||
|
||||
/// A testing stub for the system's onscreen keyboard.
|
||||
///
|
||||
/// Typical app tests will not need to use this class directly.
|
||||
///
|
||||
/// The [TestWidgetsFlutterBinding] class registers a [TestTextInput] instance
|
||||
/// ([TestWidgetsFlutterBinding.testTextInput]) as a stub keyboard
|
||||
/// implementation if its [TestWidgetsFlutterBinding.registerTestTextInput]
|
||||
/// property returns true when a test starts, and unregisters it when the test
|
||||
/// ends (unless it ends with a failure).
|
||||
///
|
||||
/// See [register], [unregister], and [isRegistered] for details.
|
||||
///
|
||||
/// The [enterText], [updateEditingValue], [receiveAction], and
|
||||
/// [closeConnection] methods can be used even when the [TestTextInput] is not
|
||||
/// registered. All other methods will assert if [isRegistered] is false.
|
||||
///
|
||||
/// See also:
|
||||
///
|
||||
/// * [WidgetTester.enterText], which uses this class to simulate keyboard input.
|
||||
@@ -33,61 +49,76 @@ class TestTextInput {
|
||||
/// first be requested, e.g. using [WidgetTester.showKeyboard].
|
||||
final VoidCallback? onCleared;
|
||||
|
||||
/// The messenger which sends the bytes for this channel, not null.
|
||||
BinaryMessenger get _binaryMessenger => ServicesBinding.instance!.defaultBinaryMessenger;
|
||||
|
||||
/// Resets any internal state of this object and calls [register].
|
||||
///
|
||||
/// This method is invoked by the testing framework between tests. It should
|
||||
/// not ordinarily be called by tests directly.
|
||||
void resetAndRegister() {
|
||||
log.clear();
|
||||
editingState = null;
|
||||
setClientArgs = null;
|
||||
_client = 0;
|
||||
_isVisible = false;
|
||||
register();
|
||||
}
|
||||
/// Installs this object as a mock handler for [SystemChannels.textInput].
|
||||
void register() => SystemChannels.textInput.setMockMethodCallHandler(_handleTextInputCall);
|
||||
|
||||
/// Removes this object as a mock handler for [SystemChannels.textInput].
|
||||
///
|
||||
/// After calling this method, the channel will exchange messages with the
|
||||
/// Flutter engine. Use this with [FlutterDriver] tests that need to display
|
||||
/// on-screen keyboard provided by the operating system.
|
||||
void unregister() => SystemChannels.textInput.setMockMethodCallHandler(null);
|
||||
|
||||
/// Log for method calls.
|
||||
///
|
||||
/// For all registered channels, handled calls are added to the list. Can
|
||||
/// be cleaned using `log.clear()`.
|
||||
final List<MethodCall> log = <MethodCall>[];
|
||||
|
||||
/// Installs this object as a mock handler for [SystemChannels.textInput].
|
||||
///
|
||||
/// Called by the binding at the top of a test when
|
||||
/// [TestWidgetsFlutterBinding.registerTestTextInput] is true.
|
||||
void register() => SystemChannels.textInput.setMockMethodCallHandler(_handleTextInputCall);
|
||||
|
||||
/// Removes this object as a mock handler for [SystemChannels.textInput].
|
||||
///
|
||||
/// After calling this method, the channel will exchange messages with the
|
||||
/// Flutter engine instead of the stub.
|
||||
///
|
||||
/// Called by the binding at the end of a (successful) test when
|
||||
/// [TestWidgetsFlutterBinding.registerTestTextInput] is true.
|
||||
void unregister() => SystemChannels.textInput.setMockMethodCallHandler(null);
|
||||
|
||||
/// Whether this [TestTextInput] is registered with [SystemChannels.textInput].
|
||||
///
|
||||
/// Use [register] and [unregister] methods to control this value.
|
||||
/// The binding uses the [register] and [unregister] methods to control this
|
||||
/// value when [TestWidgetsFlutterBinding.registerTestTextInput] is true.
|
||||
bool get isRegistered => SystemChannels.textInput.checkMockMethodCallHandler(_handleTextInputCall);
|
||||
|
||||
int? _client;
|
||||
|
||||
/// Whether there are any active clients listening to text input.
|
||||
bool get hasAnyClients {
|
||||
assert(isRegistered);
|
||||
return _client > 0;
|
||||
return _client != null && _client! > 0;
|
||||
}
|
||||
|
||||
int _client = 0;
|
||||
|
||||
/// Arguments supplied to the TextInput.setClient method call.
|
||||
/// The last set of arguments supplied to the `TextInput.setClient` and
|
||||
/// `TextInput.updateConfig` methods of this stub implementation.
|
||||
Map<String, dynamic>? setClientArgs;
|
||||
|
||||
/// The last set of arguments that [TextInputConnection.setEditingState] sent
|
||||
/// to the embedder.
|
||||
/// to this stub implementation (i.e. the arguments set to
|
||||
/// `TextInput.setEditingState`).
|
||||
///
|
||||
/// This is a map representation of a [TextEditingValue] object. For example,
|
||||
/// it will have a `text` entry whose value matches the most recent
|
||||
/// [TextEditingValue.text] that was sent to the embedder.
|
||||
Map<String, dynamic>? editingState;
|
||||
|
||||
/// Whether the onscreen keyboard is visible to the user.
|
||||
///
|
||||
/// Specifically, this reflects the last call to `TextInput.show` or
|
||||
/// `TextInput.hide` received by the stub implementation.
|
||||
bool get isVisible {
|
||||
assert(isRegistered);
|
||||
return _isVisible;
|
||||
}
|
||||
bool _isVisible = false;
|
||||
|
||||
/// Resets any internal state of this object.
|
||||
///
|
||||
/// This method is invoked by the testing framework between tests. It should
|
||||
/// not ordinarily be called by tests directly.
|
||||
void reset() {
|
||||
log.clear();
|
||||
_client = null;
|
||||
setClientArgs = null;
|
||||
editingState = null;
|
||||
_isVisible = false;
|
||||
}
|
||||
|
||||
Future<dynamic> _handleTextInputCall(MethodCall methodCall) async {
|
||||
log.add(methodCall);
|
||||
switch (methodCall.method) {
|
||||
@@ -99,7 +130,7 @@ class TestTextInput {
|
||||
setClientArgs = methodCall.arguments as Map<String, dynamic>;
|
||||
break;
|
||||
case 'TextInput.clearClient':
|
||||
_client = 0;
|
||||
_client = null;
|
||||
_isVisible = false;
|
||||
onCleared?.call();
|
||||
break;
|
||||
@@ -115,87 +146,86 @@ class TestTextInput {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the onscreen keyboard is visible to the user.
|
||||
bool get isVisible {
|
||||
assert(isRegistered);
|
||||
return _isVisible;
|
||||
}
|
||||
bool _isVisible = false;
|
||||
|
||||
/// Simulates the user changing the [TextEditingValue] to the given value.
|
||||
void updateEditingValue(TextEditingValue value) {
|
||||
assert(isRegistered);
|
||||
// Not using the `expect` function because in the case of a FlutterDriver
|
||||
// test this code does not run in a package:test test zone.
|
||||
if (_client == 0)
|
||||
throw TestFailure('Tried to use TestTextInput with no keyboard attached. You must use WidgetTester.showKeyboard() first.');
|
||||
_binaryMessenger.handlePlatformMessage(
|
||||
SystemChannels.textInput.name,
|
||||
SystemChannels.textInput.codec.encodeMethodCall(
|
||||
MethodCall(
|
||||
'TextInputClient.updateEditingState',
|
||||
<dynamic>[_client, value.toJSON()],
|
||||
),
|
||||
),
|
||||
(ByteData? data) { /* response from framework is discarded */ },
|
||||
);
|
||||
}
|
||||
|
||||
/// Simulates the user closing the text input connection.
|
||||
/// Simulates the user hiding the onscreen keyboard.
|
||||
///
|
||||
/// For example:
|
||||
/// - User pressed the home button and sent the application to background.
|
||||
/// - User closed the virtual keyboard.
|
||||
void closeConnection() {
|
||||
/// This does nothing but set the internal flag.
|
||||
void hide() {
|
||||
assert(isRegistered);
|
||||
// Not using the `expect` function because in the case of a FlutterDriver
|
||||
// test this code does not run in a package:test test zone.
|
||||
if (_client == 0)
|
||||
throw TestFailure('Tried to use TestTextInput with no keyboard attached. You must use WidgetTester.showKeyboard() first.');
|
||||
_binaryMessenger.handlePlatformMessage(
|
||||
SystemChannels.textInput.name,
|
||||
SystemChannels.textInput.codec.encodeMethodCall(
|
||||
MethodCall(
|
||||
'TextInputClient.onConnectionClosed',
|
||||
<dynamic>[_client,]
|
||||
),
|
||||
),
|
||||
(ByteData? data) { /* response from framework is discarded */ },
|
||||
);
|
||||
_isVisible = false;
|
||||
}
|
||||
|
||||
/// Simulates the user typing the given text.
|
||||
/// Simulates the user changing the text of the focused text field, and resets
|
||||
/// the selection.
|
||||
///
|
||||
/// Calling this method replaces the content of the connected input field with
|
||||
/// `text`, and places the caret at the end of the text.
|
||||
///
|
||||
/// To update the UI under test after this method is invoked, use
|
||||
/// [WidgetTester.pump].
|
||||
///
|
||||
/// This can be called even if the [TestTextInput] has not been [register]ed.
|
||||
///
|
||||
/// If this is used to inject text when there is a real IME connection, for
|
||||
/// example when using the [integration_test] library, there is a risk that
|
||||
/// the real IME will become confused as to the current state of input.
|
||||
///
|
||||
/// See also:
|
||||
///
|
||||
/// * [updateEditingValue], which takes a [TextEditingValue] so that one can
|
||||
/// also change the selection.
|
||||
void enterText(String text) {
|
||||
assert(isRegistered);
|
||||
updateEditingValue(TextEditingValue(
|
||||
text: text,
|
||||
selection: TextSelection.collapsed(offset: text.length),
|
||||
));
|
||||
}
|
||||
|
||||
/// Simulates the user changing the [TextEditingValue] to the given value.
|
||||
///
|
||||
/// To update the UI under test after this method is invoked, use
|
||||
/// [WidgetTester.pump].
|
||||
///
|
||||
/// This can be called even if the [TestTextInput] has not been [register]ed.
|
||||
///
|
||||
/// If this is used to inject text when there is a real IME connection, for
|
||||
/// example when using the [integration_test] library, there is a risk that
|
||||
/// the real IME will become confused as to the current state of input.
|
||||
///
|
||||
/// See also:
|
||||
///
|
||||
/// * [enterText], which is similar but takes only a String and resets the
|
||||
/// selection.
|
||||
void updateEditingValue(TextEditingValue value) {
|
||||
TestDefaultBinaryMessengerBinding.instance!.defaultBinaryMessenger.handlePlatformMessage(
|
||||
SystemChannels.textInput.name,
|
||||
SystemChannels.textInput.codec.encodeMethodCall(
|
||||
MethodCall(
|
||||
'TextInputClient.updateEditingState',
|
||||
<dynamic>[_client ?? -1, value.toJSON()],
|
||||
),
|
||||
),
|
||||
(ByteData? data) { /* ignored */ },
|
||||
);
|
||||
}
|
||||
|
||||
/// Simulates the user pressing one of the [TextInputAction] buttons.
|
||||
/// Does not check that the [TextInputAction] performed is an acceptable one
|
||||
/// based on the `inputAction` [setClientArgs].
|
||||
///
|
||||
/// This can be called even if the [TestTextInput] has not been [register]ed.
|
||||
///
|
||||
/// If this is used to inject an action when there is a real IME connection,
|
||||
/// for example when using the [integration_test] library, there is a risk
|
||||
/// that the real IME will become confused as to the current state of input.
|
||||
Future<void> receiveAction(TextInputAction action) async {
|
||||
assert(isRegistered);
|
||||
return TestAsyncUtils.guard(() {
|
||||
// Not using the `expect` function because in the case of a FlutterDriver
|
||||
// test this code does not run in a package:test test zone.
|
||||
if (_client == 0) {
|
||||
throw TestFailure('Tried to use TestTextInput with no keyboard attached. You must use WidgetTester.showKeyboard() first.');
|
||||
}
|
||||
|
||||
final Completer<void> completer = Completer<void>();
|
||||
|
||||
_binaryMessenger.handlePlatformMessage(
|
||||
TestDefaultBinaryMessengerBinding.instance!.defaultBinaryMessenger.handlePlatformMessage(
|
||||
SystemChannels.textInput.name,
|
||||
SystemChannels.textInput.codec.encodeMethodCall(
|
||||
MethodCall(
|
||||
'TextInputClient.performAction',
|
||||
<dynamic>[_client, action.toString()],
|
||||
<dynamic>[_client ?? -1, action.toString()],
|
||||
),
|
||||
),
|
||||
(ByteData? data) {
|
||||
@@ -204,8 +234,7 @@ class TestTextInput {
|
||||
// Decoding throws a PlatformException if the data represents an
|
||||
// error, and that's all we care about here.
|
||||
SystemChannels.textInput.codec.decodeEnvelope(data!);
|
||||
|
||||
// No error was found. Complete without issue.
|
||||
// If we reach here then no error was found. Complete without issue.
|
||||
completer.complete();
|
||||
} catch (error) {
|
||||
// An exception occurred as a result of receiveAction()'ing. Report
|
||||
@@ -214,14 +243,32 @@ class TestTextInput {
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
return completer.future;
|
||||
});
|
||||
}
|
||||
|
||||
/// Simulates the user hiding the onscreen keyboard.
|
||||
void hide() {
|
||||
assert(isRegistered);
|
||||
_isVisible = false;
|
||||
/// Simulates the user closing the text input connection.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// * User pressed the home button and sent the application to background.
|
||||
/// * User closed the virtual keyboard.
|
||||
///
|
||||
/// This can be called even if the [TestTextInput] has not been [register]ed.
|
||||
///
|
||||
/// If this is used to inject text when there is a real IME connection, for
|
||||
/// example when using the [integration_test] library, there is a risk that
|
||||
/// the real IME will become confused as to the current state of input.
|
||||
void closeConnection() {
|
||||
TestDefaultBinaryMessengerBinding.instance!.defaultBinaryMessenger.handlePlatformMessage(
|
||||
SystemChannels.textInput.name,
|
||||
SystemChannels.textInput.codec.encodeMethodCall(
|
||||
MethodCall(
|
||||
'TextInputClient.onConnectionClosed',
|
||||
<dynamic>[_client ?? -1],
|
||||
),
|
||||
),
|
||||
(ByteData? data) { /* response from framework is discarded */ },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -129,7 +129,7 @@ void testWidgets(
|
||||
dynamic tags,
|
||||
}) {
|
||||
assert(variant != null);
|
||||
assert(variant.values.isNotEmpty, 'There must be at least on value to test in the testing variant');
|
||||
assert(variant.values.isNotEmpty, 'There must be at least one value to test in the testing variant.');
|
||||
final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized() as TestWidgetsFlutterBinding;
|
||||
final WidgetTester tester = WidgetTester._(binding);
|
||||
for (final dynamic value in variant.values) {
|
||||
@@ -147,9 +147,8 @@ void testWidgets(
|
||||
test_package.addTearDown(binding.postTest);
|
||||
return binding.runTest(
|
||||
() async {
|
||||
binding.reset();
|
||||
binding.reset(); // TODO(ianh): the binding should just do this itself in _runTest
|
||||
debugResetSemanticsIdCounter();
|
||||
tester.resetTestTextInput();
|
||||
Object? memento;
|
||||
try {
|
||||
memento = await variant.setUp(value);
|
||||
@@ -918,10 +917,12 @@ class WidgetTester extends WidgetController implements HitTestDispatcher, Ticker
|
||||
/// Acts as if the application went idle.
|
||||
///
|
||||
/// Runs all remaining microtasks, including those scheduled as a result of
|
||||
/// running them, until there are no more microtasks scheduled.
|
||||
/// running them, until there are no more microtasks scheduled. Then, runs any
|
||||
/// previously scheduled timers with zero time, and completes the returned future.
|
||||
///
|
||||
/// Does not run timers. May result in an infinite loop or run out of memory
|
||||
/// if microtasks continue to recursively schedule new microtasks.
|
||||
/// May result in an infinite loop or run out of memory if microtasks continue
|
||||
/// to recursively schedule new microtasks. Will not run any timers scheduled
|
||||
/// after this method was invoked, even if they are zero-time timers.
|
||||
Future<void> idle() {
|
||||
return TestAsyncUtils.guard<void>(() => binding.idle());
|
||||
}
|
||||
@@ -1002,18 +1003,13 @@ class WidgetTester extends WidgetController implements HitTestDispatcher, Ticker
|
||||
///
|
||||
/// Typical app tests will not need to use this value. To add text to widgets
|
||||
/// like [TextField] or [TextFormField], call [enterText].
|
||||
TestTextInput get testTextInput => binding.testTextInput;
|
||||
|
||||
/// Ensures that [testTextInput] is registered and [TestTextInput.log] is
|
||||
/// reset.
|
||||
///
|
||||
/// This is called by the testing framework before test runs, so that if a
|
||||
/// previous test has set its own handler on [SystemChannels.textInput], the
|
||||
/// [testTextInput] regains control and the log is fresh for the new test.
|
||||
/// It should not typically need to be called by tests.
|
||||
void resetTestTextInput() {
|
||||
testTextInput.resetAndRegister();
|
||||
}
|
||||
/// Some of the properties and methods on this value are only valid if the
|
||||
/// binding's [TestWidgetsFlutterBinding.registerTestTextInput] flag is set to
|
||||
/// true as a test is starting (meaning that the keyboard is to be simulated
|
||||
/// by the test framework). If those members are accessed when using a binding
|
||||
/// that sets this flag to false, they will throw.
|
||||
TestTextInput get testTextInput => binding.testTextInput;
|
||||
|
||||
/// Give the text input widget specified by [finder] the focus, as if the
|
||||
/// onscreen keyboard had appeared.
|
||||
@@ -1035,6 +1031,9 @@ class WidgetTester extends WidgetController implements HitTestDispatcher, Ticker
|
||||
matchRoot: true,
|
||||
),
|
||||
);
|
||||
// Setting focusedEditable causes the binding to call requestKeyboard()
|
||||
// on the EditableTextState, which itself eventually calls TextInput.attach
|
||||
// to establish the connection.
|
||||
binding.focusedEditable = editable;
|
||||
await pump();
|
||||
});
|
||||
@@ -1052,6 +1051,12 @@ class WidgetTester extends WidgetController implements HitTestDispatcher, Ticker
|
||||
///
|
||||
/// To just give [finder] the focus without entering any text,
|
||||
/// see [showKeyboard].
|
||||
///
|
||||
/// To enter text into other widgets (e.g. a custom widget that maintains a
|
||||
/// TextInputConnection the way that a [EditableText] does), first ensure that
|
||||
/// that widget has an open connection (e.g. by using [tap] to to focus it),
|
||||
/// then call `testTextInput.enterText` directly (see
|
||||
/// [TestTextInput.enterText]).
|
||||
Future<void> enterText(Finder finder, String text) async {
|
||||
return TestAsyncUtils.guard<void>(() async {
|
||||
await showKeyboard(finder);
|
||||
|
||||
@@ -379,8 +379,16 @@ class TestWindow implements ui.SingletonFlutterWindow {
|
||||
platformDispatcher.sendPlatformMessage(name, data, callback);
|
||||
}
|
||||
|
||||
@Deprecated(
|
||||
'Instead of calling this callback, use ServicesBinding.instance.channelBuffers.push. '
|
||||
'This feature was deprecated after v2.1.0-10.0.pre.'
|
||||
)
|
||||
@override
|
||||
ui.PlatformMessageCallback? get onPlatformMessage => platformDispatcher.onPlatformMessage;
|
||||
@Deprecated(
|
||||
'Instead of setting this callback, use ServicesBinding.instance.defaultBinaryMessenger.setMessageHandler. '
|
||||
'This feature was deprecated after v2.1.0-10.0.pre.'
|
||||
)
|
||||
@override
|
||||
set onPlatformMessage(ui.PlatformMessageCallback? callback) {
|
||||
platformDispatcher.onPlatformMessage = callback;
|
||||
|
||||
Reference in New Issue
Block a user