crash_reporting_test.dart 12.7 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5
// 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:convert';
7 8 9 10

import 'package:file/file.dart';
import 'package:file/local.dart';
import 'package:file/memory.dart';
11
import 'package:flutter_tools/runner.dart' as tools;
12
import 'package:flutter_tools/src/base/common.dart';
13 14
import 'package:flutter_tools/src/base/context.dart';
import 'package:flutter_tools/src/base/io.dart';
15
import 'package:flutter_tools/src/cache.dart';
16
import 'package:flutter_tools/src/doctor.dart';
17
import 'package:flutter_tools/src/reporting/reporting.dart';
18
import 'package:flutter_tools/src/runner/flutter_command.dart';
19
import 'package:flutter_tools/src/globals.dart' as globals;
20 21
import 'package:http/http.dart';
import 'package:http/testing.dart';
22
import 'package:quiver/testing/async.dart';
23
import 'package:platform/platform.dart';
24

25 26
import '../src/common.dart';
import '../src/context.dart';
27 28 29

void main() {
  group('crash reporting', () {
30 31 32 33
    setUpAll(() {
      Cache.disableLocking();
    });

34
    setUp(() async {
35
      tools.crashFileSystem = MemoryFileSystem();
36
      setExitFunctionForTests((_) { });
37
      MockCrashReportSender.sendCalls = 0;
38 39 40
    });

    tearDown(() {
41
      tools.crashFileSystem = const LocalFileSystem();
42 43 44 45
      restoreExitFunction();
    });

    testUsingContext('should send crash reports', () async {
46
      final RequestInfo requestInfo = RequestInfo();
47

48
      CrashReportSender.initializeWith(MockCrashReportSender(requestInfo));
49
      final int exitCode = await tools.run(
50
        <String>['crash'],
51
        <FlutterCommand>[_CrashCommand()],
52 53 54 55 56
        reportCrashes: true,
        flutterVersion: 'test-version',
      );
      expect(exitCode, 1);

57 58
      await verifyCrashReportSent(requestInfo);
    }, overrides: <Type, Generator>{
59
      Stdio: () => _NoStderr(),
60
    });
61

62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
    testUsingContext('should print an explanatory message when there is a SocketException', () async {
      final Completer<int> exitCodeCompleter = Completer<int>();
      setExitFunctionForTests((int exitCode) {
        exitCodeCompleter.complete(exitCode);
      });

      CrashReportSender.initializeWith(
          CrashingCrashReportSender(const SocketException('no internets')));

      unawaited(tools.run(
        <String>['crash'],
        <FlutterCommand>[_CrashAsyncCommand()],
        reportCrashes: true,
        flutterVersion: 'test-version',
      ));
      expect(await exitCodeCompleter.future, 1);
      expect(testLogger.errorText, contains('Failed to send crash report due to a network error'));
    }, overrides: <Type, Generator>{
80
      Stdio: () => _NoStderr(),
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
    });

    testUsingContext('should print an explanatory message when there is an HttpException', () async {
      final Completer<int> exitCodeCompleter = Completer<int>();
      setExitFunctionForTests((int exitCode) {
        exitCodeCompleter.complete(exitCode);
      });

      CrashReportSender.initializeWith(
          CrashingCrashReportSender(const HttpException('no internets')));

      unawaited(tools.run(
        <String>['crash'],
        <FlutterCommand>[_CrashAsyncCommand()],
        reportCrashes: true,
        flutterVersion: 'test-version',
      ));
      expect(await exitCodeCompleter.future, 1);
      expect(testLogger.errorText, contains('Failed to send crash report due to a network error'));
    }, overrides: <Type, Generator>{
101
      Stdio: () => _NoStderr(),
102 103
    });

104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
    testUsingContext('should send crash reports when async throws', () async {
      final Completer<int> exitCodeCompleter = Completer<int>();
      setExitFunctionForTests((int exitCode) {
        exitCodeCompleter.complete(exitCode);
      });

      final RequestInfo requestInfo = RequestInfo();

      CrashReportSender.initializeWith(MockCrashReportSender(requestInfo));

      unawaited(tools.run(
        <String>['crash'],
        <FlutterCommand>[_CrashAsyncCommand()],
        reportCrashes: true,
        flutterVersion: 'test-version',
      ));
120
      expect(await exitCodeCompleter.future, 1);
121
      await verifyCrashReportSent(requestInfo);
122
    }, overrides: <Type, Generator>{
123
      Stdio: () => _NoStderr(),
124
    });
125

126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
    testUsingContext('should send only one crash report when async throws many', () async {
      final Completer<int> exitCodeCompleter = Completer<int>();
      setExitFunctionForTests((int exitCode) {
        if (!exitCodeCompleter.isCompleted) {
          exitCodeCompleter.complete(exitCode);
        }
      });

      final RequestInfo requestInfo = RequestInfo();
      final MockCrashReportSender sender = MockCrashReportSender(requestInfo);
      CrashReportSender.initializeWith(sender);

      FakeAsync().run((FakeAsync time) {
        time.elapse(const Duration(seconds: 1));
        unawaited(tools.run(
          <String>['crash'],
          <FlutterCommand>[_MultiCrashAsyncCommand(crashes: 4)],
          reportCrashes: true,
          flutterVersion: 'test-version',
        ));
        time.elapse(const Duration(seconds: 1));
        time.flushMicrotasks();
      });
      expect(await exitCodeCompleter.future, 1);
      expect(MockCrashReportSender.sendCalls, 1);
      await verifyCrashReportSent(requestInfo, crashes: 4);
    }, overrides: <Type, Generator>{
      DoctorValidatorsProvider: () => FakeDoctorValidatorsProvider(),
154
      Stdio: () => _NoStderr(),
155 156
    });

157 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
    testUsingContext('should not send a crash report if on a user-branch', () async {
      String method;
      Uri uri;

      CrashReportSender.initializeWith(MockClient((Request request) async {
        method = request.method;
        uri = request.url;

        return Response(
          'test-report-id',
          200,
        );
      }));

      final int exitCode = await tools.run(
        <String>['crash'],
        <FlutterCommand>[_CrashCommand()],
        reportCrashes: true,
        flutterVersion: '[user-branch]/v1.2.3',
      );

      expect(exitCode, 1);

      // Verify that the report wasn't sent
      expect(method, null);
      expect(uri, null);

184
      expect(testLogger.traceText, isNot(contains('Crash report sent')));
185
    }, overrides: <Type, Generator>{
186
      Stdio: () => _NoStderr(),
187 188
    });

189 190
    testUsingContext('can override base URL', () async {
      Uri uri;
191
      CrashReportSender.initializeWith(MockClient((Request request) async {
192
        uri = request.url;
193
        return Response('test-report-id', 200);
194 195 196 197
      }));

      final int exitCode = await tools.run(
        <String>['crash'],
198
        <FlutterCommand>[_CrashCommand()],
199 200 201 202 203 204 205 206
        reportCrashes: true,
        flutterVersion: 'test-version',
      );

      expect(exitCode, 1);

      // Verify that we sent the crash report.
      expect(uri, isNotNull);
207
      expect(uri, Uri(
208 209 210 211 212 213
        scheme: 'https',
        host: 'localhost',
        port: 12345,
        path: '/fake_server',
        queryParameters: <String, String>{
          'product': 'Flutter_Tools',
214
          'version': 'test-version',
215 216
        },
      ));
217
    }, overrides: <Type, Generator>{
218
      Platform: () => FakePlatform(
219 220
        operatingSystem: 'linux',
        environment: <String, String>{
221
          'HOME': '/',
222 223
          'FLUTTER_CRASH_SERVER_BASE_URL': 'https://localhost:12345/fake_server',
        },
224
        script: Uri(scheme: 'data'),
225
      ),
226
      Stdio: () => _NoStderr(),
227
    });
228 229 230
  });
}

