runner_test.dart 11.6 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5 6
// @dart = 2.8

7 8 9 10
import 'dart:async';

import 'package:file/memory.dart';
import 'package:flutter_tools/runner.dart' as runner;
11
import 'package:flutter_tools/src/artifacts.dart';
12
import 'package:flutter_tools/src/base/common.dart';
13 14
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/base/io.dart' as io;
15
import 'package:flutter_tools/src/base/net.dart';
16
import 'package:flutter_tools/src/base/platform.dart';
17
import 'package:flutter_tools/src/base/user_messages.dart';
18
import 'package:flutter_tools/src/cache.dart';
19
import 'package:flutter_tools/src/globals.dart' as globals;
20
import 'package:flutter_tools/src/reporting/crash_reporting.dart';
21 22 23 24 25
import 'package:flutter_tools/src/reporting/reporting.dart';
import 'package:flutter_tools/src/runner/flutter_command.dart';

import '../../src/common.dart';
import '../../src/context.dart';
26
import '../../src/fake_http_client.dart';
27

28 29
const String kCustomBugInstructions = 'These are instructions to report with a custom bug tracker.';

30
void main() {
31 32
  int firstExitCode;

33 34 35 36
  group('runner', () {
    setUp(() {
      // Instead of exiting with dart:io exit(), this causes an exception to
      // be thrown, which we catch with the onError callback in the zone below.
37 38 39 40 41 42 43 44 45 46
      //
      // Tests might trigger exit() multiple times.  In real life, exit() would
      // cause the VM to terminate immediately, so only the first one matters.
      firstExitCode = null;
      io.setExitFunctionForTests((int exitCode) {
        firstExitCode ??= exitCode;

        // TODO(jamesderlin): Ideally only the first call to exit() would be
        // honored and subsequent calls would be no-ops, but existing tests
        // rely on all calls to throw.
47
        throw Exception('test exit');
48 49
      });

50 51 52 53 54 55 56 57
      Cache.disableLocking();
    });

    tearDown(() {
      io.restoreExitFunction();
      Cache.enableLocking();
    });

58
    testUsingContext('error handling crash report (synchronous crash)', () async {
59 60 61
      final Completer<void> completer = Completer<void>();
      // runner.run() asynchronously calls the exit function set above, so we
      // catch it in a zone.
62 63
      unawaited(runZoned<Future<void>>(
        () {
64
          unawaited(runner.run(
65
            <String>['crash'],
66
            () => <FlutterCommand>[
67 68 69 70 71 72 73 74
              CrashingFlutterCommand(),
            ],
            // This flutterVersion disables crash reporting.
            flutterVersion: '[user-branch]/',
            reportCrashes: true,
          ));
          return null;
        },
75
        onError: (Object error, StackTrace stack) { // ignore: deprecated_member_use
76 77
          expect(firstExitCode, isNotNull);
          expect(firstExitCode, isNot(0));
78
          expect(error.toString(), 'Exception: test exit');
79
          completer.complete();
80 81
        },
      ));
82 83 84 85 86 87 88 89
      await completer.future;

      // This is the main check of this test.
      //
      // We are checking that, even though crash reporting failed with an
      // exception on the first attempt, the second attempt tries to report the
      // *original* crash, and not the crash from the first crash report
      // attempt.
90
      final CrashingUsage crashingUsage = globals.flutterUsage as CrashingUsage;
91
      expect(crashingUsage.sentException.toString(), 'Exception: an exception % --');
92 93 94 95 96
    }, overrides: <Type, Generator>{
      Platform: () => FakePlatform(environment: <String, String>{
        'FLUTTER_ANALYTICS_LOG_FILE': 'test',
        'FLUTTER_ROOT': '/',
      }),
97
      FileSystem: () => MemoryFileSystem.test(),
98
      ProcessManager: () => FakeProcessManager.any(),
99
      Usage: () => CrashingUsage(),
100
      Artifacts: () => Artifacts.test(),
101
      HttpClientFactory: () => () => FakeHttpClient.any()
102
    });
103

104 105 106 107 108 109 110 111 112 113 114 115 116 117
    // This Completer completes when CrashingFlutterCommand.runCommand
    // completes, but ideally we'd want it to complete when execution resumes
    // runner.run.  Currently the distinction does not matter, but if it ever
    // does, this test might fail to catch a regression of
    // https://github.com/flutter/flutter/issues/56406.
    final Completer<void> commandCompleter = Completer<void>();
    testUsingContext('error handling crash report (asynchronous crash)', () async {
      final Completer<void> completer = Completer<void>();
      // runner.run() asynchronously calls the exit function set above, so we
      // catch it in a zone.
      unawaited(runZoned<Future<void>>(
        () {
          unawaited(runner.run(
            <String>['crash'],
118
            () => <FlutterCommand>[
119 120 121 122 123 124 125 126 127 128 129
              CrashingFlutterCommand(asyncCrash: true, completer: commandCompleter),
            ],
            // This flutterVersion disables crash reporting.
            flutterVersion: '[user-branch]/',
            reportCrashes: true,
          ));
          return null;
        },
        onError: (Object error, StackTrace stack) { // ignore: deprecated_member_use
          expect(firstExitCode, isNotNull);
          expect(firstExitCode, isNot(0));
130
          expect(error.toString(), 'Exception: test exit');
131 132 133 134 135 136 137 138 139
          completer.complete();
        },
      ));
      await completer.future;
    }, overrides: <Type, Generator>{
      Platform: () => FakePlatform(environment: <String, String>{
        'FLUTTER_ANALYTICS_LOG_FILE': 'test',
        'FLUTTER_ROOT': '/',
      }),
140
      FileSystem: () => MemoryFileSystem.test(),
141 142
      ProcessManager: () => FakeProcessManager.any(),
      CrashReporter: () => WaitingCrashReporter(commandCompleter.future),
143
      Artifacts: () => Artifacts.test(),
144
      HttpClientFactory: () => () => FakeHttpClient.any()
145 146
    });

147
    testUsingContext('create local report', () async {
148 149 150 151 152 153 154 155 156 157
      // Since crash reporting calls the doctor, which checks for the devtools
      // version file in the cache, write a version file to the memory fs.
      Cache.flutterRoot = '/path/to/flutter';
      final Directory devtoolsDir = globals.fs.directory(
        '${Cache.flutterRoot}/bin/cache/dart-sdk/bin/resources/devtools',
      )..createSync(recursive: true);
      devtoolsDir.childFile('version.json').writeAsStringSync(
        '{"version": "1.2.3"}',
      );

158 159 160 161 162 163
      final Completer<void> completer = Completer<void>();
      // runner.run() asynchronously calls the exit function set above, so we
      // catch it in a zone.
      unawaited(runZoned<Future<void>>(
        () {
        unawaited(runner.run(
164
          <String>['crash'],
165
          () => <FlutterCommand>[
166 167 168 169 170 171 172 173
            CrashingFlutterCommand(),
          ],
          // This flutterVersion disables crash reporting.
          flutterVersion: '[user-branch]/',
          reportCrashes: true,
        ));
        return null;
        },
174
        onError: (Object error, StackTrace stack) { // ignore: deprecated_member_use
175 176
          expect(firstExitCode, isNotNull);
          expect(firstExitCode, isNot(0));
177
          expect(error.toString(), 'Exception: test exit');
178 179 180 181 182 183
          completer.complete();
        },
      ));
      await completer.future;

      final String errorText = testLogger.errorText;
184 185
      expect(
        errorText,
186
        containsIgnoringWhitespace('Oops; flutter has exited unexpectedly: "Exception: an exception % --".\n'),
187
      );
188

189 190 191
      final File log = globals.fs.file('/flutter_01.log');
      final String logContents = log.readAsStringSync();
      expect(logContents, contains(kCustomBugInstructions));
192
      expect(logContents, contains('flutter crash'));
193
      expect(logContents, contains('Exception: an exception % --'));
194 195 196
      expect(logContents, contains('CrashingFlutterCommand.runCommand'));
      expect(logContents, contains('[✓] Flutter'));

197
      final CrashDetails sentDetails = (globals.crashReporter as WaitingCrashReporter)._details;
198
      expect(sentDetails.command, 'flutter crash');
199
      expect(sentDetails.error.toString(), 'Exception: an exception % --');
200
      expect(sentDetails.stackTrace.toString(), contains('CrashingFlutterCommand.runCommand'));
201
      expect(await sentDetails.doctorText.text, contains('[✓] Flutter'));
202 203 204 205 206
    }, overrides: <Type, Generator>{
      Platform: () => FakePlatform(
        environment: <String, String>{
          'FLUTTER_ANALYTICS_LOG_FILE': 'test',
          'FLUTTER_ROOT': '/',
207
        }
208
      ),
209
      FileSystem: () => MemoryFileSystem.test(),
210
      ProcessManager: () => FakeProcessManager.any(),
211
      UserMessages: () => CustomBugInstructions(),
212
      Artifacts: () => Artifacts.test(),
213 214
      CrashReporter: () => WaitingCrashReporter(Future<void>.value()),
      HttpClientFactory: () => () => FakeHttpClient.any()
215
    });
216 217 218 219
  });
}

