Revert "Migrate to ChannelBuffers.push (#76288)" (#81226)

This reverts commit c26ed03c8a.
This commit is contained in:
Angjie Li
2021-04-26 12:57:17 -07:00
committed by GitHub
parent e2ddeb0427
commit b74df388e1
74 changed files with 596 additions and 889 deletions

View File

@@ -61,7 +61,6 @@ export 'src/all_elements.dart';
export 'src/animation_sheet.dart';
export 'src/binding.dart';
export 'src/controller.dart';
export 'src/deprecated.dart';
export 'src/event_simulation.dart';
export 'src/finders.dart';
export 'src/frame_timing_summarizer.dart';
@@ -74,7 +73,6 @@ export 'src/restoration.dart';
export 'src/stack_manipulation.dart';
export 'src/test_async_utils.dart';
export 'src/test_compat.dart';
export 'src/test_default_binary_messenger.dart';
export 'src/test_exception_reporter.dart';
export 'src/test_pointer.dart';
export 'src/test_text_input.dart';

View File

@@ -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]) {

View File

@@ -15,7 +15,8 @@ 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;
import 'package:test_api/test_api.dart' as test_package; // ignore: deprecated_member_use
// ignore: deprecated_member_use
import 'package:test_api/test_api.dart' as test_package;
import 'package:vector_math/vector_math_64.dart';
import '_binding_io.dart' if (dart.library.html) '_binding_web.dart' as binding;
@@ -24,7 +25,6 @@ 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,29 +79,74 @@ enum TestBindingEventSource {
const Size _kDefaultTestViewportSize = Size(800.0, 600.0);
/// Overrides the [ServicesBinding]'s binary messenger logic to use
/// [TestDefaultBinaryMessenger].
/// A [BinaryMessenger] subclass that is used as the default binary messenger
/// under testing environment.
///
/// 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 {
/// 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;
@override
void initInstances() {
super.initInstances();
_instance = this;
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;
}
/// The current [TestDefaultBinaryMessengerBinding], if one has been created.
static TestDefaultBinaryMessengerBinding? get instance => _instance;
static TestDefaultBinaryMessengerBinding? _instance;
/// 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);
}
@override
TestDefaultBinaryMessenger get defaultBinaryMessenger => super.defaultBinaryMessenger as TestDefaultBinaryMessenger;
Future<void> handlePlatformMessage(
String channel,
ByteData? data,
ui.PlatformMessageResponseCallback? callback,
) {
return delegate.handlePlatformMessage(channel, data, callback);
}
@override
TestDefaultBinaryMessenger createBinaryMessenger() {
return TestDefaultBinaryMessenger(super.createBinaryMessenger());
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);
}
}
@@ -126,8 +171,7 @@ abstract class TestWidgetsFlutterBinding extends BindingBase
SemanticsBinding,
RendererBinding,
PaintingBinding,
WidgetsBinding,
TestDefaultBinaryMessengerBinding {
WidgetsBinding {
/// Constructor for [TestWidgetsFlutterBinding].
///
@@ -304,6 +348,11 @@ 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;

View File

@@ -1,109 +0,0 @@
// 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);
}
}

View File