231 232 233 234 235 236
class RequestInfo {
  String method;
  Uri uri;
  Map<String, String> fields;
}

237 238 239
Future<void> verifyCrashReportSent(RequestInfo crashInfo, {
  int crashes = 1,
}) async {
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
  // Verify that we sent the crash report.
  expect(crashInfo.method, 'POST');
  expect(crashInfo.uri, Uri(
    scheme: 'https',
    host: 'clients2.google.com',
    port: 443,
    path: '/cr/report',
    queryParameters: <String, String>{
      'product': 'Flutter_Tools',
      'version': 'test-version',
    },
  ));
  expect(crashInfo.fields['uuid'], '00000000-0000-4000-0000-000000000000');
  expect(crashInfo.fields['product'], 'Flutter_Tools');
  expect(crashInfo.fields['version'], 'test-version');
255
  expect(crashInfo.fields['osName'], globals.platform.operatingSystem);
256 257 258 259
  expect(crashInfo.fields['osVersion'], 'fake OS name and version');
  expect(crashInfo.fields['type'], 'DartError');
  expect(crashInfo.fields['error_runtime_type'], 'StateError');
  expect(crashInfo.fields['error_message'], 'Bad state: Test bad state error');
260
  expect(crashInfo.fields['comments'], 'crash');
261

262 263
  expect(testLogger.traceText, contains('Sending crash report to Google.'));
  expect(testLogger.traceText, contains('Crash report sent (report ID: test-report-id)'));
264 265 266 267 268

  // Verify that we've written the crash report to disk.
  final List<String> writtenFiles =
  (await tools.crashFileSystem.directory('/').list(recursive: true).toList())
      .map((FileSystemEntity e) => e.path).toList();
269
  expect(writtenFiles, hasLength(crashes));
270 271 272 273 274
  expect(writtenFiles, contains('flutter_01.log'));
}