class CrashingFlutterCommand extends FlutterCommand {
220 221 222 223 224 225 226 227 228
  CrashingFlutterCommand({
    bool asyncCrash = false,
    Completer<void> completer,
  }) :  _asyncCrash = asyncCrash,
        _completer = completer;

  final bool _asyncCrash;
  final Completer<void> _completer;

229 230 231 232
  @override
  String get description => null;

  @override
233
  String get name => 'crash';
234 235 236

  @override
  Future<FlutterCommandResult> runCommand() async {
237
    final Exception error = Exception('an exception % --'); // Test URL encoding.
238 239 240 241 242 243 244 245 246 247 248 249 250 251
    if (!_asyncCrash) {
      throw error;
    }

    final Completer<void> completer = Completer<void>();
    Timer.run(() {
      completer.complete();
      throw error;
    });

    await completer.future;
    _completer.complete();

    return FlutterCommandResult.success();
252 253 254 255
  }
}

class CrashingUsage implements Usage {
256 257 258 259
  CrashingUsage() : _impl = Usage(
    versionOverride: '[user-branch]',
    runningOnBot: true,
  );
260 261 262 263 264 265 266 267 268 269 270 271 272

  final Usage _impl;

  dynamic get sentException => _sentException;
  dynamic _sentException;

  bool _firstAttempt = true;