@@ -2,13 +2,10 @@
// 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
@@ -640,20 +637,21 @@ 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);
final Completer<bool> result = Completer<bool>();
await TestDefaultBinaryMessengerBinding.instance!.defaultBinaryMessenger.handlePlatformMessage(
bool result = false;
await ServicesBinding.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>;
result.complete(decoded['handled'] as bool);
if (decoded['handled'] as bool) {
result = true;
}
}
);
return result.future;
return result;
});
}
@@ -679,7 +677,7 @@ class KeyEventSimulator {
final Map<String, dynamic> data = getKeyData(key, platform: platform!, isDown: false, physicalKey: physicalKey);
bool result = false;
await TestDefaultBinaryMessengerBinding.instance!.defaultBinaryMessenger.handlePlatformMessage(
await ServicesBinding.instance!.defaultBinaryMessenger.handlePlatformMessage(
SystemChannels.keyEvent.name,
SystemChannels.keyEvent.codec.encodeMessage(data),
(ByteData? data) {

View File

@@ -1,306 +0,0 @@
// 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;
}

View File

@@ -8,10 +8,6 @@ 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.
@@ -49,6 +45,9 @@ 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;
/// Log for method calls.
///
/// For all registered channels, handled calls are added to the list. Can
@@ -154,25 +153,16 @@ class TestTextInput {
_isVisible = false;
}
/// Simulates the user changing the text of the focused text field, and resets
/// the selection.
/// Simulates the user typing the given text.
///
/// 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) {
updateEditingValue(TextEditingValue(
text: text,
@@ -182,21 +172,13 @@ class TestTextInput {
/// 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(
_binaryMessenger.handlePlatformMessage(
SystemChannels.textInput.name,
SystemChannels.textInput.codec.encodeMethodCall(
MethodCall(
@@ -204,7 +186,7 @@ class TestTextInput {
<dynamic>[_client ?? -1, value.toJSON()],
),
),
(ByteData? data) { /* ignored */ },
(ByteData? data) { /* response from framework is discarded */ },
);
}
@@ -220,7 +202,7 @@ class TestTextInput {
Future<void> receiveAction(TextInputAction action) async {
return TestAsyncUtils.guard(() {
final Completer<void> completer = Completer<void>();
TestDefaultBinaryMessengerBinding.instance!.defaultBinaryMessenger.handlePlatformMessage(
_binaryMessenger.handlePlatformMessage(
SystemChannels.textInput.name,
SystemChannels.textInput.codec.encodeMethodCall(
MethodCall(
@@ -234,7 +216,8 @@ 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!);
// If we reach here then no error was found. Complete without issue.
// No error was found. Complete without issue.
completer.complete();
} catch (error) {
// An exception occurred as a result of receiveAction()'ing. Report
@@ -243,6 +226,7 @@ class TestTextInput {
}
},
);
return completer.future;
});
}
@@ -260,7 +244,7 @@ class TestTextInput {
/// 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(
_binaryMessenger.handlePlatformMessage(
SystemChannels.textInput.name,
SystemChannels.textInput.codec.encodeMethodCall(
MethodCall(

View File

@@ -129,7 +129,7 @@ void testWidgets(
dynamic tags,
}) {
assert(variant != null);
assert(variant.values.isNotEmpty, 'There must be at least one value to test in the testing variant.');
assert(variant.values.isNotEmpty, 'There must be at least on 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,7 +147,7 @@ void testWidgets(
test_package.addTearDown(binding.postTest);
return binding.runTest(
() async {
binding.reset(); // TODO(ianh): the binding should just do this itself in _runTest
binding.reset();
debugResetSemanticsIdCounter();
Object? memento;
try {
@@ -917,12 +917,10 @@ 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. Then, runs any
/// previously scheduled timers with zero time, and completes the returned future.
/// running them, until there are no more microtasks scheduled.
///
/// 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.
/// Does not run timers. May result in an infinite loop or run out of memory
/// if microtasks continue to recursively schedule new microtasks.
Future<void> idle() {
return TestAsyncUtils.guard<void>(() => binding.idle());
}

View File

@@ -379,16 +379,8 @@ 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;

View File

@@ -20,6 +20,12 @@ class TestDelegate extends BinaryMessenger {
Future<void> handlePlatformMessage(String channel, ByteData? data, ui.PlatformMessageResponseCallback? callback) => throw UnimplementedError();
@override
void setMessageHandler(String channel, MessageHandler? handler) => throw UnimplementedError();
@override
bool checkMessageHandler(String channel, MessageHandler? handler) => throw UnimplementedError();
@override
void setMockMessageHandler(String channel, MessageHandler? handler) => throw UnimplementedError();
@override
bool checkMockMessageHandler(String channel, MessageHandler? handler) => throw UnimplementedError();
}
void main() {