drive.dart 10 KB
Newer Older
yjbanov's avatar
yjbanov committed
1 2 3 4 5
// Copyright 2016 The Chromium 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 'dart:async';
6
import 'dart:io' as io;
yjbanov's avatar
yjbanov committed
7 8

import 'package:path/path.dart' as path;
Ian Hickson's avatar
Ian Hickson committed
9
import 'package:test/src/executable.dart' as executable; // ignore: implementation_imports
yjbanov's avatar
yjbanov committed
10

11 12
import '../android/android_device.dart' show AndroidDevice;
import '../application_package.dart';
yjbanov's avatar
yjbanov committed
13
import '../base/file_system.dart';
14 15
import '../base/os.dart';
import '../device.dart';
yjbanov's avatar
yjbanov committed
16
import '../globals.dart';
17
import '../ios/simulators.dart' show SimControl, IOSSimulatorUtils;
18
import 'build_apk.dart' as build_apk;
yjbanov's avatar
yjbanov committed
19 20 21 22 23 24 25 26 27 28 29
import 'run.dart';

/// Runs integration (a.k.a. end-to-end) tests.
///
/// An integration test is a program that runs in a separate process from your
/// Flutter application. It connects to the application and acts like a user,
/// performing taps, scrolls, reading out widget properties and verifying their
/// correctness.
///
/// This command takes a target Flutter application that you would like to test
/// as the `--target` option (defaults to `lib/main.dart`). It then looks for a
30 31 32 33
/// corresponding test file within the `test_driver` directory. The test file is
/// expected to have the same name but contain the `_test.dart` suffix. The
/// `_test.dart` file would generall be a Dart program that uses
/// `package:flutter_driver` and exercises your application. Most commonly it
yjbanov's avatar
yjbanov committed
34 35 36 37 38 39 40
/// is a test written using `package:test`, but you are free to use something
/// else.
///
/// The app and the test are launched simultaneously. Once the test completes
/// the application is stopped and the command exits. If all these steps are
/// successful the exit code will be `0`. Otherwise, you will see a non-zero
/// exit code.
41 42
class DriveCommand extends RunCommandBase {
  DriveCommand() {
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
    argParser.addFlag(
      'keep-app-running',
      negatable: true,
      defaultsTo: false,
      help:
        'Will keep the Flutter application running when done testing. By '
        'default Flutter Driver stops the application after tests are finished.'
    );

    argParser.addFlag(
      'use-existing-app',
      negatable: true,
      defaultsTo: false,
      help:
        'Will not start a new Flutter application but connect to an '
        'already running instance. This will also cause the driver to keep '
        'the application running after tests are done.'
    );
61 62

    argParser.addOption('debug-port',
63
        defaultsTo: '8183',
64
        help: 'Listen to the given port for a debug connection.');
yjbanov's avatar
yjbanov committed
65 66
  }

67
  @override
68
  final String name = 'drive';
69 70

  @override
71
  final String description = 'Runs Flutter Driver tests for the current project.';
72 73

  @override
74 75 76 77
  final List<String> aliases = <String>['driver'];

  Device _device;
  Device get device => _device;
yjbanov's avatar
yjbanov committed
78

79
  int get debugPort => int.parse(argResults['debug-port']);
80

yjbanov's avatar
yjbanov committed
81 82 83
  @override
  Future<int> runInProject() async {
    String testFile = _getTestFile();
84 85 86
    if (testFile == null) {
      return 1;
    }
yjbanov's avatar
yjbanov committed
87

88 89 90 91 92
    this._device = await targetDeviceFinder();
    if (device == null) {
      return 1;
    }

yjbanov's avatar
yjbanov committed
93 94 95 96 97
    if (await fs.type(testFile) != FileSystemEntityType.FILE) {
      printError('Test file not found: $testFile');
      return 1;
    }

98 99
    if (!argResults['use-existing-app']) {
      printStatus('Starting application: ${argResults["target"]}');
100
      int result = await appStarter(this);
101 102 103 104 105
      if (result != 0) {
        printError('Application failed to start. Will not run test. Quitting.');
        return result;
      }
    } else {
106
      printStatus('Will connect to already running application instance.');
yjbanov's avatar
yjbanov committed
107 108 109
    }

    try {
110
      return await testRunner([testFile])
Ian Hickson's avatar
Ian Hickson committed
111
        .catchError((dynamic error, dynamic stackTrace) {
112
          printError('CAUGHT EXCEPTION: $error\n$stackTrace');
yjbanov's avatar
yjbanov committed
113 114 115
          return 1;
        });
    } finally {
116
      if (!argResults['keep-app-running'] && !argResults['use-existing-app']) {
117 118 119 120 121
        printStatus('Stopping application instance.');
        try {
          await appStopper(this);
        } catch(error, stackTrace) {
          // TODO(yjbanov): remove this guard when this bug is fixed: https://github.com/dart-lang/sdk/issues/25862
122
          printTrace('Could not stop application: $error\n$stackTrace');
123
        }
124
      } else {
125
        printStatus('Leaving the application running.');
126
      }
yjbanov's avatar
yjbanov committed
127 128 129 130
    }
  }

