assertions_test.dart 19.3 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 'package:flutter/foundation.dart';
6
import 'package:flutter_test/flutter_test.dart';
7 8 9 10 11 12 13 14 15 16

import 'capture_output.dart';

void main() {
  test('debugPrintStack', () {
    final List<String> log = captureOutput(() {
      debugPrintStack(label: 'Example label', maxFrames: 7);
    });
    expect(log[0], contains('Example label'));
    expect(log[1], contains('debugPrintStack'));
17
  });
18 19 20

  test('debugPrintStack', () {
    final List<String> log = captureOutput(() {
21
      final FlutterErrorDetails details = FlutterErrorDetails(
22 23 24
        exception: 'Example exception',
        stack: StackTrace.current,
        library: 'Example library',
25 26 27
        context: ErrorDescription('Example context'),
        informationCollector: () sync* {
          yield ErrorDescription('Example information');
28 29 30 31 32 33 34 35 36 37 38 39 40 41
        },
      );

      FlutterError.dumpErrorToConsole(details);
    });

    expect(log[0], contains('EXAMPLE LIBRARY'));
    expect(log[1], contains('Example context'));
    expect(log[2], contains('Example exception'));

    final String joined = log.join('\n');

    expect(joined, contains('captureOutput'));
    expect(joined, contains('\nExample information\n'));
42
  });
43

44 45
  test('FlutterErrorDetails.toString', () {
    expect(
46
      FlutterErrorDetails(
47 48
        exception: 'MESSAGE',
        library: 'LIBRARY',
49 50 51
        context: ErrorDescription('CONTEXTING'),
        informationCollector: () sync* {
          yield ErrorDescription('INFO');
52 53
        },
      ).toString(),
54 55 56 57 58
        '══╡ EXCEPTION CAUGHT BY LIBRARY ╞════════════════════════════════\n'
        'The following message was thrown CONTEXTING:\n'
        'MESSAGE\n'
        '\n'
        'INFO\n'
59
        '═════════════════════════════════════════════════════════════════\n',
60 61
    );
    expect(
62
      FlutterErrorDetails(
63
        exception: NullThrownError(),
64
        library: 'LIBRARY',
65 66 67
        context: ErrorDescription('CONTEXTING'),
        informationCollector: () sync* {
          yield ErrorDescription('INFO');
68 69
        },
      ).toString(),
70
      '══╡ EXCEPTION CAUGHT BY LIBRARY ╞════════════════════════════════\n'
71
      'The null value was thrown CONTEXTING.\n'
72 73
      '\n'
      'INFO\n'
74
      '═════════════════════════════════════════════════════════════════\n',
75 76 77 78 79 80 81 82 83 84 85 86 87 88
    );
    expect(
      FlutterErrorDetails(
        exception: 'MESSAGE',
        context: ErrorDescription('CONTEXTING'),
        informationCollector: () sync* {
          yield ErrorDescription('INFO');
        },
      ).toString(),
        '══╡ EXCEPTION CAUGHT BY FLUTTER FRAMEWORK ╞══════════════════════\n'
        'The following message was thrown CONTEXTING:\n'
        'MESSAGE\n'
        '\n'
        'INFO\n'
89
        '═════════════════════════════════════════════════════════════════\n',
90 91
    );
    expect(
92
      FlutterErrorDetails(
93
        exception: 'MESSAGE',
94 95 96
        context: ErrorDescription('CONTEXTING ${'SomeContext(BlaBla)'}'),
        informationCollector: () sync* {
          yield ErrorDescription('INFO');
97 98
        },
      ).toString(),
99 100
      '══╡ EXCEPTION CAUGHT BY FLUTTER FRAMEWORK ╞══════════════════════\n'
      'The following message was thrown CONTEXTING SomeContext(BlaBla):\n'
101
      'MESSAGE\n'
102 103 104
      '\n'
      'INFO\n'
      '═════════════════════════════════════════════════════════════════\n',
105 106 107 108 109
    );
    expect(
      const FlutterErrorDetails(
        exception: 'MESSAGE',
      ).toString(),
110 111 112
      '══╡ EXCEPTION CAUGHT BY FLUTTER FRAMEWORK ╞══════════════════════\n'
      'The following message was thrown:\n'
      'MESSAGE\n'
113
      '═════════════════════════════════════════════════════════════════\n',
114 115
    );
    expect(
116
      FlutterErrorDetails(exception: NullThrownError()).toString(),
117
      '══╡ EXCEPTION CAUGHT BY FLUTTER FRAMEWORK ╞══════════════════════\n'
118
      'The null value was thrown.\n'
119
      '═════════════════════════════════════════════════════════════════\n',
120 121
    );
  });
122

123 124 125 126 127 128 129 130 131 132 133 134 135 136
  test('FlutterErrorDetails.toStringShort', () {
    expect(
        FlutterErrorDetails(
          exception: 'MESSAGE',
          library: 'library',
          context: ErrorDescription('CONTEXTING'),
          informationCollector: () sync* {
            yield ErrorDescription('INFO');
          },
        ).toStringShort(),
        'Exception caught by library',
    );
  });

137 138 139 140
  test('FlutterError default constructor', () {
    FlutterError error = FlutterError(
      'My Error Summary.\n'
      'My first description.\n'
141
      'My second description.',
142 143 144 145 146 147 148 149 150 151 152 153 154
    );
    expect(error.diagnostics.length, equals(3));
    expect(error.diagnostics[0].level, DiagnosticLevel.summary);
    expect(error.diagnostics[1].level, DiagnosticLevel.info);
    expect(error.diagnostics[2].level, DiagnosticLevel.info);
    expect(error.diagnostics[0].toString(), 'My Error Summary.');
    expect(error.diagnostics[1].toString(), 'My first description.');
    expect(error.diagnostics[2].toString(), 'My second description.');
    expect(
      error.toStringDeep(),
      'FlutterError\n'
      '   My Error Summary.\n'
      '   My first description.\n'
155
      '   My second description.\n',
156 157 158 159 160 161
    );

    error = FlutterError(
      'My Error Summary.\n'
      'My first description.\n'
      'My second description.\n'
162
      '\n',
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
    );

    expect(error.diagnostics.length, equals(5));
    expect(error.diagnostics[0].level, DiagnosticLevel.summary);
    expect(error.diagnostics[1].level, DiagnosticLevel.info);
    expect(error.diagnostics[2].level, DiagnosticLevel.info);
    expect(error.diagnostics[0].toString(), 'My Error Summary.');
    expect(error.diagnostics[1].toString(), 'My first description.');
    expect(error.diagnostics[2].toString(), 'My second description.');
    expect(error.diagnostics[3].toString(), '');
    expect(error.diagnostics[4].toString(), '');
    expect(
      error.toStringDeep(),
      'FlutterError\n'
      '   My Error Summary.\n'
      '   My first description.\n'
      '   My second description.\n'
      '\n'
181
      '\n',
182 183 184 185 186 187
    );

    error = FlutterError(
      'My Error Summary.\n'
      'My first description.\n'
      '\n'
188
      'My second description.',
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
    );
    expect(error.diagnostics.length, equals(4));
    expect(error.diagnostics[0].level, DiagnosticLevel.summary);
    expect(error.diagnostics[1].level, DiagnosticLevel.info);
    expect(error.diagnostics[2].level, DiagnosticLevel.info);
    expect(error.diagnostics[3].level, DiagnosticLevel.info);
    expect(error.diagnostics[0].toString(), 'My Error Summary.');
    expect(error.diagnostics[1].toString(), 'My first description.');
    expect(error.diagnostics[2].toString(), '');
    expect(error.diagnostics[3].toString(), 'My second description.');

    expect(
      error.toStringDeep(),
      'FlutterError\n'
      '   My Error Summary.\n'
      '   My first description.\n'
      '\n'
206
      '   My second description.\n',
207 208 209 210 211 212 213 214 215
    );
    error = FlutterError('My Error Summary.');
    expect(error.diagnostics.length, 1);
    expect(error.diagnostics.first.level, DiagnosticLevel.summary);
    expect(error.diagnostics.first.toString(), 'My Error Summary.');

    expect(
      error.toStringDeep(),
      'FlutterError\n'
216
      '   My Error Summary.\n',
217 218 219 220 221
    );
  });

  test('Malformed FlutterError objects', () {
    {
222
      final AssertionError error;
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
      try {
        throw FlutterError.fromParts(<DiagnosticsNode>[]);
      } on AssertionError catch (e) {
        error = e;
      }
      expect(
        FlutterErrorDetails(exception: error).toString(),
        '══╡ EXCEPTION CAUGHT BY FLUTTER FRAMEWORK ╞══════════════════════\n'
        'The following assertion was thrown:\n'
        'Empty FlutterError\n'
        '═════════════════════════════════════════════════════════════════\n',
      );
    }

    {
238
      final AssertionError error;
239 240
      try {
        throw FlutterError.fromParts(<DiagnosticsNode>[
241 242
          ErrorDescription('Error description without a summary'),
        ]);
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
      } on AssertionError catch (e) {
        error = e;
      }
      expect(
        FlutterErrorDetails(exception: error).toString(),
        '══╡ EXCEPTION CAUGHT BY FLUTTER FRAMEWORK ╞══════════════════════\n'
        'The following assertion was thrown:\n'
        'FlutterError is missing a summary.\n'
        'All FlutterError objects should start with a short (one line)\n'
        'summary description of the problem that was detected.\n'
        'Malformed FlutterError:\n'
        '  Error description without a summary\n'
        '\n'
        'This error should still help you solve your problem, however\n'
        'please also report this malformed error in the framework by\n'
        'filing a bug on GitHub:\n'
259
        '  https://github.com/flutter/flutter/issues/new?template=2_bug.md\n'
260 261 262 263 264
        '═════════════════════════════════════════════════════════════════\n',
      );
    }

    {
265
      final AssertionError error;
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
      try {
        throw FlutterError.fromParts(<DiagnosticsNode>[
          ErrorSummary('Error Summary A'),
          ErrorDescription('Some descriptionA'),
          ErrorSummary('Error Summary B'),
          ErrorDescription('Some descriptionB'),
        ]);
      } on AssertionError catch (e) {
        error = e;
      }
      expect(
        FlutterErrorDetails(exception: error).toString(),
        '══╡ EXCEPTION CAUGHT BY FLUTTER FRAMEWORK ╞══════════════════════\n'
        'The following assertion was thrown:\n'
        'FlutterError contained multiple error summaries.\n'
        'All FlutterError objects should have only a single short (one\n'
        'line) summary description of the problem that was detected.\n'
        'Malformed FlutterError:\n'
        '  Error Summary A\n'
        '  Some descriptionA\n'
        '  Error Summary B\n'
        '  Some descriptionB\n'
        '\n'
        'The malformed error has 2 summaries.\n'
        'Summary 1: Error Summary A\n'
        'Summary 2: Error Summary B\n'
        '\n'
        'This error should still help you solve your problem, however\n'
        'please also report this malformed error in the framework by\n'
        'filing a bug on GitHub:\n'
296
        '  https://github.com/flutter/flutter/issues/new?template=2_bug.md\n'
297 298 299 300 301
        '═════════════════════════════════════════════════════════════════\n',
      );
    }

    {
302
      final AssertionError error;
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
      try {
        throw FlutterError.fromParts(<DiagnosticsNode>[
          ErrorDescription('Some description'),
          ErrorSummary('Error summary'),
        ]);
      } on AssertionError catch (e) {
        error = e;
      }
      expect(
        FlutterErrorDetails(exception: error).toString(),
        '══╡ EXCEPTION CAUGHT BY FLUTTER FRAMEWORK ╞══════════════════════\n'
        'The following assertion was thrown:\n'
        'FlutterError is missing a summary.\n'
        'All FlutterError objects should start with a short (one line)\n'
        'summary description of the problem that was detected.\n'
        'Malformed FlutterError:\n'
        '  Some description\n'
        '  Error summary\n'
        '\n'
        'This error should still help you solve your problem, however\n'
        'please also report this malformed error in the framework by\n'
        'filing a bug on GitHub:\n'
325
        '  https://github.com/flutter/flutter/issues/new?template=2_bug.md\n'
326 327 328 329
        '═════════════════════════════════════════════════════════════════\n',
      );
    }
  });
330 331 332

  test('User-thrown exceptions have ErrorSummary properties', () {
    {
333
      final DiagnosticsNode node;
334 335 336 337 338 339 340 341 342 343
      try {
        throw 'User thrown string';
      } catch (e) {
        node = FlutterErrorDetails(exception: e).toDiagnosticsNode();
      }
      final ErrorSummary summary = node.getProperties().whereType<ErrorSummary>().single;
      expect(summary.value, equals(<String>['User thrown string']));
    }

    {
344
      final DiagnosticsNode node;
345 346 347 348 349 350 351 352 353
      try {
        throw ArgumentError.notNull('myArgument');
      } catch (e) {
        node = FlutterErrorDetails(exception: e).toDiagnosticsNode();
      }
      final ErrorSummary summary = node.getProperties().whereType<ErrorSummary>().single;
      expect(summary.value, equals(<String>['Invalid argument(s) (myArgument): Must not be null']));
    }
  });
354 355 356

  test('Identifies user fault', () {
    // User fault because they called `new Text(null)` from their own code.
357 358
    final StackTrace stack = StackTrace.fromString('''
#0      _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:42:39)
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
#1      _AssertionError._throwNew (dart:core-patch/errors_patch.dart:38:5)
#2      new Text (package:flutter/src/widgets/text.dart:287:10)
#3      _MyHomePageState.build (package:hello_flutter/main.dart:72:16)
#4      StatefulElement.build (package:flutter/src/widgets/framework.dart:4414:27)
#5      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4303:15)
#6      Element.rebuild (package:flutter/src/widgets/framework.dart:4027:5)
#7      ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4286:5)
#8      StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4461:11)
#9      ComponentElement.mount (package:flutter/src/widgets/framework.dart:4281:5)
#10      Element.inflateWidget (package:flutter/src/widgets/framework.dart:3276:14)
#11     Element.updateChild (package:flutter/src/widgets/framework.dart:3070:12)
#12     SingleChildRenderObjectElement.mount (package:flutter/blah.dart:999:9)''');

    final FlutterErrorDetails details = FlutterErrorDetails(
      exception: AssertionError('Test assertion'),
      stack: stack,
    );

    final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
    details.debugFillProperties(builder);

    expect(builder.properties.length, 4);
    expect(builder.properties[0].toString(), 'The following assertion was thrown:');
Dan Field's avatar
Dan Field committed
382
    expect(builder.properties[1].toString(), contains('Assertion failed'));
383 384 385 386 387 388 389 390 391
    expect(builder.properties[2] is ErrorSpacer, true);
    final DiagnosticsStackTrace trace = builder.properties[3] as DiagnosticsStackTrace;
    expect(trace, isNotNull);
    expect(trace.value, stack);
  });

  test('Identifies our fault', () {
    // Our fault because we should either have an assertion in `text_helper.dart`
    // or we should make sure not to pass bad values into new Text.
392 393
    final StackTrace stack = StackTrace.fromString('''
#0      _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:42:39)
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
#1      _AssertionError._throwNew (dart:core-patch/errors_patch.dart:38:5)
#2      new Text (package:flutter/src/widgets/text.dart:287:10)
#3      new SomeWidgetUsingText (package:flutter/src/widgets/text_helper.dart:287:10)
#4      _MyHomePageState.build (package:hello_flutter/main.dart:72:16)
#5      StatefulElement.build (package:flutter/src/widgets/framework.dart:4414:27)
#6      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4303:15)
#7      Element.rebuild (package:flutter/src/widgets/framework.dart:4027:5)
#8      ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4286:5)
#9      StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4461:11)
#10     ComponentElement.mount (package:flutter/src/widgets/framework.dart:4281:5)
#11     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3276:14)
#12     Element.updateChild (package:flutter/src/widgets/framework.dart:3070:12)
#13     SingleChildRenderObjectElement.mount (package:flutter/blah.dart:999:9)''');

    final FlutterErrorDetails details = FlutterErrorDetails(
      exception: AssertionError('Test assertion'),
      stack: stack,
    );

    final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
    details.debugFillProperties(builder);
    expect(builder.properties.length, 6);
    expect(builder.properties[0].toString(), 'The following assertion was thrown:');
Dan Field's avatar
Dan Field committed
417
    expect(builder.properties[1].toString(), contains('Assertion failed'));
418 419 420 421 422 423 424
    expect(builder.properties[2] is ErrorSpacer, true);
    expect(
      builder.properties[3].toString(),
      'Either the assertion indicates an error in the framework itself, or we should '
      'provide substantially more information in this error message to help you determine '
      'and fix the underlying cause.\n'
      'In either case, please report this assertion by filing a bug on GitHub:\n'
425
      '  https://github.com/flutter/flutter/issues/new?template=2_bug.md',
426 427 428 429 430 431
    );
    expect(builder.properties[4] is ErrorSpacer, true);
    final DiagnosticsStackTrace trace = builder.properties[5] as DiagnosticsStackTrace;
    expect(trace, isNotNull);
    expect(trace.value, stack);
  });
432 433 434 435 436 437 438 439 440 441

  test('RepetitiveStackFrameFilter does not go out of range', () {
    const RepetitiveStackFrameFilter filter = RepetitiveStackFrameFilter(
      frames: <PartialStackFrame>[
        PartialStackFrame(className: 'TestClass', method: 'test1', package: 'package:test/blah.dart'),
        PartialStackFrame(className: 'TestClass', method: 'test2', package: 'package:test/blah.dart'),
        PartialStackFrame(className: 'TestClass', method: 'test3', package: 'package:test/blah.dart'),
      ],
      replacement: 'test',
    );
442
    final List<String?> reasons = List<String?>.filled(2, null);
443 444 445 446 447 448 449
    filter.filter(
      const <StackFrame>[
        StackFrame(className: 'TestClass', method: 'test1', packageScheme: 'package', package: 'test', packagePath: 'blah.dart', line: 1, column: 1, number: 0, source: ''),
        StackFrame(className: 'TestClass', method: 'test2', packageScheme: 'package', package: 'test', packagePath: 'blah.dart', line: 1, column: 1, number: 0, source: ''),
      ],
      reasons,
    );
450
    expect(reasons, List<String?>.filled(2, null));
451
  });
452
}