run_tests.dart 11 KB
Newer Older
1 2 3 4 5 6
// 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 'dart:async';
import 'dart:convert';
7
import 'dart:ffi';
8 9 10 11 12 13 14
import 'dart:io';

import '../framework/devices.dart';
import '../framework/framework.dart';
import '../framework/task_result.dart';
import '../framework/utils.dart';

15
TaskFunction createAndroidRunDebugTest() {
16
  return AndroidRunOutputTest(release: false).call;
17 18
}

19
TaskFunction createAndroidRunReleaseTest() {
20
  return AndroidRunOutputTest(release: true).call;
21 22
}

23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
TaskFunction createLinuxRunDebugTest() {
  return DesktopRunOutputTest(
    '${flutterDirectory.path}/dev/integration_tests/ui',
    'lib/empty.dart',
    release: false,
  ).call;
}

TaskFunction createLinuxRunReleaseTest() {
  return DesktopRunOutputTest(
    '${flutterDirectory.path}/dev/integration_tests/ui',
    'lib/empty.dart',
    release: true,
  ).call;
}

39 40 41 42 43 44 45 46
TaskFunction createMacOSRunDebugTest() {
  return DesktopRunOutputTest(
    // TODO(cbracken): https://github.com/flutter/flutter/issues/87508#issuecomment-1043753201
    // Switch to dev/integration_tests/ui once we have CocoaPods working on M1 Macs.
    '${flutterDirectory.path}/examples/hello_world',
    'lib/main.dart',
    release: false,
    allowStderr: true,
47
  ).call;
48 49
}

50 51 52 53 54 55 56
TaskFunction createMacOSRunReleaseTest() {
  return DesktopRunOutputTest(
    // TODO(cbracken): https://github.com/flutter/flutter/issues/87508#issuecomment-1043753201
    // Switch to dev/integration_tests/ui once we have CocoaPods working on M1 Macs.
    '${flutterDirectory.path}/examples/hello_world',
    'lib/main.dart',
    release: true,
57
    allowStderr: true,
58
  ).call;
59 60
}

61
TaskFunction createWindowsRunDebugTest() {
62
  return WindowsRunOutputTest(
63 64 65
    '${flutterDirectory.path}/dev/integration_tests/ui',
    'lib/empty.dart',
    release: false,
66
  ).call;
67 68
}

69
TaskFunction createWindowsRunReleaseTest() {
70
  return WindowsRunOutputTest(
71 72 73
    '${flutterDirectory.path}/dev/integration_tests/ui',
    'lib/empty.dart',
    release: true,
74
  ).call;
75 76
}

77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
class AndroidRunOutputTest extends RunOutputTask {
  AndroidRunOutputTest({required super.release}) : super(
    '${flutterDirectory.path}/dev/integration_tests/ui',
    'lib/main.dart',
  );

  @override
  Future<void> prepare(String deviceId) async {
    // Uninstall if the app is already installed on the device to get to a clean state.
    final List<String> stderr = <String>[];
    print('uninstalling...');
    final Process uninstall = await startFlutter(
      'install',
      options:  <String>['--suppress-analytics', '--uninstall-only', '-d', deviceId],
      isBot: false,
    );
    uninstall.stdout
      .transform<String>(utf8.decoder)
      .transform<String>(const LineSplitter())
      .listen((String line) {
        print('uninstall:stdout: $line');
      });
    uninstall.stderr
      .transform<String>(utf8.decoder)
      .transform<String>(const LineSplitter())
      .listen((String line) {
        print('uninstall:stderr: $line');
        stderr.add(line);
      });
    if (await uninstall.exitCode != 0) {
      throw 'flutter install --uninstall-only failed.';
    }
    if (stderr.isNotEmpty) {
      throw 'flutter install --uninstall-only had output on standard error.';
    }
  }

  @override
  bool isExpectedStderr(String line) {
    // TODO(egarciad): Remove once https://github.com/flutter/flutter/issues/95131 is fixed.
    return line.contains('Mapping new ns');
  }

