runner_test.dart 7.22 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/base/common.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/platform.dart';
13
import 'package:flutter_tools/src/base/user_messages.dart';
14
import 'package:flutter_tools/src/cache.dart';
15
import 'package:flutter_tools/src/globals.dart' as globals;
16 17
import 'package:flutter_tools/src/reporting/reporting.dart';
import 'package:flutter_tools/src/runner/flutter_command.dart';
18
import 'package:mockito/mockito.dart';
19 20 21 22

import '../../src/common.dart';
import '../../src/context.dart';

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

25 26 27 28 29 30 31 32 33 34 35 36 37 38
void main() {
  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.
      io.setExitFunctionForTests((int _) { throw 'test exit';});
      Cache.disableLocking();
    });

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

39
    testUsingContext('error handling crash report', () async {
40 41 42
      final Completer<void> completer = Completer<void>();
      // runner.run() asynchronously calls the exit function set above, so we
      // catch it in a zone.
43 44
      unawaited(runZoned<Future<void>>(
        () {
45 46
          unawaited(runner.run(
            <String>['test'],
47
            () => <FlutterCommand>[
48 49 50 51 52 53 54 55
              CrashingFlutterCommand(),
            ],
            // This flutterVersion disables crash reporting.
            flutterVersion: '[user-branch]/',
            reportCrashes: true,
          ));
          return null;
        },
56
        onError: (Object error, StackTrace stack) { // ignore: deprecated_member_use
57 58
          expect(error, 'test exit');
          completer.complete();
59 60
        },
      ));
61 62 63 64 65 66 67 68
      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.
69
      final CrashingUsage crashingUsage = globals.flutterUsage as CrashingUsage;
70
      expect(crashingUsage.sentException, 'an exception % --');
71 72 73 74 75 76
    }, overrides: <Type, Generator>{
      Platform: () => FakePlatform(environment: <String, String>{
        'FLUTTER_ANALYTICS_LOG_FILE': 'test',
        'FLUTTER_ROOT': '/',
      }),
      FileSystem: () => MemoryFileSystem(),
77
      ProcessManager: () => FakeProcessManager.any(),
78 79
      Usage: () => CrashingUsage(),
    });
80

81
    testUsingContext('create local report', () async {
82 83 84 85 86 87 88
      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>['test'],
89
          () => <FlutterCommand>[
90 91 92 93 94 95 96 97
            CrashingFlutterCommand(),
          ],
          // This flutterVersion disables crash reporting.
          flutterVersion: '[user-branch]/',
          reportCrashes: true,
        ));
        return null;
        },
98
        onError: (Object error, StackTrace stack) { // ignore: deprecated_member_use
99 100 101 102 103 104 105
          expect(error, 'test exit');
          completer.complete();
        },
      ));
      await completer.future;

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

111 112 113 114 115 116 117 118 119 120 121 122 123 124
      final File log = globals.fs.file('/flutter_01.log');
      final String logContents = log.readAsStringSync();
      expect(logContents, contains(kCustomBugInstructions));
      expect(logContents, contains('flutter test'));
      expect(logContents, contains('String: an exception % --'));
      expect(logContents, contains('CrashingFlutterCommand.runCommand'));
      expect(logContents, contains('[✓] Flutter'));

      final VerificationResult argVerification = verify(globals.crashReporter.informUser(captureAny, any));
      final CrashDetails sentDetails = argVerification.captured.first as CrashDetails;
      expect(sentDetails.command, 'flutter test');
      expect(sentDetails.error, 'an exception % --');
      expect(sentDetails.stackTrace.toString(), contains('CrashingFlutterCommand.runCommand'));
      expect(sentDetails.doctorText, contains('[✓] Flutter'));
125 126 127 128 129 130 131 132 133 134
    }, overrides: <Type, Generator>{
      Platform: () => FakePlatform(
        environment: <String, String>{
          'FLUTTER_ANALYTICS_LOG_FILE': 'test',
          'FLUTTER_ROOT': '/',
        },
        operatingSystem: 'linux'
      ),
      FileSystem: () => MemoryFileSystem(),
      ProcessManager: () => FakeProcessManager.any(),
135
      UserMessages: () => CustomBugInstructions(),
136
    });
137 138 139 140 141 142 143 144 145 146 147 148
  });
}

class CrashingFlutterCommand extends FlutterCommand {
  @override
  String get description => null;

  @override
  String get name => 'test';

  @override
  Future<FlutterCommandResult> runCommand() async {
149
    throw 'an exception % --'; // Test URL encoding.
150 151 152 153
  }
}

class CrashingUsage implements Usage {
154 155 156 157
  CrashingUsage() : _impl = Usage(
    versionOverride: '[user-branch]',
    runningOnBot: true,
  );
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202

  final Usage _impl;

  dynamic get sentException => _sentException;
  dynamic _sentException;

  bool _firstAttempt = true;

  // Crash while crashing.
  @override
  void sendException(dynamic exception) {
    if (_firstAttempt) {
      _firstAttempt = false;
      throw 'sendException';
    }
    _sentException = exception;
  }

  @override
  bool get isFirstRun => _impl.isFirstRun;

  @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
  void sendCommand(String command, {Map<String, String> parameters}) =>
      _impl.sendCommand(command, parameters: parameters);

  @override
203 204 205
  void sendEvent(
    String category,
    String parameter, {
206
    String label,
207
    int value,
208
    Map<String, String> parameters,
209 210 211 212 213 214 215
  }) => _impl.sendEvent(
    category,
    parameter,
    label: label,
    value: value,
    parameters: parameters,
  );
216 217

  @override
218 219 220 221 222
  void sendTiming(
    String category,
    String variableName,
    Duration duration, {
    String label,
223 224 225 226 227 228 229 230 231 232 233
  }) => _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();
}
234 235 236 237 238

class CustomBugInstructions extends UserMessages {
  @override
  String get flutterToolBugInstructions => kCustomBugInstructions;
}