crash_reporting_test.dart 12.7 KB
Newer Older
1 2 3 4 5
// Copyright 2017 The Chromium 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';
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 13 14
import 'package:flutter_tools/src/base/context.dart';
import 'package:flutter_tools/src/base/io.dart';
import 'package:flutter_tools/src/base/logger.dart';
15
import 'package:flutter_tools/src/base/platform.dart';
16
import 'package:flutter_tools/src/cache.dart';
17
import 'package:flutter_tools/src/doctor.dart';
18
import 'package:flutter_tools/src/reporting/reporting.dart';
19
import 'package:flutter_tools/src/runner/flutter_command.dart';
20 21
import 'package:http/http.dart';
import 'package:http/testing.dart';
22
import 'package:pedantic/pedantic.dart';
23
import 'package:quiver/testing/async.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 59 60
      await verifyCrashReportSent(requestInfo);
    }, overrides: <Type, Generator>{
      Stdio: () => const _NoStderr(),
    });
61

62 63 64 65 66 67 68 69 70 71 72 73 74 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
    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>{
      Stdio: () => const _NoStderr(),
    });

    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>{
      Stdio: () => const _NoStderr(),
    });

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 123
    }, overrides: <Type, Generator>{
      Stdio: () => const _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 154 155 156
    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(),
      Stdio: () => const _NoStderr(),
    });

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 184 185 186 187 188 189
    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);

      final BufferLogger logger = context.get<Logger>();
      expect(logger.statusText, '');
    }, overrides: <Type, Generator>{
      Stdio: () => const _NoStderr(),
    });

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

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

      expect(exitCode, 1);

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

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

238 239 240
Future<void> verifyCrashReportSent(RequestInfo crashInfo, {
  int crashes = 1,
}) async {
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
  // 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');
  expect(crashInfo.fields['osName'], platform.operatingSystem);
  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');
261
  expect(crashInfo.fields['comments'], 'crash');
262 263 264 265 266 267 268 269 270

  final BufferLogger logger = context.get<Logger>();
  expect(logger.statusText, 'Sending crash report to Google.\n'
      'Crash report sent (report ID: test-report-id)\n');

  // 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();
271
  expect(writtenFiles, hasLength(crashes));
272 273 274 275 276
  expect(writtenFiles, contains('flutter_01.log'));
}

class MockCrashReportSender extends MockClient {
  MockCrashReportSender(RequestInfo crashInfo) : super((Request request) async {
277 278 279 280 281 282 283 284 285 286 287
    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) {
288
          final Match nameMatch = RegExp(r'name="(.*)"').firstMatch(part);
289
          if (nameMatch == null) {
290
            return null;
291
          }
292 293 294 295
          final String name = nameMatch[1];
          final String value = part.split('\n').skip(2).join('\n').trim();
          return <String>[name, value];
        })
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
        .where((List<String> pair) => pair != null),
      key: (dynamic key) {
        final List<String> pair = key;
        return pair[0];
      },
      value: (dynamic value) {
        final List<String> pair = value;
        return pair[1];
      },
    );

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

  static int sendCalls = 0;
314 315
}

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

322 323 324 325 326 327 328 329 330 331
/// 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
332
  Future<FlutterCommandResult> runCommand() async {
333
    void fn1() {
334
      throw StateError('Test bad state error');
335 336 337 338 339 340 341 342 343 344 345
    }

    void fn2() {
      fn1();
    }

    void fn3() {
      fn2();
    }

    fn3();
346 347

    return null;
348 349
  }
}
350

351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
/// 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
  }
}

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 402 403
/// 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>[];
}

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

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

class _NoopIOSink implements IOSink {
  const _NoopIOSink();

  @override
  Encoding get encoding => utf8;

  @override
418
  set encoding(_) => throw UnsupportedError('');
419 420

  @override
421
  void add(_) { }
422 423

  @override
424
  void write(_) { }
425 426

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

  @override
430
  void writeln([ _ = '' ]) { }
431 432

  @override
433
  void writeCharCode(_) { }
434 435

  @override
436
  void addError(_, [ __ ]) { }
437 438

  @override
439
  Future<dynamic> addStream(_) async { }
440 441

  @override
442
  Future<dynamic> flush() async { }
443 444

  @override
445
  Future<dynamic> close() async { }
446 447

  @override
448
  Future<dynamic> get done async { }
449
}