  String _getTestFile() {
131
    String appFile = path.normalize(target);
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164

    // This command extends `flutter start` and therefore CWD == package dir
    String packageDir = getCurrentDirectory();

    // Make appFile path relative to package directory because we are looking
    // for the corresponding test file relative to it.
    if (!path.isRelative(appFile)) {
      if (!path.isWithin(packageDir, appFile)) {
        printError(
          'Application file $appFile is outside the package directory $packageDir'
        );
        return null;
      }

      appFile = path.relative(appFile, from: packageDir);
    }

    List<String> parts = path.split(appFile);

    if (parts.length < 2) {
      printError(
        'Application file $appFile must reside in one of the sub-directories '
        'of the package structure, not in the root directory.'
      );
      return null;
    }

    // Look for the test file inside `test_driver/` matching the sub-path, e.g.
    // if the application is `lib/foo/bar.dart`, the test file is expected to
    // be `test_driver/foo/bar_test.dart`.
    String pathWithNoExtension = path.withoutExtension(path.joinAll(
      [packageDir, 'test_driver']..addAll(parts.skip(1))));
    return '${pathWithNoExtension}_test${path.extension(appFile)}';
yjbanov's avatar
yjbanov committed
165 166
  }
}
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186

/// Finds a device to test on. May launch a simulator, if necessary.
typedef Future<Device> TargetDeviceFinder();
TargetDeviceFinder targetDeviceFinder = findTargetDevice;
void restoreTargetDeviceFinder() {
  targetDeviceFinder = findTargetDevice;
}

Future<Device> findTargetDevice() async {
  if (deviceManager.hasSpecifiedDeviceId) {
    return deviceManager.getDeviceById(deviceManager.specifiedDeviceId);
  }

  List<Device> devices = await deviceManager.getAllConnectedDevices();

  if (os.isMacOS) {
    // On Mac we look for the iOS Simulator. If available, we use that. Then
    // we look for an Android device. If there's one, we use that. Otherwise,
    // we launch a new iOS Simulator.
    Device reusableDevice = devices.firstWhere(
Ian Hickson's avatar
Ian Hickson committed
187
      (Device d) => d.isLocalEmulator,
188
      orElse: () {
Ian Hickson's avatar
Ian Hickson committed
189
        return devices.firstWhere((Device d) => d is AndroidDevice,
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
            orElse: () => null);
      }
    );

    if (reusableDevice != null) {
      printStatus('Found connected ${reusableDevice.isLocalEmulator ? "emulator" : "device"} "${reusableDevice.name}"; will reuse it.');
      return reusableDevice;
    }

    // No running emulator found. Attempt to start one.
    printStatus('Starting iOS Simulator, because did not find existing connected devices.');
    bool started = await SimControl.instance.boot();
    if (started) {
      return IOSSimulatorUtils.instance.getAttachedDevices().first;
    } else {
      printError('Failed to start iOS Simulator.');
      return null;
    }
  } else if (os.isLinux) {
    // On Linux, for now, we just grab the first connected device we can find.
    if (devices.isEmpty) {
      printError('No devices found.');
      return null;
    } else if (devices.length > 1) {
      printStatus('Found multiple connected devices:');
Ian Hickson's avatar
Ian Hickson committed
215
      printStatus(devices.map((Device d) => '  - ${d.name}\n').join(''));
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
    }
    printStatus('Using device ${devices.first.name}.');
    return devices.first;
  } else if (os.isWindows) {
    printError('Windows is not yet supported.');
    return null;
  } else {
    printError('The operating system on this computer is not supported.');
    return null;
  }
}

/// Starts the application on the device given command configuration.
typedef Future<int> AppStarter(DriveCommand command);
AppStarter appStarter = startApp;
void restoreAppStarter() {
  appStarter = startApp;
}

Future<int> startApp(DriveCommand command) async {
  String mainPath = findMainDartFile(command.target);
  if (await fs.type(mainPath) != FileSystemEntityType.FILE) {
    printError('Tried to run $mainPath, but that file does not exist.');
    return 1;
  }

242
  // TODO(devoncarew): We should remove the need to special case here.
243 244
  if (command.device is AndroidDevice) {
    printTrace('Building an APK.');
245
    int result = await build_apk.buildApk(
Devon Carew's avatar
Devon Carew committed
246 247 248
      command.device.platform,
      command.toolchain,
      target: command.target
Devon Carew's avatar
Devon Carew committed
249
    );
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271

    if (result != 0)
      return result;
  }

  printTrace('Stopping previously running application, if any.');
  await appStopper(command);

  printTrace('Installing application package.');
  ApplicationPackage package = command.applicationPackages
      .getPackageForPlatform(command.device.platform);
  await command.device.installApp(package);

  printTrace('Starting application.');
  bool started = await command.device.startApp(
    package,
    command.toolchain,
    mainPath: mainPath,
    route: command.route,
    checked: command.checked,
    clearLogs: true,
    startPaused: true,
272
    observatoryPort: command.debugPort,
273 274 275 276 277
    platformArgs: <String, dynamic>{
      'trace-startup': command.traceStartup,
    }
  );

278
  if (started && command.device.supportsStartPaused) {
279 280 281 282 283 284 285
    await delayUntilObservatoryAvailable('localhost', command.debugPort);
  }

  return started ? 0 : 2;
}

/// Runs driver tests.
286
typedef Future<int> TestRunner(List<String> testArgs);
287 288 289 290 291
TestRunner testRunner = runTests;
void restoreTestRunner() {
  testRunner = runTests;
}

292
Future<int> runTests(List<String> testArgs) async {
293
  printTrace('Running driver tests.');
294 295
  await executable.main(testArgs);
  return io.exitCode;
296 297 298 299 300 301 302 303 304 305 306 307
}


/// Stops the application.
typedef Future<int> AppStopper(DriveCommand command);
AppStopper appStopper = stopApp;
void restoreAppStopper() {
  appStopper = stopApp;
}

Future<int> stopApp(DriveCommand command) async {
  printTrace('Stopping application.');
308
  ApplicationPackage package = command.applicationPackages.getPackageForPlatform(command.device.platform);
309 310 311
  bool stopped = await command.device.stopApp(package);
  return stopped ? 0 : 1;
}