From 32fbc03c630a7a2aad5fe04c1bbce7725a1c92b7 Mon Sep 17 00:00:00 2001 From: Kevin Moore Date: Mon, 1 Feb 2021 00:12:26 -0800 Subject: [PATCH] Enable and fix pedantic v1.9 lints (#445) Co-authored-by: Vyacheslav Egorov --- .github/workflows/dart.yml | 7 ++- analysis_options.yaml | 45 ++++++++++++++++--- example/grpc-web/lib/app.dart | 4 +- example/metadata/bin/client.dart | 2 +- example/metadata/bin/server.dart | 2 +- example/metadata/lib/src/client.dart | 4 +- example/metadata/lib/src/server.dart | 7 +-- example/route_guide/bin/client.dart | 2 +- example/route_guide/bin/server.dart | 2 +- example/route_guide/lib/src/client.dart | 2 +- example/route_guide/lib/src/server.dart | 10 +++-- interop/lib/src/client.dart | 8 ++-- lib/src/auth/auth.dart | 2 + lib/src/auth/auth_io.dart | 3 ++ lib/src/auth/rsa.dart | 40 ++++++++--------- lib/src/client/call.dart | 2 +- lib/src/client/client.dart | 7 ++- lib/src/client/common.dart | 5 ++- lib/src/client/http2_connection.dart | 16 ++++--- lib/src/client/options.dart | 2 +- .../client/transport/http2_credentials.dart | 5 ++- lib/src/client/transport/http2_transport.dart | 2 + lib/src/client/transport/transport.dart | 7 +-- lib/src/client/transport/xhr_transport.dart | 6 ++- lib/src/server/handler.dart | 12 ++++- lib/src/server/server.dart | 9 ++-- lib/src/server/service.dart | 2 +- lib/src/shared/codec.dart | 2 +- lib/src/shared/profiler.dart | 2 +- test/client_handles_bad_connections_test.dart | 7 +-- test/client_tests/call_test.dart | 2 +- .../client_tests/client_interceptor_test.dart | 17 +++---- test/client_tests/client_test.dart | 6 +-- .../client_transport_connector_test.dart | 6 +-- .../client_xhr_transport_test.dart | 7 +-- test/connection_server_test.dart | 4 +- test/grpc_web_decoding_test.dart | 6 +-- test/grpc_web_server.dart | 2 +- test/grpc_web_test.dart | 4 +- test/round_trip_test.dart | 14 +++--- ...server_handles_broken_connection_test.dart | 7 +-- test/server_test.dart | 6 +-- test/src/client_utils.dart | 12 ++++- test/src/server_utils.dart | 8 ++-- test/src/utils.dart | 3 +- test/timeline_test.dart | 12 +++-- test/timeout_test.dart | 2 +- 47 files changed, 215 insertions(+), 129 deletions(-) diff --git a/.github/workflows/dart.yml b/.github/workflows/dart.yml index 24c29fa..4aa214c 100644 --- a/.github/workflows/dart.yml +++ b/.github/workflows/dart.yml @@ -28,18 +28,17 @@ jobs: run: dart pub get - name: Check formatting run: dart format --output=none --set-exit-if-changed . - - name: Analyze code (lib and test) - run: dart analyze --fatal-infos . - name: Analyze code (introp and examples) run: | for example in interop example/*/; do pushd $example - echo [Analyzing $example] + echo [Getting dependencies in $example] dart pub get - dart analyze --fatal-infos . popd done shell: bash + - name: Analyze code + run: dart analyze --fatal-infos . # Run tests on a matrix consisting of three dimensions: # 1. OS: mac, windows, linux diff --git a/analysis_options.yaml b/analysis_options.yaml index ea75ffc..6ffed43 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -1,21 +1,56 @@ # Lint rules and documentation, see http://dart-lang.github.io/linter/lints -analyzer: - exclude: - - example/** - - interop/** + linter: rules: + - always_declare_return_types + - always_require_non_null_named_parameters + - annotate_overrides + - avoid_empty_else - avoid_init_to_null + - avoid_null_checks_in_equality_operators + - avoid_relative_lib_imports + - avoid_return_types_on_setters + - avoid_shadowing_type_parameters + - avoid_types_as_parameter_names + - camel_case_extensions - cancel_subscriptions - close_sinks + - curly_braces_in_flow_control_structures - directives_ordering + - empty_catches + - empty_constructor_bodies - hash_and_equals - iterable_contains_unrelated_type + - library_names + - library_prefixes - list_remove_unrelated_type + - no_duplicate_case_values + - null_closures + - omit_local_variable_types + - prefer_adjacent_string_concatenation + - prefer_collection_literals + - prefer_conditional_assignment + - prefer_contains + - prefer_equal_for_default_values - prefer_final_fields - prefer_final_locals + - prefer_for_elements_to_map_fromIterable + - prefer_generic_function_type_aliases + - prefer_if_null_operators + - prefer_is_empty - prefer_is_not_empty + - prefer_iterable_whereType + - prefer_single_quotes + - prefer_spread_collections + - recursive_getters + - slash_for_doc_comments - test_types_in_equals + - type_init_formals + - unnecessary_const + - unnecessary_new + - unnecessary_null_in_if_null_operators + - unnecessary_this - unrelated_type_equality_checks + - use_function_type_syntax_for_parameters + - use_rethrow_when_possible - valid_regexps - - prefer_collection_literals diff --git a/example/grpc-web/lib/app.dart b/example/grpc-web/lib/app.dart index 48dc856..85ef7ab 100644 --- a/example/grpc-web/lib/app.dart +++ b/example/grpc-web/lib/app.dart @@ -33,11 +33,11 @@ class EchoApp { } void _addLeftMessage(String message) { - _addMessage(message, "label-primary pull-left"); + _addMessage(message, 'label-primary pull-left'); } void _addRightMessage(String message) { - _addMessage(message, "label-default pull-right"); + _addMessage(message, 'label-default pull-right'); } void _addMessage(String message, String cssClass) { diff --git a/example/metadata/bin/client.dart b/example/metadata/bin/client.dart index 0e5c5aa..66e3479 100644 --- a/example/metadata/bin/client.dart +++ b/example/metadata/bin/client.dart @@ -15,6 +15,6 @@ import 'package:metadata/src/client.dart'; -main(List args) { +void main(List args) { Client().main(args); } diff --git a/example/metadata/bin/server.dart b/example/metadata/bin/server.dart index 8124253..6b1819a 100644 --- a/example/metadata/bin/server.dart +++ b/example/metadata/bin/server.dart @@ -15,6 +15,6 @@ import 'package:metadata/src/server.dart'; -main(List args) { +void main(List args) { Server().main(args); } diff --git a/example/metadata/lib/src/client.dart b/example/metadata/lib/src/client.dart index 79712c2..6644304 100644 --- a/example/metadata/lib/src/client.dart +++ b/example/metadata/lib/src/client.dart @@ -113,7 +113,7 @@ class Client { /// after receiving more than 5 responses. Future runFibonacciCancel() async { final call = stub.fibonacci(Empty()); - int count = 0; + var count = 0; try { await for (var number in call) { count++; @@ -135,7 +135,7 @@ class Client { Future runFibonacciTimeout() async { final call = stub.fibonacci(Empty(), options: CallOptions(timeout: Duration(seconds: 2))); - int count = 0; + var count = 0; try { await for (var number in call) { count++; diff --git a/example/metadata/lib/src/server.dart b/example/metadata/lib/src/server.dart index 7a328b7..1f49424 100644 --- a/example/metadata/lib/src/server.dart +++ b/example/metadata/lib/src/server.dart @@ -40,7 +40,7 @@ class MetadataService extends MetadataServiceBase { @override Stream addOne(grpc.ServiceCall call, Stream request) async* { - int lastNumber = -1; + var lastNumber = -1; try { await for (var number in request) { lastNumber = number.value; @@ -56,9 +56,10 @@ class MetadataService extends MetadataServiceBase { } /// Streams a Fibonacci number every 500ms until the call is canceled. + @override Stream fibonacci(grpc.ServiceCall call, Empty request) async* { - int previous = 0; - int current = 1; + var previous = 0; + var current = 1; try { while (true) { await Future.delayed(Duration(milliseconds: 500)); diff --git a/example/route_guide/bin/client.dart b/example/route_guide/bin/client.dart index b41c226..f816550 100644 --- a/example/route_guide/bin/client.dart +++ b/example/route_guide/bin/client.dart @@ -15,6 +15,6 @@ import 'package:route_guide/src/client.dart'; -main(List args) async { +Future main(List args) async { await Client().main(args); } diff --git a/example/route_guide/bin/server.dart b/example/route_guide/bin/server.dart index eae657a..69bcba0 100644 --- a/example/route_guide/bin/server.dart +++ b/example/route_guide/bin/server.dart @@ -15,6 +15,6 @@ import 'package:route_guide/src/server.dart'; -main(List args) async { +Future main(List args) async { await Server().main(args); } diff --git a/example/route_guide/lib/src/client.dart b/example/route_guide/lib/src/client.dart index b5f75cd..f2ba669 100644 --- a/example/route_guide/lib/src/client.dart +++ b/example/route_guide/lib/src/client.dart @@ -94,7 +94,7 @@ class Client { Stream generateRoute(int count) async* { final random = Random(); - for (int i = 0; i < count; i++) { + for (var i = 0; i < count; i++) { final point = featuresDb[random.nextInt(featuresDb.length)].location; print( 'Visiting point ${point.latitude / coordFactor}, ${point.longitude / coordFactor}'); diff --git a/example/route_guide/lib/src/server.dart b/example/route_guide/lib/src/server.dart index 34bb5bc..74782d5 100644 --- a/example/route_guide/lib/src/server.dart +++ b/example/route_guide/lib/src/server.dart @@ -75,9 +75,9 @@ class RouteGuideService extends RouteGuideServiceBase { @override Future recordRoute( grpc.ServiceCall call, Stream request) async { - int pointCount = 0; - int featureCount = 0; - double distance = 0.0; + var pointCount = 0; + var featureCount = 0; + var distance = 0.0; Point previous; final timer = Stopwatch(); @@ -110,7 +110,9 @@ class RouteGuideService extends RouteGuideServiceBase { grpc.ServiceCall call, Stream request) async* { await for (var note in request) { final notes = routeNotes.putIfAbsent(note.location, () => []); - for (var note in notes) yield note; + for (var note in notes) { + yield note; + } notes.add(note); } } diff --git a/interop/lib/src/client.dart b/interop/lib/src/client.dart index 2cb93c8..8c34872 100644 --- a/interop/lib/src/client.dart +++ b/interop/lib/src/client.dart @@ -51,7 +51,7 @@ class Tester { return File(serviceAccountKeyFile).readAsStringSync(); } - void set serverPort(String value) { + set serverPort(String value) { if (value == null) { _serverPort = null; return; @@ -63,11 +63,11 @@ class Tester { } } - void set useTls(String value) { + set useTls(String value) { _useTls = value != 'false'; } - void set useTestCA(String value) { + set useTestCA(String value) { _useTestCA = value == 'true'; } @@ -613,7 +613,7 @@ class Tester { final call = client.fullDuplexCall(requests.stream); requests.close(); final responses = await call.toList(); - if (responses.length != 0) { + if (responses.isNotEmpty) { throw 'Received too many responses. ${responses.length} != 0'; } } diff --git a/lib/src/auth/auth.dart b/lib/src/auth/auth.dart index a5ae12b..8eff52e 100644 --- a/lib/src/auth/auth.dart +++ b/lib/src/auth/auth.dart @@ -60,6 +60,7 @@ abstract class BaseAuthenticator { abstract class HttpBasedAuthenticator extends BaseAuthenticator { Future? _call; + @override Future obtainAccessCredentials(String uri) { if (_call == null) { final authClient = http.Client(); @@ -94,6 +95,7 @@ class JwtServiceAccountAuthenticator extends BaseAuthenticator { String? get projectId => _projectId; + @override Future obtainAccessCredentials(String uri) async { _accessToken = _jwtTokenFor(_serviceAccountCredentials, _keyId, uri); } diff --git a/lib/src/auth/auth_io.dart b/lib/src/auth/auth_io.dart index 4d75ce2..ed20cd1 100644 --- a/lib/src/auth/auth_io.dart +++ b/lib/src/auth/auth_io.dart @@ -7,6 +7,7 @@ import 'package:http/http.dart' as http; import 'auth.dart'; class ComputeEngineAuthenticator extends HttpBasedAuthenticator { + @override Future obtainCredentialsWithClient( http.Client client, String uri) => auth.obtainAccessCredentialsViaMetadataServer(client); @@ -30,6 +31,7 @@ class ServiceAccountAuthenticator extends HttpBasedAuthenticator { String? get projectId => _projectId; + @override Future obtainCredentialsWithClient( http.Client client, String uri) => auth.obtainAccessCredentialsViaServiceAccount( @@ -47,6 +49,7 @@ class _CredentialsRefreshingAuthenticator extends HttpBasedAuthenticator { this._quotaProject, ); + @override Future authenticate(Map metadata, String uri) async { await super.authenticate(metadata, uri); if (_quotaProject != null) { diff --git a/lib/src/auth/rsa.dart b/lib/src/auth/rsa.dart index 87a18e1..a1669b1 100644 --- a/lib/src/auth/rsa.dart +++ b/lib/src/auth/rsa.dart @@ -30,7 +30,7 @@ class RS256Signer { // NIST sha-256 OID (2 16 840 1 101 3 4 2 1) // See a reference for the encoding here: // http://msdn.microsoft.com/en-us/library/bb540809%28v=vs.85%29.aspx - static const _RSA_SHA256_ALGORITHM_IDENTIFIER = const [ + static const _RSA_SHA256_ALGORITHM_IDENTIFIER = [ 0x06, 0x09, 0x60, @@ -52,7 +52,7 @@ class RS256Signer { final digest = _digestInfo(sha256.convert(bytes).bytes); final modulusLen = (_rsaKey.bitLength + 7) ~/ 8; - final block = new Uint8List(modulusLen); + final block = Uint8List(modulusLen); final padLength = block.length - digest.length - 3; block[0] = 0x00; block[1] = 0x01; @@ -68,7 +68,7 @@ class RS256Signer { // digest OCTET STRING // } var offset = 0; - final digestInfo = new Uint8List( + final digestInfo = Uint8List( 2 + 2 + _RSA_SHA256_ALGORITHM_IDENTIFIER.length + 2 + 2 + hash.length); { // DigestInfo @@ -100,14 +100,14 @@ class ASN1Parser { static ASN1Object parse(Uint8List bytes) { Never invalidFormat(String msg) { - throw new ArgumentError("Invalid DER encoding: $msg"); + throw ArgumentError('Invalid DER encoding: $msg'); } - final data = new ByteData.view(bytes.buffer); - int offset = 0; + final data = ByteData.view(bytes.buffer); + var offset = 0; final end = bytes.length; - checkNBytesAvailable(int n) { + void checkNBytesAvailable(int n) { if ((offset + n) > end) { invalidFormat('Tried to read more bytes than available.'); } @@ -134,10 +134,10 @@ class ASN1Parser { // Long length encoding form: // This byte has in bits 0..6 the number of bytes following which encode // the length. - int countLengthBytes = lengthByte & 0x7f; + var countLengthBytes = lengthByte & 0x7f; checkNBytesAvailable(countLengthBytes); - int length = 0; + var length = 0; while (countLengthBytes > 0) { length = (length << 8) | data.getUint8(offset++); countLengthBytes--; @@ -159,16 +159,16 @@ class ASN1Parser { switch (tag) { case INTEGER_TAG: final size = readEncodedLength(); - return new ASN1Integer(RSAAlgorithm.bytes2BigInt(readBytes(size))); + return ASN1Integer(RSAAlgorithm.bytes2BigInt(readBytes(size))); case OCTET_STRING_TAG: final size = readEncodedLength(); - return new ASN1OctetString(readBytes(size)); + return ASN1OctetString(readBytes(size)); case NULL_TAG: readNullBytes(); - return new ASN1Null(); + return ASN1Null(); case OBJECT_ID_TAG: final size = readEncodedLength(); - return new ASN1ObjectIdentifier(readBytes(size)); + return ASN1ObjectIdentifier(readBytes(size)); case SEQUENCE_TAG: final lengthInBytes = readEncodedLength(); if ((offset + lengthInBytes) > end) { @@ -180,7 +180,7 @@ class ASN1Parser { while (offset < endOfSequence) { objects.add(decodeObject()); } - return new ASN1Sequence(objects); + return ASN1Sequence(objects); default: invalidFormat( 'Unexpected tag $tag at offset ${offset - 1} (end: $end).'); @@ -189,7 +189,7 @@ class ASN1Parser { final obj = decodeObject(); if (offset != bytes.length) { - throw new ArgumentError('More bytes than expected in ASN1 encoding.'); + throw ArgumentError('More bytes than expected in ASN1 encoding.'); } return obj; } @@ -300,17 +300,17 @@ abstract class RSAAlgorithm { static BigInt bytes2BigInt(List bytes) { var number = BigInt.zero; for (var i = 0; i < bytes.length; i++) { - number = (number << 8) | new BigInt.from(bytes[i]); + number = (number << 8) | BigInt.from(bytes[i]); } return number; } static List integer2Bytes(BigInt integer, int intendedLength) { if (integer < BigInt.one) { - throw new ArgumentError('Only positive integers are supported.'); + throw ArgumentError('Only positive integers are supported.'); } - final bytes = new Uint8List(intendedLength); - for (int i = bytes.length - 1; i >= 0; i--) { + final bytes = Uint8List(intendedLength); + for (var i = bytes.length - 1; i >= 0; i--) { bytes[i] = (integer & _bigIntFF).toInt(); integer >>= 8; } @@ -318,4 +318,4 @@ abstract class RSAAlgorithm { } } -final _bigIntFF = new BigInt.from(0xff); +final _bigIntFF = BigInt.from(0xff); diff --git a/lib/src/client/call.dart b/lib/src/client/call.dart index 75f0aba..156462b 100644 --- a/lib/src/client/call.dart +++ b/lib/src/client/call.dart @@ -50,7 +50,7 @@ const _statusDetailsHeader = 'grpc-status-details-bin'; /// by previous metadata providers) and the [uri] that is being called, and is /// expected to modify the map before returning or before completing the /// returned [Future]. -typedef FutureOr MetadataProvider( +typedef MetadataProvider = FutureOr Function( Map metadata, String uri); /// Runtime options for an RPC. diff --git a/lib/src/client/client.dart b/lib/src/client/client.dart index 2d52124..8814064 100644 --- a/lib/src/client/client.dart +++ b/lib/src/client/client.dart @@ -45,9 +45,8 @@ regenerate these stubs using protobuf compiler plugin version 19.2.0 or newer. ResponseFuture $createUnaryCall(ClientMethod method, Q request, {CallOptions? options}) { - ClientUnaryInvoker invoker = (method, request, options) => - ResponseFuture( - _channel.createCall(method, Stream.value(request), options)); + var invoker = (method, request, options) => ResponseFuture( + _channel.createCall(method, Stream.value(request), options)); for (final interceptor in _interceptors.reversed) { final delegate = invoker; @@ -61,7 +60,7 @@ regenerate these stubs using protobuf compiler plugin version 19.2.0 or newer. ResponseStream $createStreamingCall( ClientMethod method, Stream requests, {CallOptions? options}) { - ClientStreamingInvoker invoker = (method, request, options) => + var invoker = (method, request, options) => ResponseStream(_channel.createCall(method, requests, options)); for (final interceptor in _interceptors.reversed) { diff --git a/lib/src/client/common.dart b/lib/src/client/common.dart index 1140703..901ff1a 100644 --- a/lib/src/client/common.dart +++ b/lib/src/client/common.dart @@ -44,6 +44,7 @@ abstract class Response { /// A gRPC response producing a single value. class ResponseFuture extends DelegatingFuture with _ResponseMixin { + @override final ClientCall _call; static R _ensureOnlyOneResponse(R? previous, R element) { @@ -67,11 +68,13 @@ class ResponseFuture extends DelegatingFuture /// A gRPC response producing a stream of values. class ResponseStream extends DelegatingStream with _ResponseMixin { + @override final ClientCall _call; ResponseStream(this._call) : super(_call.response); - ResponseFuture get single => ResponseFuture(this._call); + @override + ResponseFuture get single => ResponseFuture(_call); } abstract class _ResponseMixin implements Response { diff --git a/lib/src/client/http2_connection.dart b/lib/src/client/http2_connection.dart index fbfc22c..4f7522f 100644 --- a/lib/src/client/http2_connection.dart +++ b/lib/src/client/http2_connection.dart @@ -66,13 +66,15 @@ class Http2ClientConnection implements connection.ClientConnection { ChannelCredentials get credentials => options.credentials; + @override String get authority => _transportConnector.authority; + @override String get scheme => options.credentials.isSecure ? 'https' : 'http'; ConnectionState get state => _state; - static const _estimatedRoundTripTime = const Duration(milliseconds: 20); + static const _estimatedRoundTripTime = Duration(milliseconds: 20); Future connectTransport() async { final connection = await _transportConnector.connect(); @@ -81,7 +83,7 @@ class Http2ClientConnection implements connection.ClientConnection { // Give the settings settings-frame a bit of time to arrive. // TODO(sigurdm): This is a hack. The http2 package should expose a way of // waiting for the settings frame to arrive. - await new Future.delayed(_estimatedRoundTripTime); + await Future.delayed(_estimatedRoundTripTime); if (_state == ConnectionState.shutdown) { _transportConnector.shutdown(); @@ -119,8 +121,8 @@ class Http2ClientConnection implements connection.ClientConnection { /// /// Assumes [_transportConnection] is not `null`. void _refreshConnectionIfUnhealthy() { - final bool isHealthy = _transportConnection!.isOpen; - final bool shouldRefresh = + final isHealthy = _transportConnection!.isOpen; + final shouldRefresh = _connectionLifeTimer.elapsed > options.connectionTimeout; if (shouldRefresh) { _transportConnection!.finish(); @@ -130,6 +132,7 @@ class Http2ClientConnection implements connection.ClientConnection { } } + @override void dispatchCall(ClientCall call) { if (_transportConnection != null) { _refreshConnectionIfUnhealthy(); @@ -149,6 +152,7 @@ class Http2ClientConnection implements connection.ClientConnection { } } + @override GrpcTransportStream makeRequest(String path, Duration? timeout, Map metadata, ErrorHandler onRequestFailure, {CallOptions? callOptions}) { @@ -188,12 +192,14 @@ class Http2ClientConnection implements connection.ClientConnection { _failCall(call, 'Connection shutting down.'); } + @override Future shutdown() async { if (_state == ConnectionState.shutdown) return null; _setShutdownState(); await _transportConnection?.finish(); } + @override Future terminate() async { _setShutdownState(); await _transportConnection?.terminate(); @@ -353,7 +359,7 @@ class _SocketTransportConnector implements ClientTransportConnector { final host = _host is String ? _host as String : (_host as InternetAddress).host; return _options.credentials.authority ?? - (_port == 443 ? host : "$host:$_port"); + (_port == 443 ? host : '$host:$_port'); } @override diff --git a/lib/src/client/options.dart b/lib/src/client/options.dart index dfe0f5d..bf0ddfb 100644 --- a/lib/src/client/options.dart +++ b/lib/src/client/options.dart @@ -26,7 +26,7 @@ const defaultIdleTimeout = Duration(minutes: 5); const defaultConnectionTimeOut = Duration(minutes: 50); const defaultUserAgent = 'dart-grpc/2.0.0'; -typedef Duration BackoffStrategy(Duration? lastBackoff); +typedef BackoffStrategy = Duration Function(Duration? lastBackoff); // Backoff algorithm from https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md const _initialBackoff = Duration(seconds: 1); diff --git a/lib/src/client/transport/http2_credentials.dart b/lib/src/client/transport/http2_credentials.dart index da0b619..5b20e7a 100644 --- a/lib/src/client/transport/http2_credentials.dart +++ b/lib/src/client/transport/http2_credentials.dart @@ -21,7 +21,8 @@ import '../../shared/security.dart'; /// returns `true`, the bad certificate is allowed, and the TLS handshake can /// continue. If the handler returns `false`, the TLS handshake fails, and the /// connection is aborted. -typedef bool BadCertificateHandler(X509Certificate certificate, String host); +typedef BadCertificateHandler = bool Function( + X509Certificate certificate, String host); /// Bad certificate handler that disables all certificate checks. /// DO NOT USE IN PRODUCTION! @@ -60,7 +61,7 @@ class ChannelCredentials { ..setTrustedCertificatesBytes(_certificateBytes!, password: _certificatePassword); } - final context = new SecurityContext(withTrustedRoots: true); + final context = SecurityContext(withTrustedRoots: true); context.setAlpnProtocols(supportedAlpnProtocols, false); return context; } diff --git a/lib/src/client/transport/http2_transport.dart b/lib/src/client/transport/http2_transport.dart index 3a34a05..83fae12 100644 --- a/lib/src/client/transport/http2_transport.dart +++ b/lib/src/client/transport/http2_transport.dart @@ -25,10 +25,12 @@ import 'transport.dart'; class Http2TransportStream extends GrpcTransportStream { final TransportStream _transportStream; + @override final Stream incomingMessages; final StreamController> _outgoingMessages = StreamController(); final ErrorHandler _onError; + @override StreamSink> get outgoingMessages => _outgoingMessages.sink; Http2TransportStream( diff --git a/lib/src/client/transport/transport.dart b/lib/src/client/transport/transport.dart index e14c4ca..7ac70a1 100644 --- a/lib/src/client/transport/transport.dart +++ b/lib/src/client/transport/transport.dart @@ -17,12 +17,13 @@ import 'dart:async'; import '../../shared/message.dart'; -typedef void SocketClosedHandler(); -typedef void ActiveStateHandler(bool isActive); -typedef void ErrorHandler(error, StackTrace stackTrace); +typedef SocketClosedHandler = void Function(); +typedef ActiveStateHandler = void Function(bool isActive); +typedef ErrorHandler = void Function(Object, StackTrace); abstract class GrpcTransportStream { Stream get incomingMessages; + StreamSink> get outgoingMessages; Future terminate(); diff --git a/lib/src/client/transport/xhr_transport.dart b/lib/src/client/transport/xhr_transport.dart index c9e522d..c92fe82 100644 --- a/lib/src/client/transport/xhr_transport.dart +++ b/lib/src/client/transport/xhr_transport.dart @@ -166,7 +166,9 @@ class XhrClientConnection extends ClientConnection { XhrClientConnection(this.uri); + @override String get authority => uri.authority; + @override String get scheme => uri.scheme; void _initializeRequest(HttpRequest request, Map metadata) { @@ -198,7 +200,7 @@ class XhrClientConnection extends ClientConnection { requestUri = cors.moveHttpHeadersToQueryParam(metadata, requestUri); } - final HttpRequest request = createHttpRequest(); + final request = createHttpRequest(); request.open('POST', requestUri.toString()); if (callOptions is WebCallOptions && callOptions.withCredentials == true) { request.withCredentials = true; @@ -206,7 +208,7 @@ class XhrClientConnection extends ClientConnection { // Must set headers after calling open(). _initializeRequest(request, metadata); - final XhrTransportStream transportStream = + final transportStream = XhrTransportStream(request, onError: onError, onDone: _removeStream); _requests.add(transportStream); return transportStream; diff --git a/lib/src/server/handler.dart b/lib/src/server/handler.dart index f8f0886..4239e88 100644 --- a/lib/src/server/handler.dart +++ b/lib/src/server/handler.dart @@ -66,16 +66,22 @@ class ServerHandler_ extends ServiceCall { this._codecRegistry, ); + @override DateTime? get deadline => _deadline; + @override bool get isCanceled => _isCanceled; + @override bool get isTimedOut => _isTimedOut; + @override Map? get clientMetadata => _clientMetadata; + @override Map? get headers => _customHeaders; + @override Map? get trailers => _customTrailers; void handle() { @@ -162,7 +168,7 @@ class ServerHandler_ extends ServiceCall { Future _applyInterceptors() async { try { for (final interceptor in _interceptors) { - final error = await interceptor(this, this._descriptor); + final error = await interceptor(this, _descriptor); if (error != null) { return error; } @@ -293,6 +299,7 @@ class ServerHandler_ extends ServiceCall { } } + @override void sendHeaders() { if (_headersSent) throw GrpcError.internal('Headers already sent'); @@ -316,6 +323,7 @@ class ServerHandler_ extends ServiceCall { _headersSent = true; } + @override void sendTrailers({int? status = 0, String? message}) { _timeoutTimer?.cancel(); @@ -336,7 +344,7 @@ class ServerHandler_ extends ServiceCall { outgoingTrailersMap['grpc-status'] = status.toString(); if (message != null) { outgoingTrailersMap['grpc-message'] = - Uri.encodeFull(message).replaceAll("%20", " "); + Uri.encodeFull(message).replaceAll('%20', ' '); } final outgoingTrailers =
[]; diff --git a/lib/src/server/server.dart b/lib/src/server/server.dart index a0c0e8c..71ee1d5 100644 --- a/lib/src/server/server.dart +++ b/lib/src/server/server.dart @@ -61,6 +61,7 @@ class ServerTlsCredentials extends ServerCredentials { this.privateKey, this.privateKeyPassword}); + @override SecurityContext get securityContext { final context = createSecurityContext(true); if (privateKey != null) { @@ -152,6 +153,7 @@ class Server extends ConnectionServer { return null; } + @override Service? lookupService(String service) => _services[service]; /// Starts the [Server] with the given options. @@ -162,9 +164,9 @@ class Server extends ConnectionServer { int? port, ServerCredentials? security, ServerSettings? http2ServerSettings, - int backlog: 0, - bool v6Only: false, - bool shared: false}) async { + int backlog = 0, + bool v6Only = false, + bool shared = false}) async { // TODO(dart-lang/grpc-dart#9): Handle HTTP/1.1 upgrade to h2c, if allowed. Stream? server; final securityContext = security?.securityContext; @@ -198,6 +200,7 @@ class Server extends ConnectionServer { }); } + @override @visibleForTesting ServerHandler_ serveStream_(ServerTransportStream stream) { return ServerHandler_(lookupService, stream, _interceptors, _codecRegistry) diff --git a/lib/src/server/service.dart b/lib/src/server/service.dart index 303efca..ac5e37a 100644 --- a/lib/src/server/service.dart +++ b/lib/src/server/service.dart @@ -84,7 +84,7 @@ class ServiceMethod { return future; } - void _awaitAndCatch(Future f) async { + void _awaitAndCatch(Future f) async { try { await f; } catch (_) {} diff --git a/lib/src/shared/codec.dart b/lib/src/shared/codec.dart index c6316a9..8f771d5 100644 --- a/lib/src/shared/codec.dart +++ b/lib/src/shared/codec.dart @@ -54,7 +54,7 @@ class GzipCodec implements Codec { const GzipCodec(); @override - final encodingName = "gzip"; + final encodingName = 'gzip'; @override List compress(List data) { diff --git a/lib/src/shared/profiler.dart b/lib/src/shared/profiler.dart index ddd49a0..c229e11 100644 --- a/lib/src/shared/profiler.dart +++ b/lib/src/shared/profiler.dart @@ -15,7 +15,7 @@ import 'dart:developer'; -typedef TimelineTask TimelineTaskFactory( +typedef TimelineTaskFactory = TimelineTask Function( {String? filterKey, TimelineTask? parent}); TimelineTaskFactory timelineTaskFactory = _defaultTimelineTaskFactory; diff --git a/test/client_handles_bad_connections_test.dart b/test/client_handles_bad_connections_test.dart index 805b0ac..7368aef 100644 --- a/test/client_handles_bad_connections_test.dart +++ b/test/client_handles_bad_connections_test.dart @@ -23,6 +23,7 @@ class TestClient extends grpc.Client { } class TestService extends grpc.Service { + @override String get $name => 'test.TestService'; TestService() { @@ -47,11 +48,11 @@ class FixedConnectionClientChannel extends ClientChannelBase { ClientConnection createConnection() => clientConnection; } -main() async { +Future main() async { testTcpAndUds('client reconnects after the connection gets old', (address) async { // client reconnect after a short delay. - final grpc.Server server = grpc.Server([TestService()]); + final server = grpc.Server([TestService()]); await server.serve(address: address, port: 0); final channel = FixedConnectionClientChannel(Http2ClientConnection( @@ -76,7 +77,7 @@ main() async { testTcpAndUds('client reconnects when stream limit is used', (address) async { // client reconnect after setting stream limit. - final grpc.Server server = grpc.Server([TestService()]); + final server = grpc.Server([TestService()]); await server.serve( address: address, port: 0, diff --git a/test/client_tests/call_test.dart b/test/client_tests/call_test.dart index c493dd7..ceff888 100644 --- a/test/client_tests/call_test.dart +++ b/test/client_tests/call_test.dart @@ -5,7 +5,7 @@ void main() { test('WebCallOptions mergeWith CallOptions returns WebCallOptions', () { final options = WebCallOptions(bypassCorsPreflight: true, withCredentials: true); - final metadata = {"test": "42"}; + final metadata = {'test': '42'}; final mergedOptions = options.mergedWith(CallOptions(metadata: metadata)) as WebCallOptions; diff --git a/test/client_tests/client_interceptor_test.dart b/test/client_tests/client_interceptor_test.dart index aa2eafc..2abbe9c 100644 --- a/test/client_tests/client_interceptor_test.dart +++ b/test/client_tests/client_interceptor_test.dart @@ -13,6 +13,7 @@ class InterceptorInvocation { InterceptorInvocation(this.id, this.unary, this.streaming); + @override String toString() { return '{id: ${id}, unary: ${unary}, streaming: ${streaming}}'; } @@ -48,7 +49,7 @@ class FakeInterceptor implements ClientInterceptor { CallOptions _inject(CallOptions options) { return options.mergedWith(CallOptions(metadata: { - "x-interceptor": _invocations.map((i) => i.toString()).join(', '), + 'x-interceptor': _invocations.map((i) => i.toString()).join(', '), })); } @@ -57,7 +58,7 @@ class FakeInterceptor implements ClientInterceptor { } } -main() { +void main() { test('single unary interceptor', () async { final harness = ClientHarness() ..interceptors = [FakeInterceptor(1)] @@ -81,7 +82,7 @@ main() { expectedResult: responseValue, expectedPath: '/Test/Unary', expectedCustomHeaders: { - "x-interceptor": "{id: 1, unary: 1, streaming: 0}" + 'x-interceptor': '{id: 1, unary: 1, streaming: 0}' }, serverHandlers: [handleRequest], ); @@ -113,8 +114,8 @@ main() { expectedResult: responseValue, expectedPath: '/Test/Unary', expectedCustomHeaders: { - "x-interceptor": - "{id: 1, unary: 1, streaming: 0}, {id: 2, unary: 1, streaming: 0}" + 'x-interceptor': + '{id: 1, unary: 1, streaming: 0}, {id: 2, unary: 1, streaming: 0}' }, serverHandlers: [handleRequest], ); @@ -154,7 +155,7 @@ main() { expectedResult: responses, expectedPath: '/Test/Bidirectional', expectedCustomHeaders: { - "x-interceptor": "{id: 1, unary: 0, streaming: 1}" + 'x-interceptor': '{id: 1, unary: 0, streaming: 1}' }, serverHandlers: [handleRequest, handleRequest, handleRequest], doneHandler: handleDone, @@ -195,8 +196,8 @@ main() { expectedResult: responses, expectedPath: '/Test/Bidirectional', expectedCustomHeaders: { - "x-interceptor": - "{id: 1, unary: 0, streaming: 1}, {id: 2, unary: 0, streaming: 1}" + 'x-interceptor': + '{id: 1, unary: 0, streaming: 1}, {id: 2, unary: 0, streaming: 1}' }, serverHandlers: [handleRequest, handleRequest, handleRequest], doneHandler: handleDone, diff --git a/test/client_tests/client_test.dart b/test/client_tests/client_test.dart index ac4f6cc..8e9d879 100644 --- a/test/client_tests/client_test.dart +++ b/test/client_tests/client_test.dart @@ -330,7 +330,7 @@ void main() { } harness.client = TestClient(harness.channel, decode: (bytes) { - throw "error decoding"; + throw 'error decoding'; }); await harness.runFailureTest( @@ -439,9 +439,9 @@ void main() { }); test('Default reconnect backoff backs off', () { - Duration lastBackoff = defaultBackoffStrategy(null); + var lastBackoff = defaultBackoffStrategy(null); expect(lastBackoff, const Duration(seconds: 1)); - for (int i = 0; i < 12; i++) { + for (var i = 0; i < 12; i++) { final minNext = lastBackoff * (1.6 - 0.2); final maxNext = lastBackoff * (1.6 + 0.2); lastBackoff = defaultBackoffStrategy(lastBackoff); diff --git a/test/client_tests/client_transport_connector_test.dart b/test/client_tests/client_transport_connector_test.dart index f4340c4..16f6ab5 100644 --- a/test/client_tests/client_transport_connector_test.dart +++ b/test/client_tests/client_transport_connector_test.dart @@ -280,7 +280,7 @@ void main() { } harness.client = TestClient(harness.channel, decode: (bytes) { - throw "error decoding"; + throw 'error decoding'; }); await harness.runFailureTest( @@ -389,9 +389,9 @@ void main() { }); test('Default reconnect backoff backs off', () { - Duration lastBackoff = defaultBackoffStrategy(null); + var lastBackoff = defaultBackoffStrategy(null); expect(lastBackoff, const Duration(seconds: 1)); - for (int i = 0; i < 12; i++) { + for (var i = 0; i < 12; i++) { final minNext = lastBackoff * (1.6 - 0.2); final maxNext = lastBackoff * (1.6 + 0.2); lastBackoff = defaultBackoffStrategy(lastBackoff); diff --git a/test/client_tests/client_xhr_transport_test.dart b/test/client_tests/client_xhr_transport_test.dart index 76f8553..1d05e25 100644 --- a/test/client_tests/client_xhr_transport_test.dart +++ b/test/client_tests/client_xhr_transport_test.dart @@ -53,6 +53,7 @@ class MockHttpRequest extends Mock implements HttpRequest { @override final int status; + @override int get readyState => super.noSuchMethod(Invocation.getter(#readyState), -1); @override @@ -69,7 +70,7 @@ class MockXhrClientConnection extends XhrClientConnection { final int _statusCode; @override - createHttpRequest() { + HttpRequest createHttpRequest() { final request = MockHttpRequest(code: _statusCode); latestRequest = request; return request; @@ -360,9 +361,9 @@ void main() { final errorReceived = Completer(); connection.makeRequest('test_path', Duration(seconds: 10), {}, (e, _) { errorReceived.complete(); - errors.add(e); + errors.add(e as GrpcError); }); - const errorDetails = "error details"; + const errorDetails = 'error details'; when(connection.latestRequest.getResponseHeader('Content-Type')) .thenReturn('application/grpc+proto'); when(connection.latestRequest.responseHeaders).thenReturn({}); diff --git a/test/connection_server_test.dart b/test/connection_server_test.dart index 8e0a681..83817eb 100644 --- a/test/connection_server_test.dart +++ b/test/connection_server_test.dart @@ -289,7 +289,7 @@ void main() { } final Interceptor interceptor = (call, method) { - if (method.name == "Unary") { + if (method.name == 'Unary') { return null; } return GrpcError.unauthenticated('Request is unauthenticated'); @@ -311,7 +311,7 @@ void main() { group('returns error if interceptor blocks request', () { final Interceptor interceptor = (call, method) { - if (method.name == "Unary") { + if (method.name == 'Unary') { return GrpcError.unauthenticated('Request is unauthenticated'); } return null; diff --git a/test/grpc_web_decoding_test.dart b/test/grpc_web_decoding_test.dart index b5420d8..aa0f390 100644 --- a/test/grpc_web_decoding_test.dart +++ b/test/grpc_web_decoding_test.dart @@ -5,9 +5,9 @@ import 'package:grpc/src/client/transport/web_streams.dart'; import 'package:grpc/src/shared/message.dart'; import 'package:test/test.dart'; -main() { - test("decoding an empty repeated", () async { - final GrpcData data = await GrpcWebDecoder() +void main() { + test('decoding an empty repeated', () async { + final data = await GrpcWebDecoder() .bind(Stream.fromIterable([ Uint8List.fromList([0, 0, 0, 0, 0]).buffer ])) diff --git a/test/grpc_web_server.dart b/test/grpc_web_server.dart index 0a2811d..e039622 100644 --- a/test/grpc_web_server.dart +++ b/test/grpc_web_server.dart @@ -85,7 +85,7 @@ static_resources: port_value: %TARGET_PORT% '''; -hybridMain(StreamChannel channel) async { +Future hybridMain(StreamChannel channel) async { // Envoy output will be collected and dumped to stdout if envoy exits // with an error. Otherwise if verbose is specified it will be dumped // to stdout unconditionally. diff --git a/test/grpc_web_test.dart b/test/grpc_web_test.dart index 83c1ae0..34c6e21 100644 --- a/test/grpc_web_test.dart +++ b/test/grpc_web_test.dart @@ -56,7 +56,7 @@ void main() { // Verify that terminate does not cause an exception when terminating // channel with multiple active requests. - test("terminate works", () async { + test('terminate works', () async { final channel = GrpcWebClientChannel.xhr(server.uri); final service = EchoServiceClient(channel); @@ -96,7 +96,7 @@ void main() { }); // Verify that stream cancellation does not cause an exception - test("stream cancellation works", () async { + test('stream cancellation works', () async { final channel = GrpcWebClientChannel.xhr(server.uri); final service = EchoServiceClient(channel); diff --git a/test/round_trip_test.dart b/test/round_trip_test.dart index 7902c4f..798e67a 100644 --- a/test/round_trip_test.dart +++ b/test/round_trip_test.dart @@ -23,6 +23,7 @@ class TestClient extends Client { } class TestService extends Service { + @override String get $name => 'test.TestService'; TestService() { @@ -43,6 +44,7 @@ class TestService extends Service { } class TestServiceWithOnMetadataException extends TestService { + @override void $onMetadata(ServiceCall context) { throw Exception('business exception'); } @@ -58,10 +60,10 @@ class FixedConnectionClientChannel extends ClientChannelBase { ClientConnection createConnection() => clientConnection; } -main() async { +Future main() async { testTcpAndUds('round trip insecure connection', (address) async { // round trip test of insecure connection. - final Server server = Server([TestService()]); + final server = Server([TestService()]); await server.serve(address: address, port: 0); final channel = FixedConnectionClientChannel(Http2ClientConnection( @@ -77,7 +79,7 @@ main() async { testTcpAndUds('round trip with outgoing and incoming compression', (address) async { - final Server server = Server( + final server = Server( [TestService()], const [], CodecRegistry(codecs: const [GzipCodec()])); await server.serve(address: address, port: 0); @@ -101,7 +103,7 @@ main() async { testTcpAndUds('round trip secure connection', (address) async { // round trip test of secure connection. - final Server server = Server([TestService()]); + final server = Server([TestService()]); await server.serve( address: address, port: 0, @@ -124,7 +126,7 @@ main() async { }); test('exception in onMetadataException', () async { - final Server server = Server([TestServiceWithOnMetadataException()]); + final server = Server([TestServiceWithOnMetadataException()]); await server.serve(address: 'localhost', port: 0); final channel = FixedConnectionClientChannel(Http2ClientConnection( @@ -140,7 +142,7 @@ main() async { }); test('cancellation of streaming subscription propagates properly', () async { - final Server server = Server([TestService()]); + final server = Server([TestService()]); await server.serve(address: 'localhost', port: 0); final channel = FixedConnectionClientChannel(Http2ClientConnection( diff --git a/test/server_handles_broken_connection_test.dart b/test/server_handles_broken_connection_test.dart index 1eda3e0..b8a934c 100644 --- a/test/server_handles_broken_connection_test.dart +++ b/test/server_handles_broken_connection_test.dart @@ -21,6 +21,7 @@ class TestClient extends grpc.Client { } class TestService extends grpc.Service { + @override String get $name => 'test.TestService'; final void Function() finallyCallback; @@ -31,7 +32,7 @@ class TestService extends grpc.Service { Stream infiniteStream( grpc.ServiceCall call, Future request) async* { - int count = await request; + var count = await request; try { while (true) { count++; @@ -70,9 +71,9 @@ void client(clientData) async { }); } -main() async { +Future main() async { testTcpAndUds( - "the client interrupting the connection does not crash the server", + 'the client interrupting the connection does not crash the server', (address) async { // interrrupt the connect of client, the server does not crash. late grpc.Server server; diff --git a/test/server_test.dart b/test/server_test.dart index 38ab2de..36b3bc5 100644 --- a/test/server_test.dart +++ b/test/server_test.dart @@ -169,7 +169,7 @@ void main() { test('Server returns encoded error for unary call', () async { Future methodHandler(ServiceCall call, Future request) async { - throw GrpcError.unknown("エラー"); + throw GrpcError.unknown('エラー'); } harness @@ -303,7 +303,7 @@ void main() { } final Interceptor interceptor = (call, method) { - if (method.name == "Unary") { + if (method.name == 'Unary') { return null; } return GrpcError.unauthenticated('Request is unauthenticated'); @@ -325,7 +325,7 @@ void main() { group('returns error if interceptor blocks request', () { final Interceptor interceptor = (call, method) { - if (method.name == "Unary") { + if (method.name == 'Unary') { return GrpcError.unauthenticated('Request is unauthenticated'); } return null; diff --git a/test/src/client_utils.dart b/test/src/client_utils.dart index a22bcdc..86ac164 100644 --- a/test/src/client_utils.dart +++ b/test/src/client_utils.dart @@ -62,16 +62,23 @@ class FakeClientTransportConnection extends Http2ClientConnection { Duration testBackoff(Duration? lastBackoff) => const Duration(milliseconds: 1); class FakeChannelOptions implements ChannelOptions { + @override ChannelCredentials credentials = const ChannelCredentials.secure(); + @override Duration idleTimeout = const Duration(seconds: 1); + @override Duration connectionTimeout = const Duration(seconds: 10); + @override String userAgent = 'dart-grpc/1.0.0 test'; + @override BackoffStrategy backoffStrategy = testBackoff; + @override CodecRegistry codecRegistry = CodecRegistry.empty(); } class FakeChannel extends ClientChannel { final Http2ClientConnection connection; + @override final FakeChannelOptions options; FakeChannel(String host, this.connection, this.options) @@ -83,6 +90,7 @@ class FakeChannel extends ClientChannel { class FakeClientConnectorChannel extends ClientTransportConnectorChannel { final Http2ClientConnection connection; + @override final FakeChannelOptions options; FakeClientConnectorChannel( @@ -106,7 +114,7 @@ class TestClient extends Client { TestClient(base.ClientChannel channel, {CallOptions? options, Iterable? interceptors, - this.decode: mockDecode}) + this.decode = mockDecode}) : super(channel, options: options, interceptors: interceptors) { _$unary = ClientMethod('/Test/Unary', mockEncode, decode); _$clientStreaming = @@ -255,7 +263,7 @@ abstract class _Harness { List serverHandlers = const [], void Function()? doneHandler, bool expectDone = true}) async { - int serverHandlerIndex = 0; + var serverHandlerIndex = 0; void handleServerMessage(StreamMessage message) { serverHandlers[serverHandlerIndex++](message); } diff --git a/test/src/server_utils.dart b/test/src/server_utils.dart index bc238d0..8e92c2e 100644 --- a/test/src/server_utils.dart +++ b/test/src/server_utils.dart @@ -91,7 +91,9 @@ class TestInterceptor { } class TestServerStream extends ServerTransportStream { + @override final Stream incomingMessages; + @override final StreamSink outgoingMessages; TestServerStream(this.incomingMessages, this.outgoingMessages); @@ -106,7 +108,7 @@ class TestServerStream extends ServerTransportStream { } @override - set onTerminated(void value(int x)) {} + set onTerminated(void Function(int x) value) {} @override bool get canPush => true; @@ -162,7 +164,7 @@ abstract class _Harness { } void setupTest(List handlers) { - int handlerIndex = 0; + var handlerIndex = 0; void handleMessages(StreamMessage message) { handlers[handlerIndex++](message); } @@ -204,7 +206,7 @@ abstract class _Harness { validateResponseHeaders(header.metadata); } - int responseIndex = 0; + var responseIndex = 0; void handleResponse(StreamMessage message) { final response = validateDataMessage(message); expect(mockDecode(response.data), expectedResponses[responseIndex++]); diff --git a/test/src/utils.dart b/test/src/utils.dart index 9c1a32d..35e631d 100644 --- a/test/src/utils.dart +++ b/test/src/utils.dart @@ -27,8 +27,7 @@ List mockEncode(int value) => List.filled(value, 0); int mockDecode(List value) => value.length; Map headersToMap(List
headers) => - Map.fromIterable(headers, - key: (h) => ascii.decode(h.name), value: (h) => ascii.decode(h.value)); + {for (var h in headers) ascii.decode(h.name): ascii.decode(h.value)}; void validateRequestHeaders(Map headers, {String? path, diff --git a/test/timeline_test.dart b/test/timeline_test.dart index 0ae0d3d..33f91ed 100644 --- a/test/timeline_test.dart +++ b/test/timeline_test.dart @@ -40,6 +40,7 @@ class TestClient extends Client { } class TestService extends Service { + @override String get $name => 'test.TestService'; TestService() { @@ -84,6 +85,7 @@ class FakeTimelineTask extends Fake implements TimelineTask { bool get isComplete => _startFinishCount == 0; + @override void start(String name, {Map? arguments}) { events.add({ 'id': id, @@ -98,6 +100,7 @@ class FakeTimelineTask extends Fake implements TimelineTask { ++_startFinishCount; } + @override void instant(String name, {Map? arguments}) { events.add({ 'id': id, @@ -110,6 +113,7 @@ class FakeTimelineTask extends Fake implements TimelineTask { }); } + @override void finish({Map? arguments}) { events.add({ 'id': id, @@ -128,8 +132,8 @@ TimelineTask fakeTimelineTaskFactory( {String? filterKey, TimelineTask? parent}) => FakeTimelineTask(filterKey: filterKey, parent: parent); -testee() async { - final Server server = Server([TestService()]); +Future testee() async { + final server = Server([TestService()]); await server.serve(address: 'localhost', port: 0); isTimelineLoggingEnabled = true; timelineTaskFactory = fakeTimelineTaskFactory; @@ -171,7 +175,7 @@ void checkWriteEvent(List events) { void checkReceiveEvent(List events) { events = events.where((e) => e['name'] == 'Data received').toList(); expect(events.length, equals(3)); - int sum = 0; + var sum = 0; for (final e in events) { expect(e['id'], 1); // 3 elements are 1, 2 and 3. @@ -200,7 +204,7 @@ void checkFinishEvent(List events) { expect(e.length, 2); } -main([args = const []]) { +void main([args = const []]) { test('Test gRPC timeline logging', () async { await testee(); for (final task in FakeTimelineTask.tasks) { diff --git a/test/timeout_test.dart b/test/timeout_test.dart index 76cc781..95deaa6 100644 --- a/test/timeout_test.dart +++ b/test/timeout_test.dart @@ -73,7 +73,7 @@ void main() { test('Calls time out if deadline is exceeded', () async { void handleRequest(StreamMessage message) { validateDataMessage(message); - final Future delay = Future.delayed(Duration(milliseconds: 2)); + final delay = Future.delayed(Duration(milliseconds: 2)); expect(delay, completes); delay.then((_) { try {