crash_reporting_test.dart 4.4 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/src/base/platform.dart';
12 13 14 15 16 17 18 19
import 'package:http/http.dart';
import 'package:http/testing.dart';
import 'package:test/test.dart';

import 'package:flutter_tools/executable.dart' as tools;
import 'package:flutter_tools/src/base/context.dart';
import 'package:flutter_tools/src/base/io.dart';
import 'package:flutter_tools/src/base/logger.dart';
20
import 'package:flutter_tools/src/cache.dart';
21 22 23 24 25 26
import 'package:flutter_tools/src/crash_reporting.dart';
import 'package:flutter_tools/src/runner/flutter_command.dart';
import 'src/context.dart';

void main() {
  group('crash reporting', () {
27 28 29 30
    setUpAll(() {
      Cache.disableLocking();
    });

31 32
    setUp(() async {
      tools.crashFileSystem = new MemoryFileSystem();
33
      tools.writelnStderr = ([_]) { };
34 35 36 37
      setExitFunctionForTests((_) { });
    });

    tearDown(() {
38
      tools.crashFileSystem = const LocalFileSystem();
39
      tools.writelnStderr = stderr.writeln;
40 41 42 43 44 45
      restoreExitFunction();
    });

    testUsingContext('should send crash reports', () async {
      String method;
      Uri uri;
46
      Map<String, String> fields;
47 48 49 50

      CrashReportSender.initializeWith(new MockClient((Request request) async {
        method = request.method;
        uri = request.url;
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70

        // 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);
        fields = new Map<String, String>.fromIterable(
          UTF8.decode(request.bodyBytes)
              .split('--$boundary')
              .map<List<String>>((String part) {
                final Match nameMatch = new RegExp(r'name="(.*)"').firstMatch(part);
                if (nameMatch == null)
                  return null;
                final String name = nameMatch[1];
                final String value = part.split('\n').skip(2).join('\n').trim();
                return <String>[name, value];
              })
              .where((List<String> pair) => pair != null),
          key: (List<String> pair) => pair[0],
          value: (List<String> pair) => pair[1],
        );

71 72 73 74 75 76
        return new Response(
            'test-report-id',
            200
        );
      }));

77
      final int exitCode = await tools.run(
78 79 80 81 82 83 84 85 86 87 88
        <String>['crash'],
        <FlutterCommand>[new _CrashCommand()],
        reportCrashes: true,
        flutterVersion: 'test-version',
      );

      expect(exitCode, 1);

      // Verify that we sent the crash report.
      expect(method, 'POST');
      expect(uri, new Uri(
89 90 91
        scheme: 'https',
        host: 'clients2.google.com',
        port: 443,
92
        path: '/cr/report',
93 94 95 96 97
        queryParameters: <String, String>{
          'product': 'Flutter_Tools',
          'version' : 'test-version',
        },
      ));
98 99 100 101 102 103 104 105
      expect(fields['uuid'], '00000000-0000-4000-0000-000000000000');
      expect(fields['product'], 'Flutter_Tools');
      expect(fields['version'], 'test-version');
      expect(fields['osName'], platform.operatingSystem);
      expect(fields['osVersion'], 'fake OS name and version');
      expect(fields['type'], 'DartError');
      expect(fields['error_runtime_type'], 'StateError');

106
      final BufferLogger logger = context[Logger];
107 108 109 110
      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.
111
      final List<String> writtenFiles =
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
        (await tools.crashFileSystem.directory('/').list(recursive: true).toList())
            .map((FileSystemEntity e) => e.path).toList();
      expect(writtenFiles, hasLength(1));
      expect(writtenFiles, contains('flutter_01.log'));
    });
  });
}

/// 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
  Future<Null> runCommand() async {
    void fn1() {
      throw new StateError('Test bad state error');
    }

    void fn2() {
      fn1();
    }

    void fn3() {
      fn2();
    }

    fn3();
  }
}