class MockCrashReportSender extends MockClient {
  MockCrashReportSender(RequestInfo crashInfo) : super((Request request) async {
275 276 277 278 279 280 281 282 283 284 285
    MockCrashReportSender.sendCalls++;
    crashInfo.method = request.method;
    crashInfo.uri = request.url;

    // A very ad-hoc multipart request parser. Good enough for this test.
    String boundary = request.headers['Content-Type'];
    boundary = boundary.substring(boundary.indexOf('boundary=') + 9);
    crashInfo.fields = Map<String, String>.fromIterable(
      utf8.decode(request.bodyBytes)
        .split('--$boundary')
        .map<List<String>>((String part) {
286
          final Match nameMatch = RegExp(r'name="(.*)"').firstMatch(part);
287
          if (nameMatch == null) {
288
            return null;
289
          }
290 291 292 293
          final String name = nameMatch[1];
          final String value = part.split('\n').skip(2).join('\n').trim();
          return <String>[name, value];
        })
294 295
        .where((List<String> pair) => pair != null),
      key: (dynamic key) {
296
        final List<String> pair = key as List<String>;
297 298 299
        return pair[0];
      },
      value: (dynamic value) {
300
        final List<String> pair = value as List<String>;
301 302 303 304 305 306 307 308 309
        return pair[1];
      },
    );

    return Response(
      'test-report-id',
      200,
    );
  });
310 311

  static int sendCalls = 0;
312 313
}

314
class CrashingCrashReportSender extends MockClient {
315
  CrashingCrashReportSender(Object exception) : super((Request request) async {
316 317 318 319
    throw exception;
  });
}

320 321 322 323 324 325 326 327 328 329
/// Throws a random error to simulate a CLI crash.
class _CrashCommand extends FlutterCommand {

  @override
  String get description => 'Simulates a crash';

  @override
  String get name => 'crash';

  @override
330
  Future<FlutterCommandResult> runCommand() async {
331
    void fn1() {
332
      throw StateError('Test bad state error');
333 334 335 336 337 338 339 340 341 342 343
    }

    void fn2() {
      fn1();
    }

    void fn3() {
      fn2();
    }

    fn3();
344

345
    return FlutterCommandResult.success();
346 347
  }
}
348

349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
/// Throws StateError from async callback.
class _CrashAsyncCommand extends FlutterCommand {

  @override
  String get description => 'Simulates a crash';

  @override
  String get name => 'crash';

  @override
  Future<FlutterCommandResult> runCommand() async {
    Timer.run(() {
      throw StateError('Test bad state error');
    });
    return Completer<FlutterCommandResult>().future; // expect StateError
  }
}

367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
/// Generates multiple asynchronous unhandled exceptions.
class _MultiCrashAsyncCommand extends FlutterCommand {
  _MultiCrashAsyncCommand({
    int crashes = 1,
  }) : _crashes = crashes;

  final int _crashes;

  @override
  String get description => 'Simulates a crash';

  @override
  String get name => 'crash';

  @override
  Future<FlutterCommandResult> runCommand() async {
    for (int i = 0; i < _crashes; i++) {
      Timer.run(() {
        throw StateError('Test bad state error');
      });
    }
    return Completer<FlutterCommandResult>().future; // expect StateError
  }
}

/// A DoctorValidatorsProvider that overrides the default validators without
/// overriding the doctor.
class FakeDoctorValidatorsProvider implements DoctorValidatorsProvider {
  @override
  List<DoctorValidator> get validators => <DoctorValidator>[];

  @override
  List<Workflow> get workflows => <Workflow>[];
}

402
class _NoStderr extends Stdio {
403
  _NoStderr();
404 405 406 407 408 409 410 411 412 413 414 415

  @override
  IOSink get stderr => const _NoopIOSink();
}

class _NoopIOSink implements IOSink {
  const _NoopIOSink();

  @override
  Encoding get encoding => utf8;

  @override
416
  set encoding(_) => throw UnsupportedError('');
417 418

  @override
419
  void add(_) { }
420 421

  @override
422
  void write(_) { }
423 424

  @override
425
  void writeAll(_, [ __ = '' ]) { }
426 427

  @override
428
  void writeln([ _ = '' ]) { }
429 430

  @override
431
  void writeCharCode(_) { }
432 433

  @override
434
  void addError(_, [ __ ]) { }
435 436

  @override
437
  Future<dynamic> addStream(_) async { }
438 439

  @override
440
  Future<dynamic> flush() async { }
441 442

  @override
443
  Future<dynamic> close() async { }
444 445

  @override
446
  Future<dynamic> get done async { }
447
}