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

import 'dart:async';

import 'package:file/memory.dart';
import 'package:flutter_tools/runner.dart' as runner;
9
import 'package:flutter_tools/src/artifacts.dart';
10 11
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/base/io.dart' as io;
12
import 'package:flutter_tools/src/base/net.dart';
13
import 'package:flutter_tools/src/base/platform.dart';
14
import 'package:flutter_tools/src/base/process.dart';
15
import 'package:flutter_tools/src/base/user_messages.dart';
16
import 'package:flutter_tools/src/cache.dart';
17
import 'package:flutter_tools/src/globals.dart' as globals;
18
import 'package:flutter_tools/src/reporting/crash_reporting.dart';
19 20 21 22 23
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';
24
import '../../src/fake_http_client.dart';
25

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

28
void main() {
29
  int? firstExitCode;
30
  late MemoryFileSystem fileSystem;
31

32 33 34 35
  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.
36
      //
37
      // Tests might trigger exit() multiple times. In real life, exit() would
38 39 40 41 42 43 44 45
      // 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.
46
        throw Exception('test exit');
47 48
      });

49
      Cache.disableLocking();
50
      fileSystem = MemoryFileSystem.test();
51 52 53 54 55 56 57
    });

    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
      unawaited(runZoned<Future<void>?>(
63
        () {
64
          unawaited(runner.run(
65
            <String>['crash'],
66
            () => <FlutterCommand>[
67 68 69 70 71
              CrashingFlutterCommand(),
            ],
            // This flutterVersion disables crash reporting.
            flutterVersion: '[user-branch]/',
            reportCrashes: true,
72
            shutdownHooks: ShutdownHooks(),
73 74 75
          ));
          return null;
        },
76
        onError: (Object error, StackTrace stack) { // ignore: deprecated_member_use
77 78
          expect(firstExitCode, isNotNull);
          expect(firstExitCode, isNot(0));
79
          expect(error.toString(), 'Exception: test exit');
80
          completer.complete();
81 82
        },
      ));
83 84 85 86 87 88 89 90
      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.
91
      final CrashingUsage crashingUsage = globals.flutterUsage as CrashingUsage;
92
      expect(crashingUsage.sentException.toString(), 'Exception: an exception % --');
93 94 95 96 97
    }, overrides: <Type, Generator>{
      Platform: () => FakePlatform(environment: <String, String>{
        'FLUTTER_ANALYTICS_LOG_FILE': 'test',
        'FLUTTER_ROOT': '/',
      }),
98
      FileSystem: () => fileSystem,
99
      ProcessManager: () => FakeProcessManager.any(),
100
      Usage: () => CrashingUsage(),
101
      Artifacts: () => Artifacts.test(),
102
      HttpClientFactory: () => () => FakeHttpClient.any(),
103
    });
104

105 106
    // This Completer completes when CrashingFlutterCommand.runCommand
    // completes, but ideally we'd want it to complete when execution resumes
107
    // runner.run. Currently the distinction does not matter, but if it ever
108 109 110 111 112 113 114
    // 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.
115
      unawaited(runZoned<Future<void>?>(
116 117 118
        () {
          unawaited(runner.run(
            <String>['crash'],
119
            () => <FlutterCommand>[
120 121 122 123 124
              CrashingFlutterCommand(asyncCrash: true, completer: commandCompleter),
            ],
            // This flutterVersion disables crash reporting.
            flutterVersion: '[user-branch]/',
            reportCrashes: true,
125
            shutdownHooks: ShutdownHooks(),
126 127 128 129 130 131
          ));
          return null;
        },
        onError: (Object error, StackTrace stack) { // ignore: deprecated_member_use
          expect(firstExitCode, isNotNull);
          expect(firstExitCode, isNot(0));
132
          expect(error.toString(), 'Exception: test exit');
133 134 135 136 137 138 139 140 141
          completer.complete();
        },
      ));
      await completer.future;
    }, overrides: <Type, Generator>{
      Platform: () => FakePlatform(environment: <String, String>{
        'FLUTTER_ANALYTICS_LOG_FILE': 'test',
        'FLUTTER_ROOT': '/',
      }),
142
      FileSystem: () => fileSystem,
143 144
      ProcessManager: () => FakeProcessManager.any(),
      CrashReporter: () => WaitingCrashReporter(commandCompleter.future),
145
      Artifacts: () => Artifacts.test(),
146
      HttpClientFactory: () => () => FakeHttpClient.any(),
147 148
    });

