From 6d35481cfa43d7f0f4756dd30489d562f90d3b17 Mon Sep 17 00:00:00 2001 From: Yegor Jbanov Date: Sun, 28 Feb 2016 23:47:30 -0800 Subject: [PATCH] add smoke driver test; find by tooltip; retry predicate --- packages/flutter_driver/lib/src/driver.dart | 13 ++- .../flutter_driver/lib/src/enum_util.dart | 3 +- packages/flutter_driver/lib/src/error.dart | 8 +- .../flutter_driver/lib/src/extension.dart | 107 +++++++++++++----- packages/flutter_driver/lib/src/find.dart | 91 +++++++++++++-- packages/flutter_driver/lib/src/retry.dart | 21 +++- .../test/flutter_driver_test.dart | 5 +- packages/flutter_driver/test/retry_test.dart | 20 ++++ .../lib/src/commands/analyze.dart | 48 +++++--- .../flutter_tools/lib/src/commands/drive.dart | 2 +- .../templates/create/lib/main.dart.tmpl | 8 ++ .../templates/driver/e2e.dart.tmpl | 9 -- ...e2e_test.dart.tmpl => main_test.dart.tmpl} | 16 +-- 13 files changed, 265 insertions(+), 86 deletions(-) delete mode 100644 packages/flutter_tools/templates/driver/e2e.dart.tmpl rename packages/flutter_tools/templates/driver/{e2e_test.dart.tmpl => main_test.dart.tmpl} (68%) diff --git a/packages/flutter_driver/lib/src/driver.dart b/packages/flutter_driver/lib/src/driver.dart index 113f44dc04..889a47e41b 100644 --- a/packages/flutter_driver/lib/src/driver.dart +++ b/packages/flutter_driver/lib/src/driver.dart @@ -151,8 +151,19 @@ class FlutterDriver { return Health.fromJson(await _sendCommand(new GetHealth())); } + /// Finds the UI element with the given [key]. Future findByValueKey(dynamic key) async { - return ObjectRef.fromJson(await _sendCommand(new FindByValueKey(key))); + return ObjectRef.fromJson(await _sendCommand(new Find(new ByValueKey(key)))); + } + + /// Finds the UI element for the tooltip with the given [message]. + Future findByTooltipMessage(String message) async { + return ObjectRef.fromJson(await _sendCommand(new Find(new ByTooltipMessage(message)))); + } + + /// Finds the text element with the given [text]. + Future findByText(String text) async { + return ObjectRef.fromJson(await _sendCommand(new Find(new ByText(text)))); } Future tap(ObjectRef ref) async { diff --git a/packages/flutter_driver/lib/src/enum_util.dart b/packages/flutter_driver/lib/src/enum_util.dart index ab778d566a..9b7a0f4d11 100644 --- a/packages/flutter_driver/lib/src/enum_util.dart +++ b/packages/flutter_driver/lib/src/enum_util.dart @@ -6,7 +6,8 @@ /// /// In Dart enum names are prefixed with enum class name. For example, for /// `enum Vote { yea, nay }`, `Vote.yea.toString()` produces `"Vote.yea"` -/// rather than just `"yea"` - the simple name. +/// rather than just `"yea"` - the simple name. This class provides methods for +/// getting and looking up by simple names. /// /// Example: /// diff --git a/packages/flutter_driver/lib/src/error.dart b/packages/flutter_driver/lib/src/error.dart index 36ba7484b4..ebb4be356f 100644 --- a/packages/flutter_driver/lib/src/error.dart +++ b/packages/flutter_driver/lib/src/error.dart @@ -15,7 +15,13 @@ class DriverError extends Error { final dynamic originalError; final dynamic originalStackTrace; - String toString() => 'DriverError: $message'; + String toString() { + return '''DriverError: $message +Original error: $originalError +Original stack trace: +$originalStackTrace + '''; + } } // Whether someone redirected the log messages somewhere. diff --git a/packages/flutter_driver/lib/src/extension.dart b/packages/flutter_driver/lib/src/extension.dart index 8a2e8a9896..cc5ff6ddf4 100644 --- a/packages/flutter_driver/lib/src/extension.dart +++ b/packages/flutter_driver/lib/src/extension.dart @@ -5,6 +5,7 @@ import 'dart:async'; import 'dart:convert'; import 'dart:developer'; +import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/src/instrumentation.dart'; @@ -50,14 +51,14 @@ class FlutterDriverExtension { FlutterDriverExtension() { _commandHandlers = { 'get_health': getHealth, - 'find_by_value_key': findByValueKey, + 'find': find, 'tap': tap, 'get_text': getText, }; _commandDeserializers = { 'get_health': GetHealth.fromJson, - 'find_by_value_key': FindByValueKey.fromJson, + 'find': Find.fromJson, 'tap': Tap.fromJson, 'get_text': GetText.fromJson, }; @@ -72,41 +73,95 @@ class FlutterDriverExtension { {}; Future call(Map params) async { - String commandKind = params['kind']; - CommandHandlerCallback commandHandler = _commandHandlers[commandKind]; - CommandDeserializerCallback commandDeserializer = - _commandDeserializers[commandKind]; + try { + String commandKind = params['kind']; + CommandHandlerCallback commandHandler = _commandHandlers[commandKind]; + CommandDeserializerCallback commandDeserializer = + _commandDeserializers[commandKind]; - if (commandHandler == null || commandDeserializer == null) { - return new ServiceExtensionResponse.error( - ServiceExtensionResponse.kInvalidParams, - 'Extension $_extensionMethod does not support command $commandKind' - ); + if (commandHandler == null || commandDeserializer == null) { + return new ServiceExtensionResponse.error( + ServiceExtensionResponse.kInvalidParams, + 'Extension $_extensionMethod does not support command $commandKind' + ); + } + + Command command = commandDeserializer(params); + return commandHandler(command).then((Result result) { + return new ServiceExtensionResponse.result(JSON.encode(result.toJson())); + }, onError: (e, s) { + _log.warning('$e:\n$s'); + return new ServiceExtensionResponse.error( + ServiceExtensionResponse.kExtensionError, '$e'); + }); + } catch(error, stackTrace) { + _log.warning('Uncaught extension error: $error\n$stackTrace'); } - - Command command = commandDeserializer(params); - return commandHandler(command).then((Result result) { - return new ServiceExtensionResponse.result(JSON.encode(result.toJson())); - }, onError: (e, s) { - _log.warning('$e:\n$s'); - return new ServiceExtensionResponse.error( - ServiceExtensionResponse.kExtensionError, '$e'); - }); } Future getHealth(GetHealth command) async => new Health(HealthStatus.ok); - Future findByValueKey(FindByValueKey command) async { - Element elem = await retry(() { - return prober.findElementByKey(new ValueKey(command.keyValue)); - }, _kDefaultTimeout, _kDefaultPauseBetweenRetries); + Future find(Find command) async { + SearchSpecification searchSpec = command.searchSpec; + switch(searchSpec.runtimeType) { + case ByValueKey: return findByValueKey(searchSpec); + case ByTooltipMessage: return findByTooltipMessage(searchSpec); + case ByText: return findByText(searchSpec); + } + throw new DriverError('Unsupported search specification type ${searchSpec.runtimeType}'); + } - ObjectRef elemRef = elem != null - ? new ObjectRef(_registerObject(elem)) + /// Runs object [locator] repeatedly until it returns a non-`null` value. + /// + /// [descriptionGetter] describes the object to be waited for. It is used in + /// the warning printed should timeout happen. + Future _waitForObject(String descriptionGetter(), Object locator()) async { + Object object = await retry(locator, _kDefaultTimeout, _kDefaultPauseBetweenRetries, predicate: (object) { + return object != null; + }).catchError((dynamic error, stackTrace) { + _log.warning('Timed out waiting for ${descriptionGetter()}'); + return null; + }); + + ObjectRef elemRef = object != null + ? new ObjectRef(_registerObject(object)) : new ObjectRef.notFound(); return new Future.value(elemRef); } + Future findByValueKey(ByValueKey byKey) async { + return _waitForObject( + () => 'element with key "${byKey.keyValue}" of type ${byKey.keyValueType}', + () { + return prober.findElementByKey(new ValueKey(byKey.keyValue)); + } + ); + } + + Future findByTooltipMessage(ByTooltipMessage byTooltipMessage) async { + return _waitForObject( + () => 'tooltip with message "${byTooltipMessage.text}" on it', + () { + return prober.findElement((Element element) { + Widget widget = element.widget; + + if (widget is Tooltip) + return widget.message == byTooltipMessage.text; + + return false; + }); + } + ); + } + + Future findByText(ByText byText) async { + return await _waitForObject( + () => 'text "${byText.text}"', + () { + return prober.findText(byText.text); + }); + } + Future tap(Tap command) async { Element target = await _dereferenceOrDie(command.targetRef); prober.tap(target); diff --git a/packages/flutter_driver/lib/src/find.dart b/packages/flutter_driver/lib/src/find.dart index 00e4aebe85..1e78815640 100644 --- a/packages/flutter_driver/lib/src/find.dart +++ b/packages/flutter_driver/lib/src/find.dart @@ -7,11 +7,84 @@ import 'message.dart'; const List _supportedKeyValueTypes = const [String, int]; -/// Command to find an element by a value key. -class FindByValueKey extends Command { - final String kind = 'find_by_value_key'; +/// Command to find an element. +class Find extends Command { + final String kind = 'find'; - FindByValueKey(dynamic keyValue) + Find(this.searchSpec); + + final SearchSpecification searchSpec; + + Map toJson() => searchSpec.toJson(); + + static Find fromJson(Map json) { + return new Find(SearchSpecification.fromJson(json)); + } + + static _throwInvalidKeyValueType(String invalidType) { + throw new DriverError('Unsupported key value type $invalidType. Flutter Driver only supports ${_supportedKeyValueTypes.join(", ")}'); + } +} + +/// Describes how to the driver should search for elements. +abstract class SearchSpecification extends Message { + String get searchSpecType; + + static SearchSpecification fromJson(Map json) { + String searchSpecType = json['searchSpecType']; + switch(searchSpecType) { + case 'ByValueKey': return ByValueKey.fromJson(json); + case 'ByTooltipMessage': return ByTooltipMessage.fromJson(json); + case 'ByText': return ByText.fromJson(json); + } + throw new DriverError('Unsupported search specification type $searchSpecType'); + } + + Map toJson() => { + 'searchSpecType': searchSpecType, + }; +} + +/// Tells [Find] to search by tooltip text. +class ByTooltipMessage extends SearchSpecification { + final String searchSpecType = 'ByTooltipMessage'; + + ByTooltipMessage(this.text); + + /// Tooltip message text. + final String text; + + Map toJson() => super.toJson()..addAll({ + 'text': text, + }); + + static ByTooltipMessage fromJson(Map json) { + return new ByTooltipMessage(json['text']); + } +} + +/// Tells [Find] to search for `Text` widget by text. +class ByText extends SearchSpecification { + final String searchSpecType = 'ByText'; + + ByText(this.text); + + final String text; + + Map toJson() => super.toJson()..addAll({ + 'text': text, + }); + + static ByText fromJson(Map json) { + return new ByText(json['text']); + } +} + +/// Tells [Find] to search by `ValueKey`. +class ByValueKey extends SearchSpecification { + final String searchSpecType = 'ByValueKey'; + + ByValueKey(dynamic keyValue) : this.keyValue = keyValue, this.keyValueString = '$keyValue', this.keyValueType = '${keyValue.runtimeType}' { @@ -30,19 +103,19 @@ class FindByValueKey extends Command { /// May be one of "String", "int". The list of supported types may change. final String keyValueType; - Map toJson() => { + Map toJson() => super.toJson()..addAll({ 'keyValueString': keyValueString, 'keyValueType': keyValueType, - }; + }); - static FindByValueKey fromJson(Map json) { + static ByValueKey fromJson(Map json) { String keyValueString = json['keyValueString']; String keyValueType = json['keyValueType']; switch(keyValueType) { case 'int': - return new FindByValueKey(int.parse(keyValueString)); + return new ByValueKey(int.parse(keyValueString)); case 'String': - return new FindByValueKey(keyValueString); + return new ByValueKey(keyValueString); default: return _throwInvalidKeyValueType(keyValueType); } diff --git a/packages/flutter_driver/lib/src/retry.dart b/packages/flutter_driver/lib/src/retry.dart index 695757b7cc..b9cb900db7 100644 --- a/packages/flutter_driver/lib/src/retry.dart +++ b/packages/flutter_driver/lib/src/retry.dart @@ -8,13 +8,17 @@ import 'dart:async'; /// that evaluates to the result. typedef dynamic Action(); +/// Determines if [value] is acceptable. For good style an implementation should +/// be idempotent. +typedef bool Predicate(dynamic value); + /// Performs [action] repeatedly until it either succeeds or [timeout] limit is /// reached. /// /// When the retry time out, the last seen error and stack trace are returned in /// an error [Future]. Future retry(Action action, Duration timeout, - Duration pauseBetweenRetries) async { + Duration pauseBetweenRetries, { Predicate predicate }) async { assert(action != null); assert(timeout != null); assert(pauseBetweenRetries != null); @@ -28,20 +32,25 @@ Future retry(Action action, Duration timeout, while(!success && sw.elapsed < timeout) { try { result = await action(); - success = true; + if (predicate == null || predicate(result)) + success = true; + lastError = null; + lastStackTrace = null; } catch(error, stackTrace) { lastError = error; lastStackTrace = stackTrace; - if (sw.elapsed < timeout) { - await new Future.delayed(pauseBetweenRetries); - } } + + if (!success && sw.elapsed < timeout) + await new Future.delayed(pauseBetweenRetries); } if (success) return result; - else + else if (lastError != null) return new Future.error(lastError, lastStackTrace); + else + return new Future.error('Retry timed out'); } /// A function that produces a [Stopwatch]. diff --git a/packages/flutter_driver/test/flutter_driver_test.dart b/packages/flutter_driver/test/flutter_driver_test.dart index ec4f076d1f..0c363efbff 100644 --- a/packages/flutter_driver/test/flutter_driver_test.dart +++ b/packages/flutter_driver/test/flutter_driver_test.dart @@ -122,9 +122,10 @@ main() { test('finds by ValueKey', () async { when(mockIsolate.invokeExtension(any, any)).thenAnswer((Invocation i) { expect(i.positionalArguments[1], { - 'kind': 'find_by_value_key', + 'kind': 'find', + 'searchSpecType': 'ByValueKey', 'keyValueString': 'foo', - 'keyValueType': 'String', + 'keyValueType': 'String' }); return new Future.value({ 'objectReferenceKey': '123', diff --git a/packages/flutter_driver/test/retry_test.dart b/packages/flutter_driver/test/retry_test.dart index edb5fdc347..d1e6f40536 100644 --- a/packages/flutter_driver/test/retry_test.dart +++ b/packages/flutter_driver/test/retry_test.dart @@ -51,6 +51,26 @@ main() { }); }); + test('obeys predicates', () { + fakeAsync.run((_) { + int retryCount = 0; + + expect( + // The predicate requires that the returned value is 2, so we expect + // that `retry` keeps trying until the counter reaches 2. + retry( + () async => retryCount++, + new Duration(milliseconds: 30), + new Duration(milliseconds: 10), + predicate: (value) => value == 2 + ), + completion(2) + ); + + fakeAsync.elapse(new Duration(milliseconds: 50)); + }); + }); + test('times out returning last error', () async { fakeAsync.run((_) { bool timedOut = false; diff --git a/packages/flutter_tools/lib/src/commands/analyze.dart b/packages/flutter_tools/lib/src/commands/analyze.dart index 489364bfcd..b334b3a4d8 100644 --- a/packages/flutter_tools/lib/src/commands/analyze.dart +++ b/packages/flutter_tools/lib/src/commands/analyze.dart @@ -55,6 +55,20 @@ bool _addPackage(String directoryPath, List dartFiles, Set pubSp } } + Directory testDriverDirectory = new Directory(path.join(directoryPath, 'test_driver')); + if (testDriverDirectory.existsSync()) { + for (FileSystemEntity entry in testDriverDirectory.listSync()) { + if (entry is Directory) { + for (FileSystemEntity subentry in entry.listSync()) { + if (isDartTestFile(subentry)) + dartFiles.add(subentry.path); + } + } else if (isDartTestFile(entry)) { + dartFiles.add(entry.path); + } + } + } + Directory benchmarkDirectory = new Directory(path.join(directoryPath, 'benchmark')); if (benchmarkDirectory.existsSync()) { for (FileSystemEntity entry in benchmarkDirectory.listSync()) { @@ -76,6 +90,18 @@ bool _addPackage(String directoryPath, List dartFiles, Set pubSp return false; } +/// Adds all packages in [subPath], assuming a flat directory structure, i.e. +/// each direct child of [subPath] is a plain Dart package. +void _addFlatPackageList(String subPath, List dartFiles, Set pubSpecDirectories) { + Directory subdirectory = new Directory(path.join(ArtifactStore.flutterRoot, subPath)); + if (subdirectory.existsSync()) { + for (FileSystemEntity entry in subdirectory.listSync()) { + if (entry is Directory) + _addPackage(entry.path, dartFiles, pubSpecDirectories); + } + } +} + class FileChanged { } class AnalyzeCommand extends FlutterCommand { @@ -146,24 +172,11 @@ class AnalyzeCommand extends FlutterCommand { //dev/manual_tests/*/ as package //dev/manual_tests/*/ as files + _addFlatPackageList('packages', dartFiles, pubSpecDirectories); + _addFlatPackageList('examples', dartFiles, pubSpecDirectories); + Directory subdirectory; - subdirectory = new Directory(path.join(ArtifactStore.flutterRoot, 'packages')); - if (subdirectory.existsSync()) { - for (FileSystemEntity entry in subdirectory.listSync()) { - if (entry is Directory) - _addPackage(entry.path, dartFiles, pubSpecDirectories); - } - } - - subdirectory = new Directory(path.join(ArtifactStore.flutterRoot, 'examples')); - if (subdirectory.existsSync()) { - for (FileSystemEntity entry in subdirectory.listSync()) { - if (entry is Directory) - _addPackage(entry.path, dartFiles, pubSpecDirectories); - } - } - subdirectory = new Directory(path.join(ArtifactStore.flutterRoot, 'examples', 'layers')); if (subdirectory.existsSync()) { bool foundOne = false; @@ -198,7 +211,7 @@ class AnalyzeCommand extends FlutterCommand { } - dartFiles = dartFiles.map((String directory) => path.normalize(path.absolute(directory))).toSet().toList(); + dartFiles = dartFiles.map((String directory) => path.normalize(path.absolute(directory))).toSet().toList(); dartFiles.sort(); // prepare a Dart file that references all the above Dart files @@ -444,4 +457,3 @@ linter: return 0; } } - diff --git a/packages/flutter_tools/lib/src/commands/drive.dart b/packages/flutter_tools/lib/src/commands/drive.dart index 7a951f4946..c99959784d 100644 --- a/packages/flutter_tools/lib/src/commands/drive.dart +++ b/packages/flutter_tools/lib/src/commands/drive.dart @@ -118,7 +118,7 @@ class DriveCommand extends RunCommandBase { await appStopper(this); } catch(error, stackTrace) { // TODO(yjbanov): remove this guard when this bug is fixed: https://github.com/dart-lang/sdk/issues/25862 - printStatus('Could not stop application: $error\n$stackTrace'); + printTrace('Could not stop application: $error\n$stackTrace'); } } else { printStatus('Leaving the application running.'); diff --git a/packages/flutter_tools/templates/create/lib/main.dart.tmpl b/packages/flutter_tools/templates/create/lib/main.dart.tmpl index a2cbbc0e56..b4c6fd6f35 100644 --- a/packages/flutter_tools/templates/create/lib/main.dart.tmpl +++ b/packages/flutter_tools/templates/create/lib/main.dart.tmpl @@ -1,6 +1,14 @@ import 'package:flutter/material.dart'; +{{#withDriverTest?}} +import 'package:flutter_driver/driver_extension.dart'; +{{/withDriverTest?}} void main() { +{{#withDriverTest?}} + // Starts the app with Flutter Driver extension enabled to allow Flutter Driver + // to test the app. + enableFlutterDriverExtension(); +{{/withDriverTest?}} runApp( new MaterialApp( title: 'Flutter Demo', diff --git a/packages/flutter_tools/templates/driver/e2e.dart.tmpl b/packages/flutter_tools/templates/driver/e2e.dart.tmpl deleted file mode 100644 index 889670d7f7..0000000000 --- a/packages/flutter_tools/templates/driver/e2e.dart.tmpl +++ /dev/null @@ -1,9 +0,0 @@ -// Starts the app with Flutter Driver extension enabled to allow Flutter Driver -// to test the app. -import 'package:{{projectName}}/main.dart' as app; -import 'package:flutter_driver/driver_extension.dart'; - -main() { - enableFlutterDriverExtension(); - app.main(); -} diff --git a/packages/flutter_tools/templates/driver/e2e_test.dart.tmpl b/packages/flutter_tools/templates/driver/main_test.dart.tmpl similarity index 68% rename from packages/flutter_tools/templates/driver/e2e_test.dart.tmpl rename to packages/flutter_tools/templates/driver/main_test.dart.tmpl index e9307def98..38ca063651 100644 --- a/packages/flutter_tools/templates/driver/e2e_test.dart.tmpl +++ b/packages/flutter_tools/templates/driver/main_test.dart.tmpl @@ -22,28 +22,20 @@ main() { }); tearDownAll(() async { - if (driver != null) driver.close(); - }); - - test('find the floating action button by value key', () async { - ObjectRef elem = await driver.findByValueKey('fab'); - expect(elem, isNotNull); - expect(elem.objectReferenceKey, isNotNull); + if (driver != null) + driver.close(); }); test('tap on the floating action button; verify counter', () async { // Find floating action button (fab) to tap on - ObjectRef fab = await driver.findByValueKey('fab'); + ObjectRef fab = await driver.findByTooltipMessage('Increment'); expect(fab, isNotNull); // Tap on the fab await driver.tap(fab); // Wait for text to change to the desired value - await driver.waitFor(() async { - ObjectRef counter = await driver.findByValueKey('counter'); - return await driver.getText(counter); - }, contains("Button tapped 1 times.")); + expect(await driver.findByText('Button tapped 1 time.'), isNotNull); }); }); }