From bd6de71aa8d2d2bf0af8f9a24508d6a43a25f21f Mon Sep 17 00:00:00 2001 From: Jakob Andersen Date: Fri, 18 May 2018 11:05:38 +0200 Subject: [PATCH] Fix Dart 2 runtime issues. (#53) Upgrade to Dart 2.0.0-dev.54.0 to fix issues with mirrors in Dart 2 mode. Added lots of types. --- .gitignore | 3 +- CHANGELOG.md | 4 ++ lib/common.dart | 4 +- lib/datastore.dart | 2 +- lib/db.dart | 2 +- lib/service_scope.dart | 4 +- lib/src/datastore_impl.dart | 13 ++--- lib/src/db/annotations.dart | 11 +++-- lib/src/db/db.dart | 54 ++++++++++----------- lib/src/db/model_db.dart | 16 +++--- lib/src/db/model_db_impl.dart | 38 +++++++-------- lib/src/db/models.dart | 1 - lib/src/pubsub_impl.dart | 18 +++---- lib/src/storage_impl.dart | 19 ++++---- pubspec.yaml | 8 +-- test/common.dart | 22 ++++----- test/common_e2e.dart | 2 +- test/datastore/e2e/datastore_test_impl.dart | 15 +++--- test/datastore/e2e/utils.dart | 6 +-- test/datastore/error_matchers.dart | 2 +- test/db/e2e/db_test_impl.dart | 22 ++++----- test/db/properties_test.dart | 2 +- test/pubsub/pubsub_test.dart | 21 ++++---- test/storage/storage_test.dart | 43 ++++++++-------- 24 files changed, 174 insertions(+), 158 deletions(-) diff --git a/.gitignore b/.gitignore index 794cf6c1..7903d444 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ +.dart_tool/ pubspec.lock packages .pub -.packages \ No newline at end of file +.packages diff --git a/CHANGELOG.md b/CHANGELOG.md index f18707b9..9a6645b8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,7 @@ +## 0.5.0 + +* Fixes to support Dart 2. + ## 0.4.0+1 * Made a number of strong-mode improvements. diff --git a/lib/common.dart b/lib/common.dart index d8135000..c5212778 100644 --- a/lib/common.dart +++ b/lib/common.dart @@ -36,10 +36,10 @@ class StreamFromPages { bool _paused = false; bool _cancelled = false; Page _currentPage; - StreamController _controller; + StreamController _controller; StreamFromPages(this._firstPageProvider) { - _controller = new StreamController( + _controller = new StreamController( sync: true, onListen: _onListen, onPause: _onPause, diff --git a/lib/datastore.dart b/lib/datastore.dart index cbdbd2dd..9dd85b12 100644 --- a/lib/datastore.dart +++ b/lib/datastore.dart @@ -141,7 +141,7 @@ class Key { factory Key.fromParent(String kind, int id, {Key parent}) { var partition; - var elements = []; + var elements = []; if (parent != null) { partition = parent.partition; elements.addAll(parent.elements); diff --git a/lib/db.dart b/lib/db.dart index b020d3f7..3322afd5 100644 --- a/lib/db.dart +++ b/lib/db.dart @@ -15,7 +15,7 @@ import 'dart:core' as core; import 'dart:mirrors' as mirrors; import 'common.dart' show StreamFromPages; -import 'datastore.dart' as datastore; +import 'datastore.dart' as ds; import 'service_scope.dart' as ss; part 'src/db/annotations.dart'; diff --git a/lib/service_scope.dart b/lib/service_scope.dart index 754944f5..d9e5d089 100644 --- a/lib/service_scope.dart +++ b/lib/service_scope.dart @@ -122,12 +122,12 @@ void register(Object key, Object value, {onScopeExit()}) { /// /// The registered on-scope-exit functions are executed in reverse registration /// order. -Object registerScopeExitCallback(onScopeExitCallback()) { +void registerScopeExitCallback(onScopeExitCallback()) { var serviceScope = _serviceScope; if (serviceScope == null) { throw new StateError('Not running inside a service scope zone.'); } - return serviceScope.registerOnScopeExitCallback(onScopeExitCallback); + serviceScope.registerOnScopeExitCallback(onScopeExitCallback); } /// Look up an item by it's key in the currently active service scope. diff --git a/lib/src/datastore_impl.dart b/lib/src/datastore_impl.dart index b5844e4a..789a8865 100644 --- a/lib/src/datastore_impl.dart +++ b/lib/src/datastore_impl.dart @@ -162,8 +162,8 @@ class DatastoreImpl implements datastore.Datastore { } static datastore.Entity _convertApi2DatastoreEntity(api.Entity entity) { - var unindexedProperties = new Set(); - var properties = {}; + var unindexedProperties = new Set(); + var properties = {}; if (entity.properties != null) { entity.properties.forEach((String name, api.Value value) { @@ -267,7 +267,7 @@ class DatastoreImpl implements datastore.Datastore { return orders.map(_convertDatastore2ApiOrder).toList(); } - static Future _handleError(error, stack) { + static Future _handleError(error, stack) { if (error is api.DetailedApiRequestError) { if (error.status == 400) { return new Future.error( @@ -317,7 +317,7 @@ class DatastoreImpl implements datastore.Datastore { request.mode = 'NON_TRANSACTIONAL'; } - var mutations = request.mutations = []; + var mutations = request.mutations = []; if (inserts != null) { for (int i = 0; i < inserts.length; i++) { mutations.add(new api.Mutation() @@ -349,7 +349,8 @@ class DatastoreImpl implements datastore.Datastore { keys = mutationResults .skip(autoIdStartIndex) .take(autoIdInserts.length) - .map((api.MutationResult r) => _convertApi2DatastoreKey(r.key)) + .map( + (api.MutationResult r) => _convertApi2DatastoreKey(r.key)) .toList(); } return new datastore.CommitResult(keys); @@ -495,7 +496,7 @@ class QueryPageImpl implements Page { request.query.limit = batchLimit; return api.projects.runQuery(request, project).then((response) { - var returnedEntities = const []; + var returnedEntities = const []; var batch = response.batch; if (batch.entityResults != null) { diff --git a/lib/src/db/annotations.dart b/lib/src/db/annotations.dart index 92459d35..88a511e3 100644 --- a/lib/src/db/annotations.dart +++ b/lib/src/db/annotations.dart @@ -179,7 +179,7 @@ class ModelKeyProperty extends PrimitiveProperty { Object decodePrimitiveValue(ModelDB db, Object value) { if (value == null) return null; - return db.fromDatastoreKey(value as datastore.Key); + return db.fromDatastoreKey(value as ds.Key); } } @@ -201,13 +201,13 @@ class BlobProperty extends PrimitiveProperty { Object encodeValue(ModelDB db, Object value, {bool forComparison: false}) { if (value == null) return null; - return new datastore.BlobValue(value); + return new ds.BlobValue(value); } Object decodePrimitiveValue(ModelDB db, Object value) { if (value == null) return null; - return (value as datastore.BlobValue).bytes; + return (value as ds.BlobValue).bytes; } } @@ -298,4 +298,9 @@ class StringListProperty extends ListProperty { const StringListProperty({String propertyName, bool indexed: true}) : super(const StringProperty(), propertyName: propertyName, indexed: indexed); + + @override + Object decodePrimitiveValue(ModelDB db, Object value) { + return (super.decodePrimitiveValue(db, value) as core.List).cast(); + } } diff --git a/lib/src/db/db.dart b/lib/src/db/db.dart index aa738253..d463101e 100644 --- a/lib/src/db/db.dart +++ b/lib/src/db/db.dart @@ -25,7 +25,7 @@ class Transaction { static const int _TRANSACTION_COMMITTED = 2; final DatastoreDB db; - final datastore.Transaction _datastoreTransaction; + final ds.Transaction _datastoreTransaction; final List _inserts = []; final List _deletes = []; @@ -108,30 +108,30 @@ class Transaction { } class Query { - final _relationMapping = const { - '<': datastore.FilterRelation.LessThan, - '<=': datastore.FilterRelation.LessThanOrEqual, - '>': datastore.FilterRelation.GreatherThan, - '>=': datastore.FilterRelation.GreatherThanOrEqual, - '=': datastore.FilterRelation.Equal, + final _relationMapping = const { + '<': ds.FilterRelation.LessThan, + '<=': ds.FilterRelation.LessThanOrEqual, + '>': ds.FilterRelation.GreatherThan, + '>=': ds.FilterRelation.GreatherThanOrEqual, + '=': ds.FilterRelation.Equal, }; final DatastoreDB _db; - final datastore.Transaction _transaction; + final ds.Transaction _transaction; final String _kind; final Partition _partition; final Key _ancestorKey; - final List _filters = []; - final List _orders = []; + final List _filters = []; + final List _orders = []; int _offset; int _limit; Query(DatastoreDB dbImpl, Type kind, {Partition partition, Key ancestorKey, - datastore.Transaction datastoreTransaction}) + ds.Transaction datastoreTransaction}) : _db = dbImpl, _kind = dbImpl.modelDB.kindName(kind), _partition = partition, @@ -165,11 +165,11 @@ class Query { // This is for backwards compatibility: We allow [datastore.Key]s for now. // TODO: We should remove the condition in a major version update of // `package:gcloud`. - if (comparisonObject is! datastore.Key) { + if (comparisonObject is! ds.Key) { comparisonObject = _db.modelDB .toDatastoreValue(_kind, name, comparisonObject, forComparison: true); } - _filters.add(new datastore.Filter( + _filters.add(new ds.Filter( _relationMapping[comparison], propertyName, comparisonObject)); } @@ -182,11 +182,11 @@ class Query { void order(String orderString) { // TODO: validate [orderString] (e.g. is name valid) if (orderString.startsWith('-')) { - _orders.add(new datastore.Order(datastore.OrderDirection.Decending, + _orders.add(new ds.Order(ds.OrderDirection.Decending, _convertToDatastoreName(orderString.substring(1)))); } else { - _orders.add(new datastore.Order(datastore.OrderDirection.Ascending, - _convertToDatastoreName(orderString))); + _orders.add(new ds.Order( + ds.OrderDirection.Ascending, _convertToDatastoreName(orderString))); } } @@ -220,7 +220,7 @@ class Query { if (_ancestorKey != null) { ancestorKey = _db.modelDB.toDatastoreKey(_ancestorKey); } - var query = new datastore.Query( + var query = new ds.Query( ancestorKey: ancestorKey, kind: _kind, filters: _filters, @@ -230,10 +230,10 @@ class Query { var partition; if (_partition != null) { - partition = new datastore.Partition(_partition.namespace); + partition = new ds.Partition(_partition.namespace); } - return new StreamFromPages((int pageSize) { + return new StreamFromPages((int pageSize) { return _db.datastore .query(query, transaction: _transaction, partition: partition); }).stream.map(_db.modelDB.fromDatastoreEntity); @@ -254,7 +254,7 @@ class Query { } class DatastoreDB { - final datastore.Datastore datastore; + final ds.Datastore datastore; final ModelDB _modelDB; Partition _defaultPartition; @@ -356,13 +356,13 @@ class DatastoreDB { Future _commitHelper(DatastoreDB db, {List inserts, List deletes, - datastore.Transaction datastoreTransaction}) { + ds.Transaction datastoreTransaction}) { var entityInserts, entityAutoIdInserts, entityDeletes; var autoIdModelInserts; if (inserts != null) { - entityInserts = []; - entityAutoIdInserts = []; - autoIdModelInserts = []; + entityInserts = []; + entityAutoIdInserts = []; + autoIdModelInserts = []; for (var model in inserts) { // If parent was not explicitly set, we assume this model will map to @@ -388,7 +388,7 @@ Future _commitHelper(DatastoreDB db, autoIdInserts: entityAutoIdInserts, deletes: entityDeletes, transaction: datastoreTransaction) - .then((datastore.CommitResult result) { + .then((ds.CommitResult result) { if (entityAutoIdInserts != null && entityAutoIdInserts.length > 0) { for (var i = 0; i < result.autoIdInsertKeys.length; i++) { var key = db.modelDB.fromDatastoreKey(result.autoIdInsertKeys[i]); @@ -400,11 +400,11 @@ Future _commitHelper(DatastoreDB db, } Future> _lookupHelper(DatastoreDB db, List keys, - {datastore.Transaction datastoreTransaction}) { + {ds.Transaction datastoreTransaction}) { var entityKeys = keys.map(db.modelDB.toDatastoreKey).toList(); return db.datastore .lookup(entityKeys, transaction: datastoreTransaction) - .then((List entities) { + .then((List entities) { return entities.map(db.modelDB.fromDatastoreEntity).toList(); }); } diff --git a/lib/src/db/model_db.dart b/lib/src/db/model_db.dart index 63fc3e71..8feb11e7 100644 --- a/lib/src/db/model_db.dart +++ b/lib/src/db/model_db.dart @@ -11,24 +11,24 @@ part of gcloud.db; */ abstract class ModelDB { /** - * Converts a [datastore.Key] to a [Key]. + * Converts a [ds.Key] to a [Key]. */ - Key fromDatastoreKey(datastore.Key datastoreKey); + Key fromDatastoreKey(ds.Key datastoreKey); /** - * Converts a [Key] to a [datastore.Key]. + * Converts a [Key] to a [ds.Key]. */ - datastore.Key toDatastoreKey(Key dbKey); + ds.Key toDatastoreKey(Key dbKey); /** - * Converts a [Model] instance to a [datastore.Entity]. + * Converts a [Model] instance to a [ds.Entity]. */ - datastore.Entity toDatastoreEntity(Model model); + ds.Entity toDatastoreEntity(Model model); /** - * Converts a [datastore.Entity] to a [Model] instance. + * Converts a [ds.Entity] to a [Model] instance. */ - Model fromDatastoreEntity(datastore.Entity entity); + Model fromDatastoreEntity(ds.Entity entity); /** * Returns the kind name for instances of [type]. diff --git a/lib/src/db/model_db_impl.dart b/lib/src/db/model_db_impl.dart index 124b3d69..d1a016d3 100644 --- a/lib/src/db/model_db_impl.dart +++ b/lib/src/db/model_db_impl.dart @@ -56,8 +56,8 @@ class ModelDBImpl implements ModelDB { _initialize([mirrors.currentMirrorSystem().findLibrary(librarySymbol)]); } - /// Converts a [datastore.Key] to a [Key]. - Key fromDatastoreKey(datastore.Key datastoreKey) { + /// Converts a [ds.Key] to a [Key]. + Key fromDatastoreKey(ds.Key datastoreKey) { var namespace = new Partition(datastoreKey.partition.namespace); Key key = namespace.emptyKey; for (var element in datastoreKey.elements) { @@ -73,9 +73,9 @@ class ModelDBImpl implements ModelDB { return key; } - /// Converts a [Key] to a [datastore.Key]. - datastore.Key toDatastoreKey(Key dbKey) { - List elements = []; + /// Converts a [Key] to a [ds.Key]. + ds.Key toDatastoreKey(Key dbKey) { + List elements = []; var currentKey = dbKey; while (!currentKey.isEmpty) { var id = currentKey.id; @@ -94,16 +94,16 @@ class ModelDBImpl implements ModelDB { 'id was of type ${id.runtimeType}'); } - elements.add(new datastore.KeyElement(kind, id)); + elements.add(new ds.KeyElement(kind, id)); currentKey = currentKey.parent; } Partition partition = currentKey._parent; - return new datastore.Key(elements.reversed.toList(), - partition: new datastore.Partition(partition.namespace)); + return new ds.Key(elements.reversed.toList(), + partition: new ds.Partition(partition.namespace)); } - /// Converts a [Model] instance to a [datastore.Entity]. - datastore.Entity toDatastoreEntity(Model model) { + /// Converts a [Model] instance to a [ds.Entity]. + ds.Entity toDatastoreEntity(Model model) { try { var modelDescription = _modelDescriptionForType(model.runtimeType); return modelDescription.encodeModel(this, model); @@ -112,8 +112,8 @@ class ModelDBImpl implements ModelDB { } } - /// Converts a [datastore.Entity] to a [Model] instance. - Model fromDatastoreEntity(datastore.Entity entity) { + /// Converts a [ds.Entity] to a [Model] instance. + Model fromDatastoreEntity(ds.Entity entity) { if (entity == null) return null; Key key = fromDatastoreKey(entity.key); @@ -383,17 +383,17 @@ class _ModelDescription { String kindName(ModelDBImpl db) => kind; - datastore.Entity encodeModel(ModelDBImpl db, T model) { + ds.Entity encodeModel(ModelDBImpl db, T model) { var key = db.toDatastoreKey(model.key); - var properties = {}; + var properties = {}; var mirror = mirrors.reflect(model); db._propertiesForModel(this).forEach((String fieldName, Property prop) { _encodeProperty(db, model, mirror, properties, fieldName, prop); }); - return new datastore.Entity(key, properties, + return new ds.Entity(key, properties, unIndexedProperties: _unIndexedProperties); } @@ -412,7 +412,7 @@ class _ModelDescription { properties[propertyName] = prop.encodeValue(db, value); } - Model decodeEntity(ModelDBImpl db, Key key, datastore.Entity entity) { + Model decodeEntity(ModelDBImpl db, Key key, ds.Entity entity) { if (entity == null) return null; // NOTE: this assumes a default constructor for the model classes! @@ -429,7 +429,7 @@ class _ModelDescription { return mirror.reflectee; } - _decodeProperty(ModelDBImpl db, datastore.Entity entity, + _decodeProperty(ModelDBImpl db, ds.Entity entity, mirrors.InstanceMirror mirror, String fieldName, Property prop) { String propertyName = fieldNameToPropertyName(fieldName); @@ -491,7 +491,7 @@ class _ExpandoModelDescription extends _ModelDescription { usedNames = new Set()..addAll(realFieldNames)..addAll(realPropertyNames); } - datastore.Entity encodeModel(ModelDBImpl db, ExpandoModel model) { + ds.Entity encodeModel(ModelDBImpl db, ExpandoModel model) { var entity = super.encodeModel(db, model); var properties = entity.properties; model.additionalProperties.forEach((String key, Object value) { @@ -503,7 +503,7 @@ class _ExpandoModelDescription extends _ModelDescription { return entity; } - Model decodeEntity(ModelDBImpl db, Key key, datastore.Entity entity) { + Model decodeEntity(ModelDBImpl db, Key key, ds.Entity entity) { if (entity == null) return null; ExpandoModel model = super.decodeEntity(db, key, entity); diff --git a/lib/src/db/models.dart b/lib/src/db/models.dart index 84546b93..b4672aa8 100644 --- a/lib/src/db/models.dart +++ b/lib/src/db/models.dart @@ -119,7 +119,6 @@ abstract class Model { * set arbitrary fields on these models. The expanded values must be values * accepted by the [RawDatastore] implementation. */ -@proxy abstract class ExpandoModel extends Model { final Map additionalProperties = {}; diff --git a/lib/src/pubsub_impl.dart b/lib/src/pubsub_impl.dart index 156f6992..1a34d39b 100644 --- a/lib/src/pubsub_impl.dart +++ b/lib/src/pubsub_impl.dart @@ -221,10 +221,10 @@ class _MessageImpl implements Message { : _stringMessage = null; List get asBytes => - _bytesMessage != null ? _bytesMessage : UTF8.encode(_stringMessage); + _bytesMessage != null ? _bytesMessage : utf8.encode(_stringMessage); String get asString => - _stringMessage != null ? _stringMessage : UTF8.decode(_bytesMessage); + _stringMessage != null ? _stringMessage : utf8.decode(_bytesMessage); } /// Message received using [Subscription.pull]. @@ -246,7 +246,7 @@ class _PullMessage implements Message { } String get asString { - if (_string == null) _string = UTF8.decode(_message.dataAsBytes); + if (_string == null) _string = utf8.decode(_message.dataAsBytes); return _string; } @@ -265,9 +265,9 @@ class _PushMessage implements Message { _PushMessage(this._base64Message, this.attributes); - List get asBytes => BASE64.decode(_base64Message); + List get asBytes => base64.decode(_base64Message); - String get asString => UTF8.decode(asBytes); + String get asString => utf8.decode(asBytes); } /// Pull event received from Pub/Sub pull delivery. @@ -309,14 +309,14 @@ class _PushEventImpl implements PushEvent { _PushEventImpl(this._message, this._subscriptionName); factory _PushEventImpl.fromJson(String json) { - Map body = JSON.decode(json); + Map body = jsonDecode(json); String data = body['message']['data']; - Map labels = new HashMap(); + Map labels = new HashMap(); body['message']['labels'].forEach((label) { var key = label['key']; var value = label['strValue']; if (value == null) value = label['numValue']; - labels[key] = value; + labels[key] = value.toString(); }); String subscription = body['subscription']; // TODO(#1): Remove this when the push event subscription name is prefixed @@ -353,7 +353,7 @@ class _TopicImpl implements Topic { Future delete() => _api._deleteTopic(_topic.name); Future publishString(String message, {Map attributes}) { - return _api._publish(_topic.name, UTF8.encode(message), attributes); + return _api._publish(_topic.name, utf8.encode(message), attributes); } Future publishBytes(List message, {Map attributes}) { diff --git a/lib/src/storage_impl.dart b/lib/src/storage_impl.dart index 395c84b5..90a17fe3 100644 --- a/lib/src/storage_impl.dart +++ b/lib/src/storage_impl.dart @@ -372,10 +372,10 @@ class _ObjectInfoImpl implements ObjectInfo { String get etag => _object.etag; - List get md5Hash => BASE64.decode(_object.md5Hash); + List get md5Hash => base64.decode(_object.md5Hash); int get crc32CChecksum { - var list = BASE64.decode(_object.crc32c); + var list = base64.decode(_object.crc32c); return (list[3] << 24) | (list[2] << 16) | (list[1] << 8) | list[0]; } @@ -452,7 +452,7 @@ class _ObjectMetadata implements ObjectMetadata { Map get custom { if (_object.metadata == null) return null; if (_cachedCustom == null) { - _cachedCustom = new UnmodifiableMapView(_object.metadata); + _cachedCustom = new UnmodifiableMapView(_object.metadata); } return _cachedCustom; } @@ -497,7 +497,7 @@ class _MediaUploadStreamSink implements StreamSink> { final _controller = new StreamController>(sync: true); StreamSubscription _subscription; StreamController _resumableController; - final _doneCompleter = new Completer(); + final _doneCompleter = new Completer(); static const int _STATE_LENGTH_KNOWN = 0; static const int _STATE_PROBING_LENGTH = 1; @@ -537,7 +537,7 @@ class _MediaUploadStreamSink implements StreamSink> { return _controller.addStream(stream); } - Future close() { + Future close() { _controller.close(); return _doneCompleter.future; } @@ -552,7 +552,7 @@ class _MediaUploadStreamSink implements StreamSink> { if (_bufferLength > _maxNormalUploadLength) { // Start resumable upload. // TODO: Avoid using another stream-controller. - _resumableController = new StreamController(sync: true); + _resumableController = new StreamController>(sync: true); buffer.forEach(_resumableController.add); _startResumableUpload(_resumableController.stream, _length); _state = _STATE_DECIDED_RESUMABLE; @@ -567,7 +567,8 @@ class _MediaUploadStreamSink implements StreamSink> { if (_state == _STATE_PROBING_LENGTH) { // As the data is already cached don't bother to wait on somebody // listening on the stream before adding the data. - _startNormalUpload(new Stream.fromIterable(buffer), _bufferLength); + _startNormalUpload( + new Stream>.fromIterable(buffer), _bufferLength); } else { _resumableController.close(); } @@ -591,7 +592,7 @@ class _MediaUploadStreamSink implements StreamSink> { _doneCompleter.completeError(e, s); } - void _startNormalUpload(Stream stream, int length) { + void _startNormalUpload(Stream> stream, int length) { var contentType = _object.contentType != null ? _object.contentType : 'application/octet-stream'; @@ -607,7 +608,7 @@ class _MediaUploadStreamSink implements StreamSink> { }, onError: _completeError); } - void _startResumableUpload(Stream stream, int length) { + void _startResumableUpload(Stream> stream, int length) { var contentType = _object.contentType != null ? _object.contentType : 'application/octet-stream'; diff --git a/pubspec.yaml b/pubspec.yaml index cff67b5c..9f4432bc 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,13 +1,13 @@ name: gcloud -version: 0.4.0+1 +version: 0.5.0 author: Dart Team description: Dart gcloud APIs homepage: https://github.com/dart-lang/gcloud environment: - sdk: '>=1.13.0 <2.0.0' + sdk: '>=2.0.0-dev.54.0 <2.0.0' dependencies: - googleapis: '>=0.50.0 <0.51.0' - googleapis_beta: '>=0.45.0 <0.46.0' + googleapis: '>=0.50.2 <1.0.0' + googleapis_beta: '>=0.45.2 <1.0.0' http: '>=0.11.0 <0.12.0' dev_dependencies: googleapis_auth: '>=0.2.3 <0.3.0' diff --git a/test/common.dart b/test/common.dart index d6003913..68de98fb 100644 --- a/test/common.dart +++ b/test/common.dart @@ -86,7 +86,7 @@ class MockClient extends http.BaseClient { Future respond(response) { return new Future.value(new http.Response( - JSON.encode(response.toJson()), 200, + jsonEncode(response.toJson()), 200, headers: RESPONSE_HEADERS)); } @@ -96,7 +96,7 @@ class MockClient extends http.BaseClient { } Future respondInitiateResumableUpload(project) { - Map headers = new Map.from(RESPONSE_HEADERS); + Map headers = new Map.from(RESPONSE_HEADERS); headers['location'] = 'https://www.googleapis.com/resumable/upload$rootPath' 'b/$project/o?uploadType=resumable&alt=json&' 'upload_id=AEnB2UqucpaWy7d5cr5iVQzmbQcQlLDIKiClrm0SAX3rJ7UN' @@ -113,7 +113,7 @@ class MockClient extends http.BaseClient { expect(request.url.queryParameters['alt'], 'media'); var myBytes = bytes; - var headers = new Map.from(RESPONSE_HEADERS); + var headers = new Map.from(RESPONSE_HEADERS); var range = request.headers['range']; if (range != null) { @@ -134,12 +134,12 @@ class MockClient extends http.BaseClient { var error = { 'error': {'code': statusCode, 'message': 'error'} }; - return new Future.value(new http.Response(JSON.encode(error), statusCode, + return new Future.value(new http.Response(jsonEncode(error), statusCode, headers: RESPONSE_HEADERS)); } - Future processNormalMediaUpload(http.Request request) { - var completer = new Completer(); + Future processNormalMediaUpload(http.Request request) { + var completer = new Completer(); var contentType = new http_parser.MediaType.parse(request.headers['content-type']); @@ -160,15 +160,15 @@ class MockClient extends http.BaseClient { // First part in the object JSON. expect(contentType, 'application/json; charset=utf-8'); mimeMultipart - .transform(UTF8.decoder) + .transform(utf8.decoder) .fold('', (p, e) => '$p$e') .then((j) => json = j); } else if (partCount == 2) { // Second part is the base64 encoded bytes. mimeMultipart - .transform(ASCII.decoder) + .transform(ascii.decoder) .fold('', (p, e) => '$p$e') - .then(BASE64.decode) + .then(base64.decode) .then((bytes) { completer.complete(new NormalMediaUpload(json, bytes, contentType)); }); @@ -200,14 +200,14 @@ class TraceClient extends http.BaseClient { print(request); return request.finalize().toBytes().then((body) { print('--- START REQUEST ---'); - print(UTF8.decode(body)); + print(utf8.decode(body)); print('--- END REQUEST ---'); var r = new RequestImpl(request.method, request.url, body); r.headers.addAll(request.headers); return client.send(r).then((http.StreamedResponse rr) { return rr.stream.toBytes().then((body) { print('--- START RESPONSE ---'); - print(UTF8.decode(body)); + print(utf8.decode(body)); print('--- END RESPONSE ---'); return new http.StreamedResponse( new http.ByteStream.fromBytes(body), rr.statusCode, diff --git a/test/common_e2e.dart b/test/common_e2e.dart index 612f4f1c..d0ba0f8f 100644 --- a/test/common_e2e.dart +++ b/test/common_e2e.dart @@ -51,7 +51,7 @@ Future serviceKeyJson(String serviceKeyLocation) { if (!serviceKeyLocation.startsWith('gs://')) { return new File(serviceKeyLocation).readAsString(); } - var future; + Future future; if (onBot()) { future = Process.run( 'python', ['third_party/gsutil/gsutil', 'cat', serviceKeyLocation], diff --git a/test/datastore/e2e/datastore_test_impl.dart b/test/datastore/e2e/datastore_test_impl.dart index 5606ea6f..1936d38a 100644 --- a/test/datastore/e2e/datastore_test_impl.dart +++ b/test/datastore/e2e/datastore_test_impl.dart @@ -45,13 +45,13 @@ Future sleep(Duration duration) { } Future> consumePages(FirstPageProvider provider) { - return new StreamFromPages(provider).stream.toList(); + return new StreamFromPages(provider).stream.toList(); } void runTests(Datastore datastore, String namespace) { Partition partition = new Partition(namespace); - Future withTransaction(Function f, {bool xg: false}) { + Future withTransaction(Function f, {bool xg: false}) { return datastore.beginTransaction(crossEntityGroup: xg).then(f); } @@ -258,7 +258,8 @@ void runTests(Datastore datastore, String namespace) { test('negative_insert_20000_entities', () async { // Maybe it should not be a [DataStoreError] here? // FIXME/TODO: This was adapted - expect(datastore.commit(inserts: named20000), throwsA(isSocketException)); + expect( + datastore.commit(inserts: named20000), throwsA(isSocketException)); }); // TODO: test invalid inserts (like entities without key, ...) @@ -542,7 +543,7 @@ void runTests(Datastore datastore, String namespace) { var changedEntities = new List(entities.length); for (int i = 0; i < entities.length; i++) { var entity = entities[i]; - var newProperties = new Map.from(entity.properties); + var newProperties = new Map.from(entity.properties); for (var prop in newProperties.keys) { newProperties[prop] = "${newProperties[prop]}conflict$value"; } @@ -762,7 +763,7 @@ void runTests(Datastore datastore, String namespace) { var orders = [new Order(OrderDirection.Decending, QUERY_KEY)]; test('query', () { - return insert(stringNamedEntities, []).then((keys) { + return insert(stringNamedEntities, []).then((keys) { return waitUntilEntitiesReady(datastore, stringNamedKeys, partition) .then((_) { var tests = [ @@ -1072,9 +1073,9 @@ Future waitUntilEntitiesGone(Datastore db, List keys, Partition p) { Future waitUntilEntitiesHelper( Datastore db, List keys, bool positive, Partition p) { - var keysByKind = {}; + var keysByKind = >{}; for (var key in keys) { - keysByKind.putIfAbsent(key.elements.last.kind, () => []).add(key); + keysByKind.putIfAbsent(key.elements.last.kind, () => []).add(key); } Future waitForKeys(String kind, List keys) { diff --git a/test/datastore/e2e/utils.dart b/test/datastore/e2e/utils.dart index 101fc740..bc7d4239 100644 --- a/test/datastore/e2e/utils.dart +++ b/test/datastore/e2e/utils.dart @@ -40,7 +40,7 @@ Map buildProperties(int i) { List buildKeys(int from, int to, {Function idFunction, String kind: TEST_KIND, Partition partition}) { - var keys = []; + var keys = []; for (var i = from; i < to; i++) { keys.add(buildKey(i, idFunction: idFunction, kind: kind, p: partition)); } @@ -49,7 +49,7 @@ List buildKeys(int from, int to, List buildEntities(int from, int to, {Function idFunction, String kind: TEST_KIND, Partition partition}) { - var entities = []; + var entities = []; var unIndexedProperties = new Set(); for (var i = from; i < to; i++) { var key = buildKey(i, idFunction: idFunction, kind: kind, p: partition); @@ -87,7 +87,7 @@ List buildEntityWithAllProperties(int from, int to, }; } - var entities = []; + var entities = []; for (var i = from; i < to; i++) { var key = buildKey(i, idFunction: (i) => 'allprop$i', kind: kind, p: partition); diff --git a/test/datastore/error_matchers.dart b/test/datastore/error_matchers.dart index be1496f0..9d0f7b1d 100644 --- a/test/datastore/error_matchers.dart +++ b/test/datastore/error_matchers.dart @@ -53,4 +53,4 @@ const isTimeoutError = const _TimeoutError(); const isInt = const _IntMatcher(); -const isSocketException = const _SocketException(); \ No newline at end of file +const isSocketException = const _SocketException(); diff --git a/test/db/e2e/db_test_impl.dart b/test/db/e2e/db_test_impl.dart index f31cde8b..4ec961cf 100644 --- a/test/db/e2e/db_test_impl.dart +++ b/test/db/e2e/db_test_impl.dart @@ -215,7 +215,7 @@ void runTests(db.DatastoreDB store, String namespace) { group('insert_lookup_delete', () { test('persons', () { var root = partition.emptyKey; - var persons = []; + var persons = []; for (var i = 1; i <= 10; i++) { persons.add(new Person() ..id = i @@ -228,7 +228,7 @@ void runTests(db.DatastoreDB store, String namespace) { }); test('users', () { var root = partition.emptyKey; - var users = []; + var users = []; for (var i = 1; i <= 10; i++) { users.add(new User() ..id = i @@ -241,9 +241,9 @@ void runTests(db.DatastoreDB store, String namespace) { }); test('expando_insert', () { var root = partition.emptyKey; - var expandoPersons = []; + var expandoPersons = []; for (var i = 1; i <= 10; i++) { - var expandoPerson = new ExpandoPerson() + dynamic expandoPerson = new ExpandoPerson() ..parentKey = root ..id = i ..name = 'user$i'; @@ -257,7 +257,7 @@ void runTests(db.DatastoreDB store, String namespace) { }); test('transactional_insert', () { var root = partition.emptyKey; - var models = []; + var models = []; models.add(new Person() ..id = 1 @@ -270,7 +270,7 @@ void runTests(db.DatastoreDB store, String namespace) { ..age = 2 ..name = 'user2' ..nickname = 'nickname2'); - var expandoPerson = new ExpandoPerson() + dynamic expandoPerson = new ExpandoPerson() ..parentKey = root ..id = 3 ..name = 'user1'; @@ -384,7 +384,7 @@ void runTests(db.DatastoreDB store, String namespace) { var root = partition.emptyKey; var users = []; for (var i = 1; i <= 10; i++) { - var languages = []; + var languages = []; if (i == 9) { languages = ['foo']; } else if (i == 10) { @@ -402,7 +402,7 @@ void runTests(db.DatastoreDB store, String namespace) { var expandoPersons = []; for (var i = 1; i <= 3; i++) { - var expandoPerson = new ExpandoPerson() + dynamic expandoPerson = new ExpandoPerson() ..parentKey = root ..id = i ..name = 'user$i' @@ -572,7 +572,7 @@ void runTests(db.DatastoreDB store, String namespace) { // Expando queries: Filter on expanded String property () async { var query = store.query(ExpandoPerson, partition: partition) - ..filter('foo =', expandoPersons.last.foo) + ..filter('foo =', (expandoPersons.last as dynamic).foo) ..run(); var models = await runQueryWithExponentialBackoff(query, 1); compareModels([expandoPersons.last], models); @@ -580,7 +580,7 @@ void runTests(db.DatastoreDB store, String namespace) { // Expando queries: Filter on expanded int property () async { var query = store.query(ExpandoPerson, partition: partition) - ..filter('bar =', expandoPersons.last.bar) + ..filter('bar =', (expandoPersons.last as dynamic).bar) ..run(); var models = await runQueryWithExponentialBackoff(query, 1); compareModels([expandoPersons.last], models); @@ -651,7 +651,7 @@ Future waitUntilEntitiesHelper(db.DatastoreDB mdb, List keys, bool positive, db.Partition partition) { var keysByKind = {}; for (var key in keys) { - keysByKind.putIfAbsent(key.type, () => []).add(key); + keysByKind.putIfAbsent(key.type, () => []).add(key); } Future waitForKeys(Type kind, List keys) { diff --git a/test/db/properties_test.dart b/test/db/properties_test.dart index 30ae3d0d..345db687 100644 --- a/test/db/properties_test.dart +++ b/test/db/properties_test.dart @@ -75,7 +75,7 @@ main() { expect(prop.validate(null, null), isTrue); expect(prop.validate(null, [1, 2]), isTrue); expect(prop.encodeValue(null, null), equals(null)); - expect((prop.encodeValue(null, []) as datastore.BlobValue).bytes, + expect((prop.encodeValue(null, []) as datastore.BlobValue).bytes, equals([])); expect((prop.encodeValue(null, [1, 2]) as datastore.BlobValue).bytes, equals([1, 2])); diff --git a/test/pubsub/pubsub_test.dart b/test/pubsub/pubsub_test.dart index 86889c6e..01bf96f9 100644 --- a/test/pubsub/pubsub_test.dart +++ b/test/pubsub/pubsub_test.dart @@ -50,7 +50,7 @@ main() { 'projects/$PROJECT/topics/test-topic', expectAsync1((request) { var requestTopic = - new pubsub.Topic.fromJson(JSON.decode(request.body)); + new pubsub.Topic.fromJson(jsonDecode(request.body)); expect(requestTopic.name, absoluteName); return mock.respond(new pubsub.Topic()..name = absoluteName); }, count: 2)); @@ -152,7 +152,7 @@ main() { // Mock that expect/generates [n] topics in pages of page size // [pageSize]. - registerQueryMock(mock, n, pageSize, [totalCalls]) { + registerQueryMock(MockClient mock, n, pageSize, [totalCalls]) { var totalPages = (n + pageSize - 1) ~/ pageSize; // No items still generate one request. if (totalPages == 0) totalPages = 1; @@ -428,7 +428,7 @@ main() { 'projects/$PROJECT/subscriptions', expectAsync1((request) { var requestSubscription = - new pubsub.Subscription.fromJson(JSON.decode(request.body)); + new pubsub.Subscription.fromJson(jsonDecode(request.body)); expect(requestSubscription.name, absoluteName); return mock .respond(new pubsub.Subscription()..name = absoluteName); @@ -543,7 +543,8 @@ main() { // Mock that expect/generates [n] subscriptions in pages of page size // [pageSize]. - registerQueryMock(mock, n, pageSize, {String topic, int totalCalls}) { + registerQueryMock(MockClient mock, n, pageSize, + {String topic, int totalCalls}) { var totalPages = (n + pageSize - 1) ~/ pageSize; // No items still generate one request. if (totalPages == 0) totalPages = 1; @@ -854,24 +855,24 @@ main() { var name = 'test-topic'; var absoluteName = 'projects/$PROJECT/topics/test-topic'; var message = 'Hello, world!'; - var messageBytes = UTF8.encode(message); - var messageBase64 = BASE64.encode(messageBytes); + var messageBytes = utf8.encode(message); + var messageBase64 = base64.encode(messageBytes); var attributes = {'a': '1', 'b': 'text'}; - registerLookup(mock) { + registerLookup(MockClient mock) { mock.register('GET', absoluteName, expectAsync1((request) { expect(request.body.length, 0); return mock.respond(new pubsub.Topic()..name = absoluteName); })); } - registerPublish(mock, count, fn) { + registerPublish(MockClient mock, count, fn) { mock.register( 'POST', 'projects/test-project/topics/test-topic:publish', expectAsync1((request) { var publishRequest = - new pubsub.PublishRequest.fromJson(JSON.decode(request.body)); + new pubsub.PublishRequest.fromJson(jsonDecode(request.body)); return fn(publishRequest); }, count: count)); } @@ -1053,7 +1054,7 @@ main() { '''; var event = new PushEvent.fromJson(requestBody); expect(event.message.asString, "Hello, world 30 of 50!"); - expect(event.message.attributes['messageNo'], 30); + expect(event.message.attributes['messageNo'], '30'); expect(event.message.attributes['test'], 'hello'); expect(event.subscriptionName, absoluteSubscriptionName); }); diff --git a/test/storage/storage_test.dart b/test/storage/storage_test.dart index 1a410d8d..e53e2531 100644 --- a/test/storage/storage_test.dart +++ b/test/storage/storage_test.dart @@ -39,9 +39,9 @@ main() { test('create', () { withMockClient((mock, api) { - mock.register('POST', 'b', expectAsync1((request) { + mock.register('POST', 'b', expectAsync1((http.Request request) { var requestBucket = - new storage.Bucket.fromJson(JSON.decode(request.body)); + new storage.Bucket.fromJson(jsonDecode(request.body)); expect(requestBucket.name, bucketName); return mock.respond(new storage.Bucket()..name = bucketName); })); @@ -65,9 +65,9 @@ main() { mock.register( 'POST', 'b', - expectAsync1((request) { + expectAsync1((http.Request request) { var requestBucket = - new storage.Bucket.fromJson(JSON.decode(request.body)); + new storage.Bucket.fromJson(jsonDecode(request.body)); expect(requestBucket.name, bucketName); expect(requestBucket.acl, isNull); expect(request.url.queryParameters['predefinedAcl'], @@ -109,9 +109,9 @@ main() { mock.register( 'POST', 'b', - expectAsync1((request) { + expectAsync1((http.Request request) { var requestBucket = - new storage.Bucket.fromJson(JSON.decode(request.body)); + new storage.Bucket.fromJson(jsonDecode(request.body)); expect(requestBucket.name, bucketName); expect(request.url.queryParameters['predefinedAcl'], isNull); expect(requestBucket.acl, isNotNull); @@ -171,9 +171,9 @@ main() { mock.register( 'POST', 'b', - expectAsync1((request) { + expectAsync1((http.Request request) { var requestBucket = - new storage.Bucket.fromJson(JSON.decode(request.body)); + new storage.Bucket.fromJson(jsonDecode(request.body)); int predefinedIndex = count ~/ acls.length; int aclIndex = count % acls.length; expect(requestBucket.name, bucketName); @@ -333,16 +333,19 @@ main() { bool testArgumentError(e) => e is ArgumentError; bool testDetailedApiError(e) => e is storage.DetailedApiRequestError; - Function expectNotNull(status) => (o) => expect(o, isNotNull); + final expectNotNull = (o) async { + expect(o, isNotNull); + return null; + }; - expectNormalUpload(mock, data, objectName) { + expectNormalUpload(MockClient mock, data, objectName) { var bytes = data.fold([], (p, e) => p..addAll(e)); mock.registerUpload('POST', 'b/$bucketName/o', expectAsync1((request) { return mock .processNormalMediaUpload(request) .then(expectAsync1((mediaUpload) { var object = - new storage.Object.fromJson(JSON.decode(mediaUpload.json)); + new storage.Object.fromJson(jsonDecode(mediaUpload.json)); expect(object.name, objectName); expect(mediaUpload.bytes, bytes); expect(mediaUpload.contentType, 'application/octet-stream'); @@ -351,14 +354,14 @@ main() { })); } - expectResumableUpload(mock, data, objectName) { + expectResumableUpload(MockClient mock, data, objectName) { var bytes = data.fold([], (p, e) => p..addAll(e)); expect(bytes.length, bytesResumableUpload.length); int count = 0; mock.registerResumableUpload('POST', 'b/$bucketName/o', expectAsync1((request) { var requestObject = - new storage.Object.fromJson(JSON.decode(request.body)); + new storage.Object.fromJson(jsonDecode(request.body)); expect(requestObject.name, objectName); return mock.respondInitiateResumableUpload(PROJECT); })); @@ -457,7 +460,7 @@ main() { }); test('write-short-error', () { - withMockClient((mock, api) { + withMockClient((MockClient mock, api) { Future test(length) { mock.clear(); mock.registerUpload('POST', 'b/$bucketName/o', @@ -537,7 +540,7 @@ main() { sink.done.then((_) => throw 'Unexpected').catchError( expectAsync1(expectNotNull), test: (e) => e is String || e is storage.ApiRequestError); - return new Stream.fromIterable(data) + return new Stream>.fromIterable(data) .pipe(sink) .then((_) => throw 'Unexpected') .catchError(expectAsync1(expectNotNull), @@ -629,7 +632,7 @@ main() { .processNormalMediaUpload(request) .then(expectAsync1((mediaUpload) { var object = - new storage.Object.fromJson(JSON.decode(mediaUpload.json)); + new storage.Object.fromJson(jsonDecode(mediaUpload.json)); ObjectMetadata m = metadata[count]; expect(object.name, objectName); expect(mediaUpload.bytes, bytes); @@ -682,7 +685,7 @@ main() { 'b/$bucketName/o', expectAsync1((request) { var object = - new storage.Object.fromJson(JSON.decode(request.body)); + new storage.Object.fromJson(jsonDecode(request.body)); ObjectMetadata m = metadata[countInitial]; expect(object.name, objectName); expect(object.cacheControl, m.cacheControl); @@ -745,7 +748,7 @@ main() { .processNormalMediaUpload(request) .then(expectAsync1((mediaUpload) { var object = - new storage.Object.fromJson(JSON.decode(mediaUpload.json)); + new storage.Object.fromJson(jsonDecode(mediaUpload.json)); expect(object.name, objectName); expect(mediaUpload.bytes, bytes); expect(mediaUpload.contentType, 'application/octet-stream'); @@ -797,7 +800,7 @@ main() { .processNormalMediaUpload(request) .then(expectAsync1((mediaUpload) { var object = - new storage.Object.fromJson(JSON.decode(mediaUpload.json)); + new storage.Object.fromJson(jsonDecode(mediaUpload.json)); expect(object.name, objectName); expect(mediaUpload.bytes, bytes); expect(mediaUpload.contentType, 'application/octet-stream'); @@ -870,7 +873,7 @@ main() { int predefinedIndex = count ~/ acls.length; int aclIndex = count % acls.length; var object = - new storage.Object.fromJson(JSON.decode(mediaUpload.json)); + new storage.Object.fromJson(jsonDecode(mediaUpload.json)); expect(object.name, objectName); expect(mediaUpload.bytes, bytes); expect(mediaUpload.contentType, 'application/octet-stream');