  // Crash while crashing.
  @override
  void sendException(dynamic exception) {
    if (_firstAttempt) {
      _firstAttempt = false;
273
      throw Exception('CrashingUsage.sendException');
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
    }
    _sentException = exception;
  }

  @override
  bool get suppressAnalytics => _impl.suppressAnalytics;

  @override
  set suppressAnalytics(bool value) {
    _impl.suppressAnalytics = value;
  }

  @override
  bool get enabled => _impl.enabled;

  @override
  set enabled(bool value) {
    _impl.enabled = value;
  }

  @override
  String get clientId => _impl.clientId;

  @override
298
  void sendCommand(String command, {CustomDimensions parameters}) =>
299 300 301
      _impl.sendCommand(command, parameters: parameters);

  @override
302 303 304
  void sendEvent(
    String category,
    String parameter, {
305
    String label,
306
    int value,
307
    CustomDimensions parameters,
308 309 310 311 312 313 314
  }) => _impl.sendEvent(
    category,
    parameter,
    label: label,
    value: value,
    parameters: parameters,
  );
315 316

  @override
317 318 319 320 321
  void sendTiming(
    String category,
    String variableName,
    Duration duration, {
    String label,
322 323 324 325 326 327 328 329 330 331 332
  }) => _impl.sendTiming(category, variableName, duration, label: label);

  @override
  Stream<Map<String, dynamic>> get onSend => _impl.onSend;

  @override
  Future<void> ensureAnalyticsSent() => _impl.ensureAnalyticsSent();

  @override
  void printWelcome() => _impl.printWelcome();
}
333 334 335 336 337

class CustomBugInstructions extends UserMessages {
  @override
  String get flutterToolBugInstructions => kCustomBugInstructions;
}
338 339 340 341 342 343 344 345 346

/// A fake [CrashReporter] that waits for a [Future] to complete.
///
/// Used to exacerbate a race between the success and failure paths of
/// [runner.run].  See https://github.com/flutter/flutter/issues/56406.
class WaitingCrashReporter implements CrashReporter {
  WaitingCrashReporter(Future<void> future) : _future = future;

  final Future<void> _future;
347
  CrashDetails _details;
348 349

  @override
350 351 352 353
  Future<void> informUser(CrashDetails details, File crashFile) {
    _details = details;
    return _future;
  }
354
}