149
    testUsingContext('create local report', () async {
150 151 152 153 154 155 156 157 158 159
      // 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"}',
      );

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

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

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

200
      final CrashDetails sentDetails = (globals.crashReporter! as WaitingCrashReporter)._details;
201
      expect(sentDetails.command, 'flutter crash');
202
      expect(sentDetails.error.toString(), 'Exception: an exception % --');
203
      expect(sentDetails.stackTrace.toString(), contains('CrashingFlutterCommand.runCommand'));
204
      expect(await sentDetails.doctorText.text, contains('[!] Flutter'));
205 206 207 208 209
    }, overrides: <Type, Generator>{
      Platform: () => FakePlatform(
        environment: <String, String>{
          'FLUTTER_ANALYTICS_LOG_FILE': 'test',
          'FLUTTER_ROOT': '/',
210
        }
211
      ),
212
      FileSystem: () => fileSystem,
213
      ProcessManager: () => FakeProcessManager.any(),
214
      UserMessages: () => CustomBugInstructions(),
215
      Artifacts: () => Artifacts.test(),
216
      CrashReporter: () => WaitingCrashReporter(Future<void>.value()),
217
      HttpClientFactory: () => () => FakeHttpClient.any(),
218
    });
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314

    group('in directory without permission', () {
      setUp(() {
        bool inTestSetup = true;
        fileSystem = MemoryFileSystem(opHandle: (String context, FileSystemOp operation) {
          if (inTestSetup) {
            // Allow all operations during test setup.
            return;
          }
          const Set<FileSystemOp> disallowedOperations = <FileSystemOp>{
            FileSystemOp.create,
            FileSystemOp.delete,
            FileSystemOp.copy,
            FileSystemOp.write,
          };
          // Make current_directory not writable.
          if (context.startsWith('/current_directory') && disallowedOperations.contains(operation)) {
            throw FileSystemException('No permission, context = $context, operation = $operation');
          }
        });
        final Directory currentDirectory = fileSystem.directory('/current_directory');
        currentDirectory.createSync();
        fileSystem.currentDirectory = currentDirectory;
        inTestSetup = false;
      });
      testUsingContext('create local report in temporary directory', () async {
        // 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"}',
        );

        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'],
              () => <FlutterCommand>[
                CrashingFlutterCommand(),
              ],
              // This flutterVersion disables crash reporting.
              flutterVersion: '[user-branch]/',
              reportCrashes: true,
              shutdownHooks: ShutdownHooks(),
            ));
            return null;
          },
          onError: (Object error, StackTrace stack) { // ignore: deprecated_member_use
            expect(firstExitCode, isNotNull);
            expect(firstExitCode, isNot(0));
            expect(error.toString(), 'Exception: test exit');
            completer.complete();
          },
        ));
        await completer.future;

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

        final File log = globals.fs.systemTempDirectory.childFile('flutter_01.log');
        final String logContents = log.readAsStringSync();
        expect(logContents, contains(kCustomBugInstructions));
        expect(logContents, contains('flutter crash'));
        expect(logContents, contains('Exception: an exception % --'));
        expect(logContents, contains('CrashingFlutterCommand.runCommand'));
        expect(logContents, contains('[!] Flutter'));

        final CrashDetails sentDetails = (globals.crashReporter! as WaitingCrashReporter)._details;
        expect(sentDetails.command, 'flutter crash');
        expect(sentDetails.error.toString(), 'Exception: an exception % --');
        expect(sentDetails.stackTrace.toString(), contains('CrashingFlutterCommand.runCommand'));
        expect(await sentDetails.doctorText.text, contains('[!] Flutter'));
      }, overrides: <Type, Generator>{
        Platform: () => FakePlatform(
          environment: <String, String>{
            'FLUTTER_ANALYTICS_LOG_FILE': 'test',
            'FLUTTER_ROOT': '/',
          }
        ),
        FileSystem: () => fileSystem,
        ProcessManager: () => FakeProcessManager.any(),
        UserMessages: () => CustomBugInstructions(),
        Artifacts: () => Artifacts.test(),
        CrashReporter: () => WaitingCrashReporter(Future<void>.value()),
        HttpClientFactory: () => () => FakeHttpClient.any(),
      });
    });
315 316 317 318
  });
}

class CrashingFlutterCommand extends FlutterCommand {
319 320
  CrashingFlutterCommand({
    bool asyncCrash = false,
321
    Completer<void>? completer,
322 323 324 325
  }) :  _asyncCrash = asyncCrash,
        _completer = completer;

  final bool _asyncCrash;
326
  final Completer<void>? _completer;
327

328
  @override
329
  String get description => '';
330 331

  @override
332
  String get name => 'crash';
333 334 335

  @override
  Future<FlutterCommandResult> runCommand() async {
336
    final Exception error = Exception('an exception % --'); // Test URL encoding.
337 338 339 340 341 342 343 344 345 346 347
    if (!_asyncCrash) {
      throw error;
    }

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

    await completer.future;
348
    _completer!.complete();
349 350

    return FlutterCommandResult.success();
351 352 353 354
  }
}

class CrashingUsage implements Usage {
355 356 357 358
  CrashingUsage() : _impl = Usage(
    versionOverride: '[user-branch]',
    runningOnBot: true,
  );
359 360 361 362 363 364 365 366 367 368 369 370 371

  final Usage _impl;

  dynamic get sentException => _sentException;
  dynamic _sentException;

  bool _firstAttempt = true;

  // Crash while crashing.
  @override
  void sendException(dynamic exception) {
    if (_firstAttempt) {
      _firstAttempt = false;
372
      throw Exception('CrashingUsage.sendException');
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
    }
    _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
397
  void sendCommand(String command, {CustomDimensions? parameters}) =>
398 399 400
      _impl.sendCommand(command, parameters: parameters);

  @override
401 402 403
  void sendEvent(
    String category,
    String parameter, {
404 405 406
    String? label,
    int? value,
    CustomDimensions? parameters,
407 408 409 410 411 412 413
  }) => _impl.sendEvent(
    category,
    parameter,
    label: label,
    value: value,
    parameters: parameters,
  );
414 415

  @override
416 417 418 419
  void sendTiming(
    String category,
    String variableName,
    Duration duration, {
420
    String? label,
421 422 423 424 425 426 427 428 429 430 431
  }) => _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();
}
432 433 434 435 436

class CustomBugInstructions extends UserMessages {
  @override
  String get flutterToolBugInstructions => kCustomBugInstructions;
}
437 438 439 440

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

  final Future<void> _future;
446
  late CrashDetails _details;
447 448

  @override
449 450 451 452
  Future<void> informUser(CrashDetails details, File crashFile) {
    _details = details;
    return _future;
  }
453
}