Use flutter_tools to start WebDriver browser. (#49228)

This commit is contained in:
Angjie Li
2020-01-21 16:48:02 -08:00
committed by Flutter GitHub Bot
parent d8092d999a
commit f0a175f41d
36 changed files with 520 additions and 493 deletions

View File

@@ -3,6 +3,7 @@
// found in the LICENSE file.
import 'dart:async';
import 'dart:io';
import 'package:json_rpc_2/json_rpc_2.dart' as rpc;
import 'package:meta/meta.dart';
@@ -86,18 +87,17 @@ abstract class FlutterDriver {
FlutterDriver();
/// Creates a driver that uses a connection provided by either the combination
/// of [webConnection] and [browser], or the combination of [serviceClient],
/// of [webConnection], or the combination of [serviceClient],
/// [peer] and [appIsolate]
@visibleForTesting
factory FlutterDriver.connectedTo({
FlutterWebConnection webConnection,
Browser browser,
VMServiceClient serviceClient,
rpc.Peer peer,
VMIsolate appIsolate,
}) {
if (webConnection != null && browser != null) {
return WebFlutterDriver.connectedTo(webConnection, browser);
if (webConnection != null) {
return WebFlutterDriver.connectedTo(webConnection);
}
return VMServiceFlutterDriver.connectedTo(serviceClient, peer, appIsolate);
}
@@ -140,11 +140,9 @@ abstract class FlutterDriver {
bool logCommunicationToFile = true,
int isolateNumber,
Pattern fuchsiaModuleTarget,
bool browser = false,
Duration timeout,
}) async {
if (browser) {
if (Platform.environment['FLUTTER_WEB_TEST'] != null) {
return WebFlutterDriver.connectWeb(hostUrl: dartVmServiceUrl, timeout: timeout);
}
return VMServiceFlutterDriver.connect(
@@ -561,7 +559,9 @@ abstract class FlutterDriver {
/// In practice, sometimes the device gets really busy for a while and
/// even two seconds isn't enough, which means that this is still racy
/// and a source of flakes.
Future<List<int>> screenshot() => throw UnimplementedError();
Future<List<int>> screenshot() {
throw UnimplementedError();
}
/// Returns the Flags set in the Dart VM as JSON.
///
@@ -584,8 +584,9 @@ abstract class FlutterDriver {
/// [getFlagList]: https://github.com/dart-lang/sdk/blob/master/runtime/vm/service/service.md#getflaglist
///
/// Throws [UnimplementedError] on [WebFlutterDriver] instances.
Future<List<Map<String, dynamic>>> getVmFlags() => throw UnimplementedError();
Future<List<Map<String, dynamic>>> getVmFlags() {
throw UnimplementedError();
}
/// Starts recording performance traces.
///
/// The `timeout` argument causes a warning to be displayed to the user if the
@@ -596,7 +597,9 @@ abstract class FlutterDriver {
Future<void> startTracing({
List<TimelineStream> streams = const <TimelineStream>[TimelineStream.all],
Duration timeout = kUnusuallyLongTimeout,
}) => throw UnimplementedError();
}) {
throw UnimplementedError();
}
/// Stops recording performance traces and downloads the timeline.
///
@@ -607,8 +610,9 @@ abstract class FlutterDriver {
/// For [WebFlutterDriver], this is only supported for Chrome.
Future<Timeline> stopTracingAndDownloadTimeline({
Duration timeout = kUnusuallyLongTimeout,
}) => throw UnimplementedError();
}) {
throw UnimplementedError();
}
/// Runs [action] and outputs a performance trace for it.
///
/// Waits for the `Future` returned by [action] to complete prior to stopping
@@ -632,7 +636,9 @@ abstract class FlutterDriver {
Future<dynamic> action(), {
List<TimelineStream> streams = const <TimelineStream>[TimelineStream.all],
bool retainPriorEvents = false,
}) => throw UnimplementedError();
}) {
throw UnimplementedError();
}
/// Clears all timeline events recorded up until now.
///
@@ -643,8 +649,9 @@ abstract class FlutterDriver {
/// For [WebFlutterDriver], this is only supported for Chrome.
Future<void> clearTimeline({
Duration timeout = kUnusuallyLongTimeout,
}) => throw UnimplementedError();
}) {
throw UnimplementedError();
}
/// [action] will be executed with the frame sync mechanism disabled.
///
/// By default, Flutter Driver waits until there is no pending frame scheduled
@@ -675,12 +682,16 @@ abstract class FlutterDriver {
/// Force a garbage collection run in the VM.
///
/// Throws [UnimplementedError] on [WebFlutterDriver] instances.
Future<void> forceGC() => throw UnimplementedError();
Future<void> forceGC() {
throw UnimplementedError();
}
/// Closes the underlying connection to the VM service.
///
/// Returns a [Future] that fires once the connection has been closed.
Future<void> close() => throw UnimplementedError();
Future<void> close() {
throw UnimplementedError();
}
}
/// Provides convenient accessors to frequently used finders.

View File

@@ -5,7 +5,6 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:math' as math;
import 'package:matcher/matcher.dart';
import 'package:meta/meta.dart';
@@ -17,9 +16,6 @@ import '../common/error.dart';
import '../common/message.dart';
import 'driver.dart';
import 'timeline.dart';
import 'web_driver_config.dart';
export 'web_driver_config.dart';
/// An implementation of the Flutter Driver using the WebDriver.
///
@@ -27,15 +23,14 @@ export 'web_driver_config.dart';
/// 1. Have Selenium server (https://bit.ly/2TlkRyu) and WebDriver binary (https://chromedriver.chromium.org/downloads) downloaded and placed under the same folder
/// 2. Launch WebDriver Server: java -jar selenium-server-standalone-3.141.59.jar
/// 3. Launch Flutter Web application: flutter run -v -d chrome --target=test_driver/scroll_perf_web.dart
/// 4. Run test script: flutter drive --target=test_driver/scroll_perf.dart -v --use-existing-app=/application address/
/// 4. Run test script: flutter drive --target=test_driver/scroll_perf_web.dart -v --use-existing-app=/application address/
class WebFlutterDriver extends FlutterDriver {
/// Creates a driver that uses a connection provided by the given
/// [_connection] and [_browserName].
WebFlutterDriver.connectedTo(this._connection, this._browser) :
/// [_connection].
WebFlutterDriver.connectedTo(this._connection) :
_startTime = DateTime.now();
final FlutterWebConnection _connection;
final Browser _browser;
DateTime _startTime;
/// Start time for tracing
@@ -50,21 +45,22 @@ class WebFlutterDriver extends FlutterDriver {
/// Creates a driver that uses a connection provided by the given
/// [hostUrl] which would fallback to environment variable VM_SERVICE_URL.
/// Driver also depends on environment variables BROWSER_NAME,
/// BROWSER_DIMENSION, HEADLESS and SELENIUM_PORT for configurations.
/// Driver also depends on environment variables DRIVER_SESSION_ID,
/// BROWSER_SUPPORTS_TIMELINE, DRIVER_SESSION_URI, DRIVER_SESSION_SPEC
/// and DRIVER_SESSION_CAPABILITIES for configurations.
static Future<FlutterDriver> connectWeb(
{String hostUrl, Duration timeout}) async {
hostUrl ??= Platform.environment['VM_SERVICE_URL'];
final Browser browser = browserNameToEnum(Platform.environment['BROWSER_NAME']);
final Map<String, dynamic> settings = <String, dynamic>{
'browser': browser,
'browser-dimension': Platform.environment['BROWSER_DIMENSION'],
'headless': Platform.environment['HEADLESS']?.toLowerCase() == 'true',
'selenium-port': Platform.environment['SELENIUM_PORT'],
'support-timeline-action': Platform.environment['SUPPORT_TIMELINE_ACTION'] == 'true',
'session-id': Platform.environment['DRIVER_SESSION_ID'],
'session-uri': Platform.environment['DRIVER_SESSION_URI'],
'session-spec': Platform.environment['DRIVER_SESSION_SPEC'],
'session-capabilities': Platform.environment['DRIVER_SESSION_CAPABILITIES'],
};
final FlutterWebConnection connection = await FlutterWebConnection.connect
(hostUrl, settings, timeout: timeout);
return WebFlutterDriver.connectedTo(connection, browser);
return WebFlutterDriver.connectedTo(connection);
}
@override
@@ -160,8 +156,8 @@ class WebFlutterDriver extends FlutterDriver {
/// Checks whether browser supports Timeline related operations
void _checkBrowserSupportsTimeline() {
if (_browser != Browser.chrome) {
throw UnimplementedError();
if (_connection.supportsTimelineAction) {
throw UnsupportedError('Timeline action is not supported by current testing browser');
}
}
}
@@ -169,10 +165,24 @@ class WebFlutterDriver extends FlutterDriver {
/// Encapsulates connection information to an instance of a Flutter Web application.
class FlutterWebConnection {
/// Creates a FlutterWebConnection with WebDriver
FlutterWebConnection(this._driver);
/// and whether the WebDriver supports timeline action
FlutterWebConnection(this._driver, this._supportsTimelineAction);
final sync_io.WebDriver _driver;
bool _supportsTimelineAction;
/// Whether the connected WebDriver supports timeline action for Flutter Web Driver
// ignore: unnecessary_getters_setters
bool get supportsTimelineAction => _supportsTimelineAction;
/// Setter for _supportsTimelineAction
@visibleForTesting
// ignore: unnecessary_getters_setters
set supportsTimelineAction(bool value) {
_supportsTimelineAction = value;
}
/// Starts WebDriver with the given [capabilities] and
/// establishes the connection to Flutter Web application.
static Future<FlutterWebConnection> connect(
@@ -181,13 +191,15 @@ class FlutterWebConnection {
{Duration timeout}) async {
// Use sync WebDriver because async version will create a 15 seconds
// overhead when quitting.
final sync_io.WebDriver driver = createDriver(settings);
final sync_io.WebDriver driver = sync_io.fromExistingSession(
settings['session-id'].toString(),
uri: Uri.parse(settings['session-uri'].toString()),
spec: _convertToSpec(settings['session-spec'].toString().toLowerCase()),
capabilities: jsonDecode(settings['session-capabilities'].toString()) as Map<String, dynamic>);
driver.get(url);
setDriverLocationAndDimension(driver, settings);
await waitUntilExtensionInstalled(driver, timeout);
return FlutterWebConnection(driver);
return FlutterWebConnection(driver, settings['support-timeline-action'] as bool);
}
/// Sends command via WebDriver to Flutter web application
@@ -224,24 +236,7 @@ class FlutterWebConnection {
/// Closes the WebDriver.
Future<void> close() async {
_driver.quit();
}
}
/// Configures the location and dimension of WebDriver.
void setDriverLocationAndDimension(sync_io.WebDriver driver, Map<String, dynamic> settings) {
final List<String> dimensions = settings['browser-dimension'].split(',') as List<String>;
if (dimensions.length != 2) {
throw DriverError('Invalid browser window size.');
}
final int x = int.parse(dimensions[0]);
final int y = int.parse(dimensions[1]);
final sync_io.Window window = driver.window;
try {
window.setLocation(const math.Point<int>(0, 0));
window.setSize(math.Rectangle<int>(0, 0, x, y));
} catch (_) {
// Error might be thrown in some browsers.
_driver.quit(closeSession: false);
}
}
@@ -252,3 +247,14 @@ Future<void> waitUntilExtensionInstalled(sync_io.WebDriver driver, Duration time
matcher: 'function',
timeout: timeout ?? const Duration(days: 365));
}
sync_io.WebDriverSpec _convertToSpec(String specString) {
switch (specString.toLowerCase()) {
case 'webdriverspec.w3c':
return sync_io.WebDriverSpec.W3c;
case 'webdriverspec.jsonwire':
return sync_io.WebDriverSpec.JsonWire;
default:
return sync_io.WebDriverSpec.Auto;
}
}

View File

@@ -1,130 +0,0 @@
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:meta/meta.dart';
import 'package:webdriver/sync_io.dart' as sync_io;
import '../common/error.dart';
/// A list of supported browsers
enum Browser {
/// Chrome: https://www.google.com/chrome/
chrome,
/// Edge: https://www.microsoft.com/en-us/windows/microsoft-edge
edge,
/// Firefox: https://www.mozilla.org/en-US/firefox/
firefox,
/// Safari in iOS: https://www.apple.com/safari/
iosSafari,
/// Safari in macOS: https://www.apple.com/safari/
safari,
}
/// Converts [browserName] string to [Browser]
Browser browserNameToEnum(String browserName){
switch (browserName) {
case 'chrome': return Browser.chrome;
case 'edge': return Browser.edge;
case 'firefox': return Browser.firefox;
case 'ios-safari': return Browser.iosSafari;
case 'safari': return Browser.safari;
}
throw DriverError('Browser $browserName not supported');
}
/// Creates a WebDriver instance with the given [settings].
sync_io.WebDriver createDriver(Map<String, dynamic> settings) {
return _createDriver(
settings['selenium-port'] as String,
settings['browser'] as Browser,
settings['headless'] as bool
);
}
sync_io.WebDriver _createDriver(String seleniumPort, Browser browser, bool headless) {
return sync_io.createDriver(
uri: Uri.parse('http://localhost:$seleniumPort/wd/hub/'),
desired: getDesiredCapabilities(browser, headless),
spec: browser != Browser.iosSafari ? sync_io.WebDriverSpec.JsonWire : sync_io.WebDriverSpec.W3c
);
}
/// Returns desired capabilities for given [browser] and [headless].
@visibleForTesting
Map<String, dynamic> getDesiredCapabilities(Browser browser, bool headless) {
switch (browser) {
case Browser.chrome:
return <String, dynamic>{
'acceptInsecureCerts': true,
'browserName': 'chrome',
'goog:loggingPrefs': <String, String>{ sync_io.LogType.performance: 'ALL'},
'chromeOptions': <String, dynamic>{
'args': <String>[
'--bwsi',
'--disable-background-timer-throttling',
'--disable-default-apps',
'--disable-extensions',
'--disable-popup-blocking',
'--disable-translate',
'--no-default-browser-check',
'--no-sandbox',
'--no-first-run',
if (headless) '--headless'
],
'perfLoggingPrefs': <String, String>{
'traceCategories':
'devtools.timeline,'
'v8,blink.console,benchmark,blink,'
'blink.user_timing'
}
}
};
break;
case Browser.firefox:
return <String, dynamic>{
'acceptInsecureCerts': true,
'browserName': 'firefox',
'moz:firefoxOptions' : <String, dynamic>{
'args': <String>[
if (headless) '-headless'
],
'prefs': <String, dynamic>{
'dom.file.createInChild': true,
'dom.timeout.background_throttling_max_budget': -1,
'media.autoplay.default': 0,
'media.gmp-manager.url': '',
'media.gmp-provider.enabled': false,
'network.captive-portal-service.enabled': false,
'security.insecure_field_warning.contextual.enabled': false,
'test.currentTimeOffsetSeconds': 11491200
},
'log': <String, String>{'level': 'trace'}
}
};
break;
case Browser.edge:
return <String, dynamic>{
'acceptInsecureCerts': true,
'browserName': 'edge',
};
break;
case Browser.safari:
return <String, dynamic>{
'browserName': 'safari',
'safari.options': <String, dynamic>{
'skipExtensionInstallation': true,
'cleanSession': true
}
};
break;
case Browser.iosSafari:
return <String, dynamic>{
'platformName': 'ios',
'browserName': 'safari',
'safari:useSimulator': true
};
default:
throw DriverError('Browser $browser not supported.');
}
}

View File

@@ -694,7 +694,8 @@ void main() {
setUp(() {
mockConnection = MockFlutterWebConnection();
driver = WebFlutterDriver.connectedTo(mockConnection, Browser.chrome);
mockConnection.supportsTimelineAction = true;
driver = WebFlutterDriver.connectedTo(mockConnection);
});
test('closes connection', () async {
@@ -1033,7 +1034,8 @@ void main() {
setUp(() {
mockConnection = MockFlutterWebConnection();
driver = WebFlutterDriver.connectedTo(mockConnection, Browser.edge);
mockConnection.supportsTimelineAction = false;
driver = WebFlutterDriver.connectedTo(mockConnection);
});
test('tracing', () async {

View File

@@ -1,149 +0,0 @@
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_driver/src/driver/web_driver_config.dart';
import 'package:webdriver/sync_io.dart' as sync_io;
import '../../common.dart';
void main() {
group('getDesiredCapabilities', () {
test('Chrome with headless on', () {
final Map<String, dynamic> expected = <String, dynamic>{
'acceptInsecureCerts': true,
'browserName': 'chrome',
'goog:loggingPrefs': <String, String>{ sync_io.LogType.performance: 'ALL'},
'chromeOptions': <String, dynamic>{
'args': <String>[
'--bwsi',
'--disable-background-timer-throttling',
'--disable-default-apps',
'--disable-extensions',
'--disable-popup-blocking',
'--disable-translate',
'--no-default-browser-check',
'--no-sandbox',
'--no-first-run',
'--headless'
],
'perfLoggingPrefs': <String, String>{
'traceCategories':
'devtools.timeline,'
'v8,blink.console,benchmark,blink,'
'blink.user_timing'
}
}
};
expect(getDesiredCapabilities(Browser.chrome, true), expected);
});
test('Chrome with headless off', () {
final Map<String, dynamic> expected = <String, dynamic>{
'acceptInsecureCerts': true,
'browserName': 'chrome',
'goog:loggingPrefs': <String, String>{ sync_io.LogType.performance: 'ALL'},
'chromeOptions': <String, dynamic>{
'args': <String>[
'--bwsi',
'--disable-background-timer-throttling',
'--disable-default-apps',
'--disable-extensions',
'--disable-popup-blocking',
'--disable-translate',
'--no-default-browser-check',
'--no-sandbox',
'--no-first-run',
],
'perfLoggingPrefs': <String, String>{
'traceCategories':
'devtools.timeline,'
'v8,blink.console,benchmark,blink,'
'blink.user_timing'
}
}
};
expect(getDesiredCapabilities(Browser.chrome, false), expected);
});
test('Firefox with headless on', () {
final Map<String, dynamic> expected = <String, dynamic>{
'acceptInsecureCerts': true,
'browserName': 'firefox',
'moz:firefoxOptions' : <String, dynamic>{
'args': <String>['-headless'],
'prefs': <String, dynamic>{
'dom.file.createInChild': true,
'dom.timeout.background_throttling_max_budget': -1,
'media.autoplay.default': 0,
'media.gmp-manager.url': '',
'media.gmp-provider.enabled': false,
'network.captive-portal-service.enabled': false,
'security.insecure_field_warning.contextual.enabled': false,
'test.currentTimeOffsetSeconds': 11491200
},
'log': <String, String>{'level': 'trace'}
}
};
expect(getDesiredCapabilities(Browser.firefox, true), expected);
});
test('Firefox with headless off', () {
final Map<String, dynamic> expected = <String, dynamic>{
'acceptInsecureCerts': true,
'browserName': 'firefox',
'moz:firefoxOptions' : <String, dynamic>{
'args': <String>[],
'prefs': <String, dynamic>{
'dom.file.createInChild': true,
'dom.timeout.background_throttling_max_budget': -1,
'media.autoplay.default': 0,
'media.gmp-manager.url': '',
'media.gmp-provider.enabled': false,
'network.captive-portal-service.enabled': false,
'security.insecure_field_warning.contextual.enabled': false,
'test.currentTimeOffsetSeconds': 11491200
},
'log': <String, String>{'level': 'trace'}
}
};
expect(getDesiredCapabilities(Browser.firefox, false), expected);
});
test('Edge', () {
final Map<String, dynamic> expected = <String, dynamic>{
'acceptInsecureCerts': true,
'browserName': 'edge',
};
expect(getDesiredCapabilities(Browser.edge, false), expected);
});
test('macOS Safari', () {
final Map<String, dynamic> expected = <String, dynamic>{
'browserName': 'safari',
'safari.options': <String, dynamic>{
'skipExtensionInstallation': true,
'cleanSession': true
}
};
expect(getDesiredCapabilities(Browser.safari, false), expected);
});
test('iOS Safari', () {
final Map<String, dynamic> expected = <String, dynamic>{
'platformName': 'ios',
'browserName': 'safari',
'safari:useSimulator': true
};
expect(getDesiredCapabilities(Browser.iosSafari, false), expected);
});
});
}