Integration test for channel communication (#9621)
This commit is contained in:
committed by
GitHub
parent
0770c3c14f
commit
70ff50f929
@@ -7,9 +7,12 @@ import 'dart:ui' show hashValues;
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import 'platform_channel.dart';
|
||||
|
||||
/// A message encoding/decoding mechanism.
|
||||
///
|
||||
/// Both operations throw [FormatException], if conversion fails.
|
||||
/// Both operations throw an exception, if conversion fails. Such situations
|
||||
/// should be treated as programming errors.
|
||||
///
|
||||
/// See also:
|
||||
///
|
||||
@@ -92,15 +95,7 @@ class MethodCall {
|
||||
|
||||
/// A codec for method calls and enveloped results.
|
||||
///
|
||||
/// Result envelopes are binary messages with enough structure that the codec can
|
||||
/// distinguish between a successful result and an error. In the former case,
|
||||
/// the codec must be able to extract the result payload, possibly `null`. In
|
||||
/// the latter case, the codec must be able to extract an error code string,
|
||||
/// a (human-readable) error message string, and a value providing any
|
||||
/// additional error details, possibly `null`. These data items are used to
|
||||
/// populate a [PlatformException].
|
||||
///
|
||||
/// All operations throw [FormatException], if conversion fails.
|
||||
/// All operations throw an exception, if conversion fails.
|
||||
///
|
||||
/// See also:
|
||||
///
|
||||
@@ -109,7 +104,7 @@ class MethodCall {
|
||||
/// * [PlatformEventChannel], which use [MethodCodec]s for communication
|
||||
/// between Flutter and platform plugins.
|
||||
abstract class MethodCodec {
|
||||
/// Encodes the specified [methodCall] in binary.
|
||||
/// Encodes the specified [methodCall] into binary.
|
||||
ByteData encodeMethodCall(MethodCall methodCall);
|
||||
|
||||
/// Decodes the specified [methodCall] from binary.
|
||||
@@ -139,10 +134,10 @@ abstract class MethodCodec {
|
||||
///
|
||||
/// * [MethodCodec], which throws a [PlatformException], if a received result
|
||||
/// envelope represents an error.
|
||||
/// * [PlatformMethodChannel.invokeMethod], which completes the returned future
|
||||
/// * [MethodChannel.invokeMethod], which completes the returned future
|
||||
/// with a [PlatformException], if invoking the platform plugin method
|
||||
/// results in an error envelope.
|
||||
/// * [PlatformEventChannel.receiveBroadcastStream], which emits
|
||||
/// * [EventChannel.receiveBroadcastStream], which emits
|
||||
/// [PlatformException]s as error events, whenever an event received from the
|
||||
/// platform plugin is wrapped in an error envelope.
|
||||
class PlatformException implements Exception {
|
||||
@@ -175,9 +170,11 @@ class PlatformException implements Exception {
|
||||
///
|
||||
/// See also:
|
||||
///
|
||||
/// * [PlatformMethodChannel.invokeMethod], which completes the returned future
|
||||
/// * [MethodChannel.invokeMethod], which completes the returned future
|
||||
/// with a [MissingPluginException], if no plugin handler for the method call
|
||||
/// was found.
|
||||
/// * [OptionalMethodChannel.invokeMethod], which completes the returned future
|
||||
/// with `null`, if no plugin handler for the method call was found.
|
||||
class MissingPluginException implements Exception {
|
||||
/// Creates a [MissingPluginException] with an optional human-readable
|
||||
/// error message.
|
||||
|
||||
@@ -17,14 +17,15 @@ import 'platform_messages.dart';
|
||||
/// Messages are encoded into binary before being sent, and binary messages
|
||||
/// received are decoded into Dart values. The [MessageCodec] used must be
|
||||
/// compatible with the one used by the platform plugin. This can be achieved
|
||||
/// by creating a FlutterMessageChannel counterpart of this channel on the
|
||||
/// by creating a `BasicMessageChannel` counterpart of this channel on the
|
||||
/// platform side. The Dart type of messages sent and received is [T],
|
||||
/// but only the values supported by the specified [MessageCodec] can be used.
|
||||
/// The use of unsupported values should be considered programming errors, and
|
||||
/// will result in exceptions being thrown. The `null` message is supported
|
||||
/// for all codecs.
|
||||
///
|
||||
/// The identity of the channel is given by its name, so other uses of that name
|
||||
/// with may interfere with this channel's communication. Specifically, at most
|
||||
/// one message handler can be registered with the channel name at any given
|
||||
/// time.
|
||||
/// The logical identity of the channel is given by its name. Identically named
|
||||
/// channels will interfere with each other's communication.
|
||||
///
|
||||
/// See: <https://flutter.io/platform-channels/>
|
||||
class BasicMessageChannel<T> {
|
||||
@@ -41,23 +42,21 @@ class BasicMessageChannel<T> {
|
||||
|
||||
/// Sends the specified [message] to the platform plugins on this channel.
|
||||
///
|
||||
/// Returns a [Future] which completes to the received and decoded response,
|
||||
/// or to a [FormatException], if encoding or decoding fails.
|
||||
/// Returns a [Future] which completes to the received response, which may
|
||||
/// be `null`.
|
||||
Future<T> send(T message) async {
|
||||
return codec.decodeMessage(
|
||||
await BinaryMessages.send(name, codec.encodeMessage(message))
|
||||
);
|
||||
return codec.decodeMessage(await BinaryMessages.send(name, codec.encodeMessage(message)));
|
||||
}
|
||||
|
||||
/// Sets a callback for receiving messages from the platform plugins on this
|
||||
/// channel.
|
||||
/// channel. Messages may be `null`.
|
||||
///
|
||||
/// The given callback will replace the currently registered callback for this
|
||||
/// channel, if any. To remove the handler, pass `null` as the `handler`
|
||||
/// argument.
|
||||
///
|
||||
/// The handler's return value, if non-null, is sent back to the platform
|
||||
/// plugins as a response.
|
||||
/// The handler's return value is sent back to the platform plugins as a
|
||||
/// message reply. It may be `null`.
|
||||
void setMessageHandler(Future<T> handler(T message)) {
|
||||
if (handler == null) {
|
||||
BinaryMessages.setMessageHandler(name, null);
|
||||
@@ -69,12 +68,13 @@ class BasicMessageChannel<T> {
|
||||
}
|
||||
|
||||
/// Sets a mock callback for intercepting messages sent on this channel.
|
||||
/// Messages may be `null`.
|
||||
///
|
||||
/// The given callback will replace the currently registered mock callback for
|
||||
/// this channel, if any. To remove the mock handler, pass `null` as the
|
||||
/// `handler` argument.
|
||||
///
|
||||
/// The handler's return value, if non-null, is used as a response.
|
||||
/// The handler's return value is used as a message reply. It may be `null`.
|
||||
///
|
||||
/// This is intended for testing. Messages intercepted in this manner are not
|
||||
/// sent to platform plugins.
|
||||
@@ -95,12 +95,15 @@ class BasicMessageChannel<T> {
|
||||
/// Method calls are encoded into binary before being sent, and binary results
|
||||
/// received are decoded into Dart values. The [MethodCodec] used must be
|
||||
/// compatible with the one used by the platform plugin. This can be achieved
|
||||
/// by creating a FlutterMethodChannel counterpart of this channel on the
|
||||
/// platform side. The Dart type of messages sent and received is `dynamic`,
|
||||
/// by creating a `MethodChannel` counterpart of this channel on the
|
||||
/// platform side. The Dart type of arguments and results is `dynamic`,
|
||||
/// but only values supported by the specified [MethodCodec] can be used.
|
||||
/// The use of unsupported values should be considered programming errors, and
|
||||
/// will result in exceptions being thrown. The `null` value is supported
|
||||
/// for all codecs.
|
||||
///
|
||||
/// The identity of the channel is given by its name, so other uses of that name
|
||||
/// with may interfere with this channel's communication.
|
||||
/// The logical identity of the channel is given by its name. Identically named
|
||||
/// channels will interfere with each other's communication.
|
||||
///
|
||||
/// See: <https://flutter.io/platform-channels/>
|
||||
class MethodChannel {
|
||||
@@ -124,8 +127,8 @@ class MethodChannel {
|
||||
///
|
||||
/// * a result (possibly `null`), on successful invocation;
|
||||
/// * a [PlatformException], if the invocation failed in the platform plugin;
|
||||
/// * a [FormatException], if encoding or decoding failed.
|
||||
/// * a [MissingPluginException], if the method has not been implemented.
|
||||
/// * a [MissingPluginException], if the method has not been implemented by a
|
||||
/// platform plugin.
|
||||
Future<dynamic> invokeMethod(String method, [dynamic arguments]) async {
|
||||
assert(method != null);
|
||||
final dynamic result = await BinaryMessages.send(
|
||||
@@ -150,26 +153,12 @@ class MethodChannel {
|
||||
/// populate an error envelope which is sent back instead. If the future
|
||||
/// completes with a [MissingPluginException], an empty reply is sent
|
||||
/// similarly to what happens if no method call handler has been set.
|
||||
/// Any other exception results in an error envelope being sent.
|
||||
void setMethodCallHandler(Future<dynamic> handler(MethodCall call)) {
|
||||
if (handler == null) {
|
||||
BinaryMessages.setMessageHandler(name, null);
|
||||
} else {
|
||||
BinaryMessages.setMessageHandler(
|
||||
name,
|
||||
(ByteData message) async {
|
||||
final MethodCall call = codec.decodeMethodCall(message);
|
||||
try {
|
||||
final dynamic result = await handler(call);
|
||||
return codec.encodeSuccessEnvelope(result);
|
||||
} on PlatformException catch (e) {
|
||||
return codec.encodeErrorEnvelope(
|
||||
code: e.code, message: e.message, details: e.details);
|
||||
} on MissingPluginException {
|
||||
return null;
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
BinaryMessages.setMessageHandler(
|
||||
name,
|
||||
handler == null ? null : (ByteData message) => _handleAsMethodCall(message, handler),
|
||||
);
|
||||
}
|
||||
|
||||
/// Sets a mock callback for intercepting method invocations on this channel.
|
||||
@@ -186,24 +175,26 @@ class MethodChannel {
|
||||
/// This is intended for testing. Method calls intercepted in this manner are
|
||||
/// not sent to platform plugins.
|
||||
void setMockMethodCallHandler(Future<dynamic> handler(MethodCall call)) {
|
||||
if (handler == null) {
|
||||
BinaryMessages.setMockMessageHandler(name, null);
|
||||
} else {
|
||||
BinaryMessages.setMockMessageHandler(
|
||||
name,
|
||||
(ByteData message) async {
|
||||
final MethodCall call = codec.decodeMethodCall(message);
|
||||
try {
|
||||
final dynamic result = await handler(call);
|
||||
return codec.encodeSuccessEnvelope(result);
|
||||
} on PlatformException catch (e) {
|
||||
return codec.encodeErrorEnvelope(
|
||||
code: e.code, message: e.message, details: e.details);
|
||||
} on MissingPluginException {
|
||||
return null;
|
||||
}
|
||||
},
|
||||
BinaryMessages.setMockMessageHandler(
|
||||
name,
|
||||
handler == null ? null : (ByteData message) => _handleAsMethodCall(message, handler),
|
||||
);
|
||||
}
|
||||
|
||||
Future<ByteData> _handleAsMethodCall(ByteData message, Future<dynamic> handler(MethodCall call)) async {
|
||||
final MethodCall call = codec.decodeMethodCall(message);
|
||||
try {
|
||||
return codec.encodeSuccessEnvelope(await handler(call));
|
||||
} on PlatformException catch (e) {
|
||||
return codec.encodeErrorEnvelope(
|
||||
code: e.code,
|
||||
message: e.message,
|
||||
details: e.details,
|
||||
);
|
||||
} on MissingPluginException {
|
||||
return null;
|
||||
} catch (e) {
|
||||
return codec.encodeErrorEnvelope(code: 'error', message: e.toString(), details: null);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -230,18 +221,19 @@ class OptionalMethodChannel extends MethodChannel {
|
||||
/// A named channel for communicating with platform plugins using event streams.
|
||||
///
|
||||
/// Stream setup requests are encoded into binary before being sent,
|
||||
/// and binary events received are decoded into Dart values. The [MethodCodec]
|
||||
/// used must be compatible with the one used by the platform plugin. This can
|
||||
/// be achieved by creating a FlutterEventChannel counterpart of this channel on
|
||||
/// the platform side. The Dart type of events sent and received is `dynamic`,
|
||||
/// but only values supported by the specified [MethodCodec] can be used.
|
||||
/// and binary events and errors received are decoded into Dart values.
|
||||
/// The [MethodCodec] used must be compatible with the one used by the platform
|
||||
/// plugin. This can be achieved by creating an `EventChannel` counterpart of
|
||||
/// this channel on the platform side. The Dart type of events sent and received
|
||||
/// is `dynamic`, but only values supported by the specified [MethodCodec] can
|
||||
/// be used.
|
||||
///
|
||||
/// The identity of the channel is given by its name, so other uses of that name
|
||||
/// with may interfere with this channel's communication.
|
||||
/// The logical identity of the channel is given by its name. Identically named
|
||||
/// channels will interfere with each other's communication.
|
||||
///
|
||||
/// See: <https://flutter.io/platform-channels/>
|
||||
class EventChannel {
|
||||
/// Creates a [EventChannel] with the specified [name].
|
||||
/// Creates an [EventChannel] with the specified [name].
|
||||
///
|
||||
/// The [codec] used will be [StandardMethodCodec], unless otherwise
|
||||
/// specified.
|
||||
@@ -263,61 +255,44 @@ class EventChannel {
|
||||
/// received from the platform plugin;
|
||||
/// * an error event containing a [PlatformException] for each error event
|
||||
/// received from the platform plugin;
|
||||
/// * an error event containing a [FormatException] for each event received
|
||||
/// where decoding fails;
|
||||
/// * an error event containing a [PlatformException],
|
||||
/// [MissingPluginException], or [FormatException] whenever stream setup fails
|
||||
/// (stream setup is done only when listener count changes from 0 to 1).
|
||||
///
|
||||
/// Notes for platform plugin implementers:
|
||||
///
|
||||
/// Plugins must expose methods named `listen` and `cancel` suitable for
|
||||
/// invocations by [MethodChannel.invokeMethod]. Both methods are
|
||||
/// invoked with the specified [arguments].
|
||||
///
|
||||
/// Following the semantics of broadcast streams, `listen` will be called as
|
||||
/// the first listener registers with the returned stream, and `cancel` when
|
||||
/// the last listener cancels its registration. This pattern may repeat
|
||||
/// indefinitely. Platform plugins should consume no stream-related resources
|
||||
/// while listener count is zero.
|
||||
/// Errors occurring during stream activation or deactivation are reported
|
||||
/// through the [FlutterError] facility. Stream activation happens only when
|
||||
/// stream listener count changes from 0 to 1. Stream deactivation happens
|
||||
/// only when stream listener count changes from 1 to 0.
|
||||
Stream<dynamic> receiveBroadcastStream([dynamic arguments]) {
|
||||
final MethodChannel methodChannel = new MethodChannel(name, codec);
|
||||
StreamController<dynamic> controller;
|
||||
controller = new StreamController<dynamic>.broadcast(
|
||||
onListen: () async {
|
||||
BinaryMessages.setMessageHandler(
|
||||
name, (ByteData reply) async {
|
||||
if (reply == null) {
|
||||
controller.close();
|
||||
} else {
|
||||
try {
|
||||
controller.add(codec.decodeEnvelope(reply));
|
||||
} catch (e) {
|
||||
controller.addError(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
try {
|
||||
await methodChannel.invokeMethod('listen', arguments);
|
||||
} catch (e) {
|
||||
BinaryMessages.setMessageHandler(name, null);
|
||||
controller.addError(e);
|
||||
}
|
||||
}, onCancel: () async {
|
||||
BinaryMessages.setMessageHandler(name, null);
|
||||
try {
|
||||
await methodChannel.invokeMethod('cancel', arguments);
|
||||
} catch (exception, stack) {
|
||||
FlutterError.reportError(new FlutterErrorDetails(
|
||||
exception: exception,
|
||||
stack: stack,
|
||||
library: 'services library',
|
||||
context: 'while de-activating platform stream on channel $name',
|
||||
));
|
||||
}
|
||||
controller = new StreamController<dynamic>.broadcast(onListen: () async {
|
||||
BinaryMessages.setMessageHandler(name, (ByteData reply) async {
|
||||
if (reply == null)
|
||||
controller.close();
|
||||
else
|
||||
controller.add(codec.decodeEnvelope(reply));
|
||||
});
|
||||
try {
|
||||
await methodChannel.invokeMethod('listen', arguments);
|
||||
} catch (exception, stack) {
|
||||
FlutterError.reportError(new FlutterErrorDetails(
|
||||
exception: exception,
|
||||
stack: stack,
|
||||
library: 'services library',
|
||||
context: 'while activating platform stream on channel $name',
|
||||
));
|
||||
}
|
||||
);
|
||||
}, onCancel: () async {
|
||||
BinaryMessages.setMessageHandler(name, null);
|
||||
try {
|
||||
await methodChannel.invokeMethod('cancel', arguments);
|
||||
} catch (exception, stack) {
|
||||
FlutterError.reportError(new FlutterErrorDetails(
|
||||
exception: exception,
|
||||
stack: stack,
|
||||
library: 'services library',
|
||||
context: 'while de-activating platform stream on channel $name',
|
||||
));
|
||||
}
|
||||
});
|
||||
return controller.stream;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,17 +8,20 @@ import 'dart:ui' as ui;
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import 'platform_channel.dart';
|
||||
|
||||
typedef Future<ByteData> _MessageHandler(ByteData message);
|
||||
|
||||
/// Sends binary messages to and receives binary messages from platform plugins.
|
||||
///
|
||||
/// See also:
|
||||
///
|
||||
/// * [BasicMessageChannel], which provides messaging services similar to
|
||||
/// [BinaryMessages], but with pluggable message codecs in support of sending
|
||||
/// strings or semi-structured messages.
|
||||
/// * [MethodChannel], which provides higher-level platform
|
||||
/// communication such as method invocations and event streams.
|
||||
/// * [BasicMessageChannel], which provides basic messaging services similar to
|
||||
/// `BinaryMessages`, but with pluggable message codecs in support of sending
|
||||
/// strings or semi-structured messages.
|
||||
/// * [MethodChannel], which provides platform communication using asynchronous
|
||||
/// method calls.
|
||||
/// * [EventChannel], which provides platform communication using event streams.
|
||||
///
|
||||
/// See: <https://flutter.io/platform-channels/>
|
||||
class BinaryMessages {
|
||||
@@ -54,7 +57,7 @@ class BinaryMessages {
|
||||
/// Typically called by [ServicesBinding] to handle platform messages received
|
||||
/// from [ui.window.onPlatformMessage].
|
||||
///
|
||||
/// To register a handler for a given message channel, see [PlatformChannel].
|
||||
/// To register a handler for a given message channel, see [setMessageHandler].
|
||||
static Future<Null> handlePlatformMessage(
|
||||
String channel, ByteData data, ui.PlatformMessageResponseCallback callback) async {
|
||||
ByteData response;
|
||||
|
||||
@@ -9,7 +9,7 @@ import 'package:flutter/services.dart';
|
||||
import 'package:test/test.dart';
|
||||
|
||||
void main() {
|
||||
group('PlatformMessageChannel', () {
|
||||
group('BasicMessageChannel', () {
|
||||
const MessageCodec<String> string = const StringCodec();
|
||||
const BasicMessageChannel<String> channel = const BasicMessageChannel<String>('ch', string);
|
||||
test('can send string message and get reply', () async {
|
||||
@@ -34,7 +34,7 @@ void main() {
|
||||
});
|
||||
});
|
||||
|
||||
group('PlatformMethodChannel', () {
|
||||
group('MethodChannel', () {
|
||||
const MessageCodec<dynamic> jsonMessage = const JSONMessageCodec();
|
||||
const MethodCodec jsonMethod = const JSONMethodCodec();
|
||||
const MethodChannel channel = const MethodChannel('ch7', jsonMethod);
|
||||
@@ -89,8 +89,75 @@ void main() {
|
||||
fail('MissingPluginException expected');
|
||||
}
|
||||
});
|
||||
test('can handle method call with no registered plugin', () async {
|
||||
channel.setMethodCallHandler(null);
|
||||
final ByteData call = jsonMethod.encodeMethodCall(new MethodCall('sayHello', 'hello'));
|
||||
ByteData envelope;
|
||||
await BinaryMessages.handlePlatformMessage('ch7', call, (ByteData result) {
|
||||
envelope = result;
|
||||
});
|
||||
expect(envelope, isNull);
|
||||
});
|
||||
test('can handle method call of unimplemented method', () async {
|
||||
channel.setMethodCallHandler((MethodCall call) async {
|
||||
throw new MissingPluginException();
|
||||
});
|
||||
final ByteData call = jsonMethod.encodeMethodCall(new MethodCall('sayHello', 'hello'));
|
||||
ByteData envelope;
|
||||
await BinaryMessages.handlePlatformMessage('ch7', call, (ByteData result) {
|
||||
envelope = result;
|
||||
});
|
||||
expect(envelope, isNull);
|
||||
});
|
||||
test('can handle method call with successful result', () async {
|
||||
channel.setMethodCallHandler((MethodCall call) async => '${call.arguments}, world');
|
||||
final ByteData call = jsonMethod.encodeMethodCall(new MethodCall('sayHello', 'hello'));
|
||||
ByteData envelope;
|
||||
await BinaryMessages.handlePlatformMessage('ch7', call, (ByteData result) {
|
||||
envelope = result;
|
||||
});
|
||||
expect(jsonMethod.decodeEnvelope(envelope), equals('hello, world'));
|
||||
});
|
||||
test('can handle method call with expressive error result', () async {
|
||||
channel.setMethodCallHandler((MethodCall call) async {
|
||||
throw new PlatformException(code: 'bad', message: 'sayHello failed', details: null);
|
||||
});
|
||||
final ByteData call = jsonMethod.encodeMethodCall(new MethodCall('sayHello', 'hello'));
|
||||
ByteData envelope;
|
||||
await BinaryMessages.handlePlatformMessage('ch7', call, (ByteData result) {
|
||||
envelope = result;
|
||||
});
|
||||
try {
|
||||
jsonMethod.decodeEnvelope(envelope);
|
||||
fail('Exception expected');
|
||||
} on PlatformException catch(e) {
|
||||
expect(e.code, equals('bad'));
|
||||
expect(e.message, equals('sayHello failed'));
|
||||
} catch (e) {
|
||||
fail('PlatformException expected');
|
||||
}
|
||||
});
|
||||
test('can handle method call with other error result', () async {
|
||||
channel.setMethodCallHandler((MethodCall call) async {
|
||||
throw new ArgumentError('bad');
|
||||
});
|
||||
final ByteData call = jsonMethod.encodeMethodCall(new MethodCall('sayHello', 'hello'));
|
||||
ByteData envelope;
|
||||
await BinaryMessages.handlePlatformMessage('ch7', call, (ByteData result) {
|
||||
envelope = result;
|
||||
});
|
||||
try {
|
||||
jsonMethod.decodeEnvelope(envelope);
|
||||
fail('Exception expected');
|
||||
} on PlatformException catch(e) {
|
||||
expect(e.code, equals('error'));
|
||||
expect(e.message, equals('Invalid argument(s): bad'));
|
||||
} catch (e) {
|
||||
fail('PlatformException expected');
|
||||
}
|
||||
});
|
||||
});
|
||||
group('PlatformEventChannel', () {
|
||||
group('EventChannel', () {
|
||||
const MessageCodec<dynamic> jsonMessage = const JSONMessageCodec();
|
||||
const MethodCodec jsonMethod = const JSONMethodCodec();
|
||||
const EventChannel channel = const EventChannel('ch', jsonMethod);
|
||||
|
||||
Reference in New Issue
Block a user