crash_reporting_test.dart 6.34 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
import 'package:http/http.dart';
import 'package:http/testing.dart';

15
import 'package:flutter_tools/runner.dart' as tools;
16 17 18
import 'package:flutter_tools/src/base/context.dart';
import 'package:flutter_tools/src/base/io.dart';
import 'package:flutter_tools/src/base/logger.dart';
19
import 'package:flutter_tools/src/cache.dart';
20 21
import 'package:flutter_tools/src/crash_reporting.dart';
import 'package:flutter_tools/src/runner/flutter_command.dart';
22 23

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

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

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

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

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

      CrashReportSender.initializeWith(new MockClient((Request request) async {
        method = request.method;
        uri = request.url;
50 51 52 53 54

        // 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(
55
          utf8.decode(request.bodyBytes)
56 57 58 59 60 61 62 63 64 65
              .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),
66 67 68 69 70 71 72 73
          key: (dynamic key) {
            final List<String> pair = key;
            return pair[0];
          },
          value: (dynamic value) {
            final List<String> pair = value;
            return pair[1];
          }
74 75
        );

76 77 78 79 80 81
        return new Response(
            'test-report-id',
            200
        );
      }));

82
      final int exitCode = await tools.run(
83 84 85 86 87 88 89 90 91 92 93
        <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(
94 95 96
        scheme: 'https',
        host: 'clients2.google.com',
        port: 443,
97
        path: '/cr/report',
98 99 100 101 102
        queryParameters: <String, String>{
          'product': 'Flutter_Tools',
          'version' : 'test-version',
        },
      ));
103 104 105 106 107 108 109 110
      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');

111
      final BufferLogger logger = context[Logger];
112 113 114 115
      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.
116
      final List<String> writtenFiles =
117 118 119 120
        (await tools.crashFileSystem.directory('/').list(recursive: true).toList())
            .map((FileSystemEntity e) => e.path).toList();
      expect(writtenFiles, hasLength(1));
      expect(writtenFiles, contains('flutter_01.log'));
121 122
    }, overrides: <Type, Generator>{
      Stdio: () => const _NoStderr(),
123
    });
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 157 158 159 160 161 162

    testUsingContext('can override base URL', () async {
      Uri uri;
      CrashReportSender.initializeWith(new MockClient((Request request) async {
        uri = request.url;
        return new Response('test-report-id', 200);
      }));

      final int exitCode = await tools.run(
        <String>['crash'],
        <FlutterCommand>[new _CrashCommand()],
        reportCrashes: true,
        flutterVersion: 'test-version',
      );

      expect(exitCode, 1);

      // Verify that we sent the crash report.
      expect(uri, isNotNull);
      expect(uri, new Uri(
        scheme: 'https',
        host: 'localhost',
        port: 12345,
        path: '/fake_server',
        queryParameters: <String, String>{
          'product': 'Flutter_Tools',
          'version' : 'test-version',
        },
      ));
    }, overrides: <Type, Generator> {
      Platform: () => new FakePlatform(
        operatingSystem: 'linux',
        environment: <String, String>{
          'FLUTTER_CRASH_SERVER_BASE_URL': 'https://localhost:12345/fake_server',
        },
        script: new Uri(scheme: 'data'),
      ),
      Stdio: () => const _NoStderr(),
    });
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
  });
}

/// 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();
  }
}
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238

class _NoStderr extends Stdio {
  const _NoStderr();

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

class _NoopIOSink implements IOSink {
  const _NoopIOSink();

  @override
  Encoding get encoding => utf8;

  @override
  set encoding(_) => throw new UnsupportedError('');

  @override
  void add(_) {}

  @override
  void write(_) {}

  @override
  void writeAll(_, [__]) {}

  @override
  void writeln([_]) {}

  @override
  void writeCharCode(_) {}

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

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

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

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

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