  @override
  TaskResult verify(List<String> stdout, List<String> stderr) {
122 123 124
    final String gradleTask = release ? 'assembleRelease' : 'assembleDebug';
    final String apk = release ? 'app-release.apk' : 'app-debug.apk';

125 126
    _findNextMatcherInList(
      stdout,
127 128
      (String line) => line.startsWith('Launching lib/main.dart on ') &&
        line.endsWith(' in ${release ? 'release' : 'debug'} mode...'),
129 130 131 132 133
      'Launching lib/main.dart on',
    );

    _findNextMatcherInList(
      stdout,
134 135
      (String line) => line.startsWith("Running Gradle task '$gradleTask'..."),
      "Running Gradle task '$gradleTask'...",
136 137
    );

138
    // Size information is only included in release builds.
139 140
    _findNextMatcherInList(
      stdout,
141 142 143
      (String line) => line.contains('Built build/app/outputs/flutter-apk/$apk') &&
        (!release || line.contains('MB).')),
      'Built build/app/outputs/flutter-apk/$apk',
144 145 146 147
    );

    _findNextMatcherInList(
      stdout,
148 149
      (String line) => line.startsWith('Installing build/app/outputs/flutter-apk/$apk...'),
      'Installing build/app/outputs/flutter-apk/$apk...',
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
    );

    _findNextMatcherInList(
      stdout,
      (String line) => line.contains('Quit (terminate the application on the device).'),
      'q Quit (terminate the application on the device)',
    );

    _findNextMatcherInList(
      stdout,
      (String line) => line == 'Application finished.',
      'Application finished.',
    );

    return TaskResult.success(null);
  }
}

168 169 170 171 172 173 174 175 176
class WindowsRunOutputTest extends DesktopRunOutputTest {
  WindowsRunOutputTest(
    super.testDirectory,
    super.testTarget, {
      required super.release,
      super.allowStderr = false,
    }
  );

177 178
  final String arch = Abi.current() == Abi.windowsX64 ? 'x64': 'arm64';

179 180 181 182
  static final RegExp _buildOutput = RegExp(
    r'Building Windows application\.\.\.\s*\d+(\.\d+)?(ms|s)',
    multiLine: true,
  );
183
  static final RegExp _builtOutput = RegExp(
184
    r'Built build\\windows\\(x64|arm64)\\runner\\(Debug|Release)\\\w+\.exe( \(\d+(\.\d+)?MB\))?\.',
185
  );
186 187 188 189 190 191 192 193

  @override
  void verifyBuildOutput(List<String> stdout) {
    _findNextMatcherInList(
      stdout,
      _buildOutput.hasMatch,
      'Building Windows application...',
    );
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210

    final String buildMode = release ? 'Release' : 'Debug';
    _findNextMatcherInList(
      stdout,
      (String line) {
        if (!_builtOutput.hasMatch(line) || !line.contains(buildMode)) {
          return false;
        }

        // Size information is only included in release builds.
        final bool hasSize = line.contains('MB).');
        if (release != hasSize) {
          return false;
        }

        return true;
      },
211
      'Built build\\windows\\$arch\\runner\\$buildMode\\app.exe',
212
    );
213 214 215
  }
}

216 217 218 219 220
class DesktopRunOutputTest extends RunOutputTask {
  DesktopRunOutputTest(
    super.testDirectory,
    super.testTarget, {
      required super.release,
221
      this.allowStderr = false,
222 223 224
    }
  );

225 226 227 228 229 230
  /// Whether `flutter run` is expected to produce output on stderr.
  final bool allowStderr;

  @override
  bool isExpectedStderr(String line) => allowStderr;

231 232 233 234
  @override
  TaskResult verify(List<String> stdout, List<String> stderr) {
    _findNextMatcherInList(
      stdout,
235
      (String line) => line.startsWith('Launching $testTarget on ') &&
236
        line.endsWith(' in ${release ? 'release' : 'debug'} mode...'),
237
      'Launching $testTarget on',
238 239
    );

240 241
    verifyBuildOutput(stdout);

242 243 244 245 246 247 248 249 250 251 252 253 254 255
    _findNextMatcherInList(
      stdout,
      (String line) => line.contains('Quit (terminate the application on the device).'),
      'q Quit (terminate the application on the device)',
    );

    _findNextMatcherInList(
      stdout,
      (String line) => line == 'Application finished.',
      'Application finished.',
    );

    return TaskResult.success(null);
  }
256 257 258

  /// Verify the output from `flutter run`'s build step.
  void verifyBuildOutput(List<String> stdout) {}
259 260 261 262 263 264 265 266 267 268 269
}

/// Test that the output of `flutter run` is expected.
abstract class RunOutputTask {
  RunOutputTask(
    this.testDirectory,
    this.testTarget, {
      required this.release,
    }
  );

270 271 272 273
  static final RegExp _engineLogRegex = RegExp(
    r'\[(VERBOSE|INFO|WARNING|ERROR|FATAL):.+\(\d+\)\]',
  );

274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
  /// The directory where the app under test is defined.
  final String testDirectory;
  /// The main entry-point file of the application, as run on the device.
  final String testTarget;
  /// Whether to run the app in release mode.
  final bool release;

  Future<TaskResult> call() {
    return inDirectory<TaskResult>(testDirectory, () async {
      final Device device = await devices.workingDevice;
      await device.unlock();
      final String deviceId = device.deviceId;

      final Completer<void> ready = Completer<void>();
      final List<String> stdout = <String>[];
      final List<String> stderr = <String>[];

291 292
      await prepare(deviceId);

293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
      final List<String> options = <String>[
        testTarget,
        '-d',
        deviceId,
        if (release) '--release',
      ];

      final Process run = await startFlutter(
        'run',
        options: options,
        isBot: false,
      );

      int? runExitCode;
      run.stdout
        .transform<String>(utf8.decoder)
        .transform<String>(const LineSplitter())
        .listen((String line) {
          print('run:stdout: $line');
          stdout.add(line);
          if (line.contains('Quit (terminate the application on the device).')) {
            ready.complete();
          }
        });
317
      final Stream<String> runStderr = run.stderr
318 319
        .transform<String>(utf8.decoder)
        .transform<String>(const LineSplitter())
320 321 322
        .asBroadcastStream();
      runStderr.listen((String line) => print('run:stderr: $line'));
      runStderr
323
        .skipWhile(isExpectedStderr)
324
        .listen((String line) => stderr.add(line));
325 326 327 328 329 330 331 332 333
      unawaited(run.exitCode.then<void>((int exitCode) { runExitCode = exitCode; }));
      await Future.any<dynamic>(<Future<dynamic>>[ ready.future, run.exitCode ]);
      if (runExitCode != null) {
        throw 'Failed to run test app; runner unexpected exited, with exit code $runExitCode.';
      }
      run.stdin.write('q');

      await run.exitCode;

334 335 336 337
      if (stderr.isNotEmpty) {
        throw 'flutter run ${release ? '--release' : ''} had unexpected output on standard error.';
      }

338 339 340 341 342 343 344
      final List<String> engineLogs = List<String>.from(
        stdout.where(_engineLogRegex.hasMatch),
      );
      if (engineLogs.isNotEmpty) {
        throw 'flutter run had unexpected Flutter engine logs $engineLogs';
      }

345 346 347 348
      return verify(stdout, stderr);
    });
  }

349 350 351 352 353 354
  /// Prepare the device for running the test app.
  Future<void> prepare(String deviceId) => Future<void>.value();

  /// Returns true if this stderr output line is expected.
  bool isExpectedStderr(String line) => false;

355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
  /// Verify the output of `flutter run`.
  TaskResult verify(List<String> stdout, List<String> stderr) => throw UnimplementedError('verify is not implemented');

  /// Helper that verifies a line in [list] matches [matcher].
  /// The [list] is updated to contain the lines remaining after the match.
  void _findNextMatcherInList(
    List<String> list,
    bool Function(String testLine) matcher,
    String errorMessageExpectedLine
  ) {
    final List<String> copyOfListForErrorMessage = List<String>.from(list);

    while (list.isNotEmpty) {
      final String nextLine = list.first;
      list.removeAt(0);

      if (matcher(nextLine)) {
        return;
      }
    }

    throw '''
Did not find expected line

$errorMessageExpectedLine

in flutter run ${release ? '--release' : ''} stdout

$copyOfListForErrorMessage
''';
  }
}