logger_test.dart 48.8 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
import 'dart:async';
6
import 'dart:convert';
7

8
import 'package:fake_async/fake_async.dart';
9
import 'package:flutter_tools/executable.dart';
10
import 'package:flutter_tools/src/base/io.dart';
11
import 'package:flutter_tools/src/base/logger.dart';
12
import 'package:flutter_tools/src/base/platform.dart';
13
import 'package:flutter_tools/src/base/terminal.dart';
14
import 'package:flutter_tools/src/commands/daemon.dart';
15
import 'package:test/fake.dart';
16

17
import '../../src/common.dart';
18
import '../../src/fakes.dart';
19

20
final Platform _kNoAnsiPlatform = FakePlatform();
21 22 23 24
final String red = RegExp.escape(AnsiTerminal.red);
final String bold = RegExp.escape(AnsiTerminal.bold);
final String resetBold = RegExp.escape(AnsiTerminal.resetBold);
final String resetColor = RegExp.escape(AnsiTerminal.resetColor);
25

26
void main() {
27
  testWithoutContext('correct logger instance is created', () {
28 29
    final LoggerFactory loggerFactory = LoggerFactory(
      terminal: Terminal.test(),
30
      stdio: FakeStdio(),
31 32 33 34 35
      outputPreferences: OutputPreferences.test(),
    );

    expect(loggerFactory.createLogger(
      verbose: false,
36
      prefixedErrors: false,
37
      machine: false,
38 39
      daemon: false,
      windows: false,
40
    ), isA<StdoutLogger>());
41 42 43
    expect(loggerFactory.createLogger(
      verbose: false,
      prefixedErrors: false,
44
      machine: false,
45 46
      daemon: false,
      windows: true,
47
    ), isA<WindowsStdoutLogger>());
48 49 50
    expect(loggerFactory.createLogger(
      verbose: true,
      prefixedErrors: false,
51
      machine: false,
52 53
      daemon: false,
      windows: true,
54
    ), isA<VerboseLogger>());
55 56 57
    expect(loggerFactory.createLogger(
      verbose: true,
      prefixedErrors: false,
58
      machine: false,
59 60
      daemon: false,
      windows: false,
61
    ), isA<VerboseLogger>());
62 63 64
    expect(loggerFactory.createLogger(
      verbose: false,
      prefixedErrors: true,
65
      machine: false,
66 67
      daemon: false,
      windows: false,
68
    ), isA<PrefixedErrorLogger>());
69 70 71
    expect(loggerFactory.createLogger(
      verbose: false,
      prefixedErrors: false,
72
      machine: false,
73 74
      daemon: true,
      windows: false,
75
    ), isA<NotifyingLogger>());
76 77
    expect(loggerFactory.createLogger(
      verbose: false,
78
      prefixedErrors: false,
79
      machine: true,
80 81
      daemon: false,
      windows: false,
82
    ), isA<AppRunLogger>());
83 84
  });

85 86 87 88 89
  testWithoutContext('WindowsStdoutLogger rewrites emojis when terminal does not support emoji', () {
    final FakeStdio stdio = FakeStdio();
    final WindowsStdoutLogger logger = WindowsStdoutLogger(
      outputPreferences: OutputPreferences.test(),
      stdio: stdio,
90
      terminal: Terminal.test(),
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
    );

    logger.printStatus('🔥🖼️✗✓🔨💪✏️');

    expect(stdio.writtenToStdout, <String>['X√\n']);
  });

  testWithoutContext('WindowsStdoutLogger does not rewrite emojis when terminal does support emoji', () {
    final FakeStdio stdio = FakeStdio();
    final WindowsStdoutLogger logger = WindowsStdoutLogger(
      outputPreferences: OutputPreferences.test(),
      stdio: stdio,
      terminal: Terminal.test(supportsColor: true, supportsEmoji: true),
    );

    logger.printStatus('🔥🖼️✗✓🔨💪✏️');

    expect(stdio.writtenToStdout, <String>['🔥🖼️✗✓🔨💪✏️\n']);
  });

111 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 146 147 148 149 150 151 152 153 154 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 184 185 186 187 188 189 190 191 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
  testWithoutContext('DelegatingLogger delegates', () {
    final FakeLogger fakeLogger = FakeLogger();
    final DelegatingLogger delegatingLogger = DelegatingLogger(fakeLogger);

    expect(
      () => delegatingLogger.quiet,
      _throwsInvocationFor(() => fakeLogger.quiet),
    );

    expect(
      () => delegatingLogger.quiet = true,
      _throwsInvocationFor(() => fakeLogger.quiet = true),
    );

    expect(
      () => delegatingLogger.hasTerminal,
      _throwsInvocationFor(() => fakeLogger.hasTerminal),
    );

    expect(
      () => delegatingLogger.isVerbose,
      _throwsInvocationFor(() => fakeLogger.isVerbose),
    );

    const String message = 'message';
    final StackTrace stackTrace = StackTrace.current;
    const bool emphasis = true;
    const TerminalColor color = TerminalColor.cyan;
    const int indent = 88;
    const int hangingIndent = 52;
    const bool wrap = true;
    const bool newline = true;
    expect(
      () => delegatingLogger.printError(message,
        stackTrace: stackTrace,
        emphasis: emphasis,
        color: color,
        indent: indent,
        hangingIndent: hangingIndent,
        wrap: wrap,
      ),
      _throwsInvocationFor(() => fakeLogger.printError(message,
        stackTrace: stackTrace,
        emphasis: emphasis,
        color: color,
        indent: indent,
        hangingIndent: hangingIndent,
        wrap: wrap,
      )),
    );

    expect(
      () => delegatingLogger.printStatus(message,
        emphasis: emphasis,
        color: color,
        newline: newline,
        indent: indent,
        hangingIndent: hangingIndent,
        wrap: wrap,
      ),
      _throwsInvocationFor(() => fakeLogger.printStatus(message,
        emphasis: emphasis,
        color: color,
        newline: newline,
        indent: indent,
        hangingIndent: hangingIndent,
        wrap: wrap,
      )),
    );

    expect(
      () => delegatingLogger.printTrace(message),
      _throwsInvocationFor(() => fakeLogger.printTrace(message)),
    );

    final Map<String, dynamic> eventArgs = <String, dynamic>{};
    expect(
      () => delegatingLogger.sendEvent(message, eventArgs),
    _throwsInvocationFor(() => fakeLogger.sendEvent(message, eventArgs)),
    );

    const String progressId = 'progressId';
    const int progressIndicatorPadding = kDefaultStatusPadding * 2;
    expect(
      () => delegatingLogger.startProgress(message,
        progressId: progressId,
        progressIndicatorPadding: progressIndicatorPadding,
      ),
      _throwsInvocationFor(() => fakeLogger.startProgress(message,
          progressId: progressId,
          progressIndicatorPadding: progressIndicatorPadding,
      )),
    );

    expect(
      () => delegatingLogger.supportsColor,
      _throwsInvocationFor(() => fakeLogger.supportsColor),
    );

    expect(
      () => delegatingLogger.clear(),
      _throwsInvocationFor(() => fakeLogger.clear()),
    );
  });

  testWithoutContext('asLogger finds the correct delegate', () async {
    final FakeLogger fakeLogger = FakeLogger();
    final VerboseLogger verboseLogger = VerboseLogger(fakeLogger);
    final NotifyingLogger notifyingLogger =
        NotifyingLogger(verbose: true, parent: verboseLogger);
    expect(asLogger<Logger>(notifyingLogger), notifyingLogger);
    expect(asLogger<NotifyingLogger>(notifyingLogger), notifyingLogger);
    expect(asLogger<VerboseLogger>(notifyingLogger), verboseLogger);
    expect(asLogger<FakeLogger>(notifyingLogger), fakeLogger);

    expect(
      () => asLogger<AppRunLogger>(notifyingLogger),
228
      throwsStateError,
229 230 231
    );
  });

232
  group('AppContext', () {
233
    late FakeStopwatch fakeStopWatch;
234 235 236 237

    setUp(() {
      fakeStopWatch = FakeStopwatch();
    });
238

239
    testWithoutContext('error', () async {
240
      final BufferLogger mockLogger = BufferLogger.test(
241
        outputPreferences: OutputPreferences.test(),
242
      );
243 244
      final VerboseLogger verboseLogger = VerboseLogger(
        mockLogger,
245
        stopwatchFactory: FakeStopwatchFactory(stopwatch: fakeStopWatch),
246
      );
247 248 249

      verboseLogger.printStatus('Hey Hey Hey Hey');
      verboseLogger.printTrace('Oooh, I do I do I do');
250 251
      final StackTrace stackTrace = StackTrace.current;
      verboseLogger.printError('Helpless!', stackTrace: stackTrace);
252

253 254
      expect(mockLogger.statusText, matches(r'^\[ (?: {0,2}\+[0-9]{1,4} ms|       )\] Hey Hey Hey Hey\n'
                                             r'\[ (?: {0,2}\+[0-9]{1,4} ms|       )\] Oooh, I do I do I do\n$'));
255
      expect(mockLogger.traceText, '');
256 257 258
      expect(mockLogger.errorText, matches( r'^\[ (?: {0,2}\+[0-9]{1,4} ms|       )\] Helpless!\n'));
      final String lastLine = LineSplitter.split(stackTrace.toString()).toList().last;
      expect(mockLogger.errorText, endsWith('$lastLine\n\n'));
259
    });
260

261 262 263
    testWithoutContext('ANSI colored errors', () async {
      final BufferLogger mockLogger = BufferLogger(
        terminal: AnsiTerminal(
264
          stdio:  FakeStdio(),
265
          platform: FakePlatform(stdoutSupportsAnsi: true),
266 267 268
        ),
        outputPreferences: OutputPreferences.test(showColor: true),
      );
269
      final VerboseLogger verboseLogger = VerboseLogger(
270
        mockLogger, stopwatchFactory: FakeStopwatchFactory(stopwatch: fakeStopWatch),
271
      );
272 273 274 275 276 277 278

      verboseLogger.printStatus('Hey Hey Hey Hey');
      verboseLogger.printTrace('Oooh, I do I do I do');
      verboseLogger.printError('Helpless!');

      expect(
          mockLogger.statusText,
279 280
          matches(r'^\[ (?: {0,2}\+[0-9]{1,4} ms|       )\] ' '${bold}Hey Hey Hey Hey$resetBold'
                  r'\n\[ (?: {0,2}\+[0-9]{1,4} ms|       )\] Oooh, I do I do I do\n$'));
281 282 283
      expect(mockLogger.traceText, '');
      expect(
          mockLogger.errorText,
284
          matches('^$red' r'\[ (?: {0,2}\+[0-9]{1,4} ms|       )\] ' '${bold}Helpless!$resetBold$resetColor' r'\n$'));
285
    });
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310

    testWithoutContext('printBox', () {
      final BufferLogger mockLogger = BufferLogger(
        terminal: AnsiTerminal(
          stdio:  FakeStdio(),
          platform: FakePlatform(stdoutSupportsAnsi: true),
        ),
        outputPreferences: OutputPreferences.test(showColor: true),
      );
      final VerboseLogger verboseLogger = VerboseLogger(
        mockLogger, stopwatchFactory: FakeStopwatchFactory(stopwatch: fakeStopWatch),
      );

      verboseLogger.printBox('This is the box message', title: 'Sample title');

      expect(
        mockLogger.statusText,
        contains('[        ] \x1B[1m\x1B[22m\n'
            '\x1B[1m           ┌─ Sample title ──────────┐\x1B[22m\n'
            '\x1B[1m           │ This is the box message │\x1B[22m\n'
            '\x1B[1m           └─────────────────────────┘\x1B[22m\n'
            '\x1B[1m           \x1B[22m\n'
        ),
      );
    });
311
  });
312

313
  testWithoutContext('Logger does not throw when stdio write throws synchronously', () async {
314 315
    final FakeStdout stdout = FakeStdout(syncError: true);
    final FakeStdout stderr = FakeStdout(syncError: true);
316
    final Stdio stdio = Stdio.test(stdout: stdout, stderr: stderr);
317 318 319 320 321 322 323 324
    final Logger logger = StdoutLogger(
      terminal: AnsiTerminal(
        stdio: stdio,
        platform: _kNoAnsiPlatform,
      ),
      stdio: stdio,
      outputPreferences: OutputPreferences.test(),
    );
325

326 327
    logger.printStatus('message');
    logger.printError('error message');
328 329 330
  });

  testWithoutContext('Logger does not throw when stdio write throws asynchronously', () async {
331 332
    final FakeStdout stdout = FakeStdout(syncError: false);
    final FakeStdout stderr = FakeStdout(syncError: false);
333
    final Stdio stdio = Stdio.test(stdout: stdout, stderr: stderr);
334 335 336 337 338 339 340 341 342 343
    final Logger logger = StdoutLogger(
      terminal: AnsiTerminal(
        stdio: stdio,
        platform: _kNoAnsiPlatform,
      ),
      stdio: stdio,
      outputPreferences: OutputPreferences.test(),
    );
    logger.printStatus('message');
    logger.printError('error message');
344 345 346

    await stdout.done;
    await stderr.done;
347 348
  });

349
  testWithoutContext('Logger does not throw when stdio completes done with an error', () async {
350 351
    final FakeStdout stdout = FakeStdout(syncError: false, completeWithError: true);
    final FakeStdout stderr = FakeStdout(syncError: false, completeWithError: true);
352 353 354 355 356 357 358 359 360 361 362
    final Stdio stdio = Stdio.test(stdout: stdout, stderr: stderr);
    final Logger logger = StdoutLogger(
      terminal: AnsiTerminal(
        stdio: stdio,
        platform: _kNoAnsiPlatform,
      ),
      stdio: stdio,
      outputPreferences: OutputPreferences.test(),
    );
    logger.printStatus('message');
    logger.printError('error message');
363

364 365
    expect(() async => stdout.done, throwsException);
    expect(() async => stderr.done, throwsException);
366 367
  });

368
  group('Spinners', () {
369 370 371 372
    late FakeStdio mockStdio;
    late FakeStopwatch mockStopwatch;
    late FakeStopwatchFactory stopwatchFactory;
    late int called;
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
    final List<Platform> testPlatforms = <Platform>[
      FakePlatform(
        environment: <String, String>{},
        executableArguments: <String>[],
      ),
      FakePlatform(
        operatingSystem: 'macos',
        environment: <String, String>{},
        executableArguments: <String>[],
      ),
      FakePlatform(
        operatingSystem: 'windows',
        environment: <String, String>{},
        executableArguments: <String>[],
      ),
      FakePlatform(
        operatingSystem: 'windows',
        environment: <String, String>{'WT_SESSION': ''},
        executableArguments: <String>[],
      ),
      FakePlatform(
        operatingSystem: 'fuchsia',
        environment: <String, String>{},
        executableArguments: <String>[],
      ),
    ];
399
    final RegExp secondDigits = RegExp(r'[0-9,.]*[0-9]m?s');
400

401
    setUp(() {
402
      mockStopwatch = FakeStopwatch();
403
      mockStdio = FakeStdio();
404
      called = 0;
405
      stopwatchFactory = FakeStopwatchFactory(stopwatch: mockStopwatch);
406 407
    });

408 409
    List<String> outputStdout() => mockStdio.writtenToStdout.join().split('\n');
    List<String> outputStderr() => mockStdio.writtenToStderr.join().split('\n');
410

411
    void doWhileAsync(FakeAsync time, bool Function() doThis) {
412
      do {
413
        mockStopwatch.elapsed += const Duration(milliseconds: 1);
414 415
        time.elapse(const Duration(milliseconds: 1));
      } while (doThis());
416 417
    }

418 419
    for (final Platform testPlatform in testPlatforms) {
      group('(${testPlatform.operatingSystem})', () {
420 421 422 423 424
        late Platform platform;
        late Platform ansiPlatform;
        late AnsiTerminal terminal;
        late AnsiTerminal coloredTerminal;
        late SpinnerStatus spinnerStatus;
425

426
        setUp(() {
427
          platform = FakePlatform();
428
          ansiPlatform = FakePlatform(stdoutSupportsAnsi: true);
429 430 431 432 433 434 435 436 437 438

          terminal = AnsiTerminal(
            stdio: mockStdio,
            platform: platform,
          );
          coloredTerminal = AnsiTerminal(
            stdio: mockStdio,
            platform: ansiPlatform,
          );

439
          spinnerStatus = SpinnerStatus(
440 441 442
            message: 'Hello world',
            padding: 20,
            onFinish: () => called += 1,
443
            stdio: mockStdio,
444
            stopwatch: stopwatchFactory.createStopwatch(),
445
            terminal: terminal,
446
          );
447
        });
448

449
        testWithoutContext('AnonymousSpinnerStatus works (1)', () async {
450 451 452
          bool done = false;
          mockStopwatch = FakeStopwatch();
          FakeAsync().run((FakeAsync time) {
453
            final AnonymousSpinnerStatus spinner = AnonymousSpinnerStatus(
454
              stdio: mockStdio,
455
              stopwatch: mockStopwatch,
456 457
              terminal: terminal,
            )..start();
458
            doWhileAsync(time, () => spinner.ticks < 10);
459 460 461
            List<String> lines = outputStdout();
            expect(lines[0], startsWith(
              terminal.supportsEmoji
462 463
                ? '⣽\b⣻\b⢿\b⡿\b⣟\b⣯\b⣷\b⣾\b⣽\b⣻'
                : '\\\b|\b/\b-\b\\\b|\b/\b-'
464 465 466 467 468
              ),
            );
            expect(lines[0].endsWith('\n'), isFalse);
            expect(lines.length, equals(1));

469
            spinner.stop();
470 471 472 473 474 475
            lines = outputStdout();

            expect(lines[0], endsWith('\b \b'));
            expect(lines.length, equals(1));

            // Verify that stopping or canceling multiple times throws.
476 477
            expect(spinner.stop, throwsAssertionError);
            expect(spinner.cancel, throwsAssertionError);
478 479 480
            done = true;
          });
          expect(done, isTrue);
481
        });
482

483
        testWithoutContext('AnonymousSpinnerStatus logs warning after timeout without color support', () async {
484 485 486 487 488 489 490 491
          mockStopwatch = FakeStopwatch();
          const String warningMessage = 'a warning message.';
          final bool done = FakeAsync().run<bool>((FakeAsync time) {
            final AnonymousSpinnerStatus spinner = AnonymousSpinnerStatus(
              stdio: mockStdio,
              stopwatch: mockStopwatch,
              terminal: terminal,
              slowWarningCallback: () => warningMessage,
492
              warningColor: TerminalColor.red,
493 494 495 496 497 498 499 500
              timeout: const Duration(milliseconds: 100),
            )..start();
            // must be greater than the spinner timer duration
            const Duration timeLapse = Duration(milliseconds: 101);
            mockStopwatch.elapsed += timeLapse;
            time.elapse(timeLapse);

            List<String> lines = outputStdout();
501
            expect(lines.join().contains(RegExp(red)), isFalse);
502
            expect(lines.join(), '⣽\ba warning message.⣻');
503 504 505 506 507 508 509 510

            spinner.stop();
            lines = outputStdout();
            return true;
          });
          expect(done, isTrue);
        });

511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
        testWithoutContext('AnonymousSpinnerStatus logs warning after timeout with color support', () async {
          mockStopwatch = FakeStopwatch();
          const String warningMessage = 'a warning message.';
          final bool done = FakeAsync().run<bool>((FakeAsync time) {
            final AnonymousSpinnerStatus spinner = AnonymousSpinnerStatus(
              stdio: mockStdio,
              stopwatch: mockStopwatch,
              terminal: coloredTerminal,
              slowWarningCallback: () => warningMessage,
              warningColor: TerminalColor.red,
              timeout: const Duration(milliseconds: 100),
            )..start();
            // must be greater than the spinner timer duration
            const Duration timeLapse = Duration(milliseconds: 101);
            mockStopwatch.elapsed += timeLapse;
            time.elapse(timeLapse);

            List<String> lines = outputStdout();
            expect(lines.join().contains(RegExp(red)), isTrue);
            expect(lines.join(), '⣽\b${AnsiTerminal.red}a warning message.${AnsiTerminal.resetColor}⣻');
            expect(lines.join(), matches('$red$warningMessage$resetColor'));

            spinner.stop();
            lines = outputStdout();
            return true;
          });
          expect(done, isTrue);
        });

540
        testWithoutContext('Stdout startProgress on colored terminal', () async {
541 542 543 544 545 546 547 548 549 550 551 552
          final Logger logger = StdoutLogger(
            terminal: coloredTerminal,
            stdio: mockStdio,
            outputPreferences: OutputPreferences.test(showColor: true),
            stopwatchFactory: stopwatchFactory,
          );
          final Status status = logger.startProgress(
            'Hello',
            progressIndicatorPadding: 20, // this minus the "Hello" equals the 15 below.
          );
          expect(outputStderr().length, equals(1));
          expect(outputStderr().first, isEmpty);
553 554
          // the 4 below is the margin that is always included between the message and the time.
          // the 8 below is the space left for the time.
555 556 557
          expect(
            outputStdout().join('\n'),
            matches(terminal.supportsEmoji
558 559
              ? r'^Hello {15} {4} {8}⣽$'
              : r'^Hello {15} {4} {8}\\$'),
560 561 562 563 564 565 566
          );
          mockStopwatch.elapsed = const Duration(seconds: 4, milliseconds: 100);
          status.stop();
          expect(
            outputStdout().join('\n'),
            matches(
              terminal.supportsEmoji
567 568
              ? r'^Hello {15} {4} {8}⣽[\b] [\b]{8}[\d, ]{4}[\d]\.[\d]s[\n]$'
              : r'^Hello {15} {4} {8}\\[\b] [\b]{8}[\d, ]{4}[\d]\.[\d]s[\n]$',
569 570
            ),
          );
571
        });
572

573 574 575 576 577 578
        testWithoutContext('Stdout startProgress on colored terminal pauses', () async {
          bool done = false;
          FakeAsync().run((FakeAsync time) {
            mockStopwatch.elapsed = const Duration(seconds: 5);
            final Logger logger = StdoutLogger(
              terminal: coloredTerminal,
579
              stdio: mockStdio,
580 581 582
              outputPreferences: OutputPreferences.test(showColor: true),
              stopwatchFactory: stopwatchFactory,
            );
583
            const String message = "Knock Knock, Who's There";
584
            final Status status = logger.startProgress(
585 586
              message,
              progressIndicatorPadding: 10, // ignored
587 588 589 590 591
            );
            logger.printStatus('Rude Interrupting Cow');
            status.stop();
            final String a = terminal.supportsEmoji ? '⣽' : r'\';
            final String b = terminal.supportsEmoji ? '⣻' : '|';
592
            const String blankLine = '\r\x1B[K';
593 594
            expect(
              outputStdout().join('\n'),
595 596 597 598
              '$message' // initial message
              '${" " * 4}${" " * 8}' // margin (4) and space for the time at the end (8)
              '$a' // first tick
              '$blankLine' // clearing the line
599
              'Rude Interrupting Cow\n' // message
600 601 602
              '$message' // message restoration
              '${" " * 4}${" " * 8}' // margin (4) and space for the time at the end (8)
              '$b' // second tick
603
              // ignore: missing_whitespace_between_adjacent_strings
604 605
              '\b \b' // backspace the tick, wipe the tick, backspace the wipe
              '\b\b\b\b\b\b\b' // backspace the space for the time
606 607 608 609 610
              '    5.0s\n', // replacing it with the time
            );
            done = true;
          });
          expect(done, isTrue);
611 612
        });

613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
        testWithoutContext('Stdout startProgress on non-colored terminal pauses', () async {
          bool done = false;
          FakeAsync().run((FakeAsync time) {
            mockStopwatch.elapsed = const Duration(seconds: 5);
            final Logger logger = StdoutLogger(
              terminal: terminal,
              stdio: mockStdio,
              outputPreferences: OutputPreferences.test(showColor: true),
              stopwatchFactory: stopwatchFactory,
            );
            const String message = "Knock Knock, Who's There";
            final Status status = logger.startProgress(
              message,
              progressIndicatorPadding: 10, // ignored
            );
            logger.printStatus('Rude Interrupting Cow');
            status.stop();
            expect(
              outputStdout().join('\n'),
              '$message' // initial message
              '     ' // margin
              '\n' // clearing the line
              'Rude Interrupting Cow\n' // message
              '$message         5.0s\n' // message restoration
            );
            done = true;
          });
          expect(done, isTrue);
        });

        testWithoutContext('SpinnerStatus works when canceled', () async {
644 645
          bool done = false;
          FakeAsync().run((FakeAsync time) {
646
            spinnerStatus.start();
647
            mockStopwatch.elapsed = const Duration(seconds: 1);
648
            doWhileAsync(time, () => spinnerStatus.ticks < 10);
649 650 651 652
            List<String> lines = outputStdout();

            expect(lines[0], startsWith(
              terminal.supportsEmoji
653 654
              ? 'Hello world                     ⣽\b⣻\b⢿\b⡿\b⣟\b⣯\b⣷\b⣾\b⣽\b⣻'
              : 'Hello world                     \\\b|\b/\b-\b\\\b|\b/\b-\b\\\b|'
655 656 657 658 659
            ));
            expect(lines.length, equals(1));
            expect(lines[0].endsWith('\n'), isFalse);

            // Verify a cancel does _not_ print the time and prints a newline.
660
            spinnerStatus.cancel();
661 662 663 664 665
            lines = outputStdout();
            final List<Match> matches = secondDigits.allMatches(lines[0]).toList();
            expect(matches, isEmpty);
            final String leading = terminal.supportsEmoji ? '⣻' : '|';

666
            expect(lines[0], endsWith('$leading\b \b'));
667 668 669 670 671
            expect(called, equals(1));
            expect(lines.length, equals(2));
            expect(lines[1], equals(''));

            // Verify that stopping or canceling multiple times throws.
672 673
            expect(spinnerStatus.cancel, throwsAssertionError);
            expect(spinnerStatus.stop, throwsAssertionError);
674 675 676
            done = true;
          });
          expect(done, isTrue);
677 678
        });

679
        testWithoutContext('SpinnerStatus works when stopped', () async {
680 681
          bool done = false;
          FakeAsync().run((FakeAsync time) {
682
            spinnerStatus.start();
683
            mockStopwatch.elapsed = const Duration(seconds: 1);
684
            doWhileAsync(time, () => spinnerStatus.ticks < 10);
685 686 687 688 689 690
            List<String> lines = outputStdout();

            expect(lines, hasLength(1));
            expect(
              lines[0],
              terminal.supportsEmoji
691 692
                ? 'Hello world                     ⣽\b⣻\b⢿\b⡿\b⣟\b⣯\b⣷\b⣾\b⣽\b⣻'
                : 'Hello world                     \\\b|\b/\b-\b\\\b|\b/\b-\b\\\b|'
693 694 695
            );

            // Verify a stop prints the time.
696
            spinnerStatus.stop();
697 698 699 700
            lines = outputStdout();
            expect(lines, hasLength(2));
            expect(lines[0], matches(
              terminal.supportsEmoji
701 702
                ? r'Hello world                     ⣽[\b]⣻[\b]⢿[\b]⡿[\b]⣟[\b]⣯[\b]⣷[\b]⣾[\b]⣽[\b]⣻[\b] [\b]{8}[\d., ]{5}[\d]ms$'
                : r'Hello world                     \\[\b]|[\b]/[\b]-[\b]\\[\b]|[\b]/[\b]-[\b]\\[\b]|[\b] [\b]{8}[\d., ]{5}[\d]ms$'
703 704 705 706 707 708 709
            ));
            expect(lines[1], isEmpty);
            final List<Match> times = secondDigits.allMatches(lines[0]).toList();
            expect(times, isNotNull);
            expect(times, hasLength(1));
            final Match match = times.single;

710
            expect(lines[0], endsWith(match.group(0)!));
711 712 713 714 715
            expect(called, equals(1));
            expect(lines.length, equals(2));
            expect(lines[1], equals(''));

            // Verify that stopping or canceling multiple times throws.
716 717
            expect(spinnerStatus.stop, throwsAssertionError);
            expect(spinnerStatus.cancel, throwsAssertionError);
718 719 720
            done = true;
          });
          expect(done, isTrue);
721
        });
722 723
      });
    }
724
  });
725

726
  group('Output format', () {
727 728 729
    late FakeStdio fakeStdio;
    late SummaryStatus summaryStatus;
    late int called;
730 731

    setUp(() {
732
      fakeStdio = FakeStdio();
733 734 735 736 737
      called = 0;
      summaryStatus = SummaryStatus(
        message: 'Hello world',
        padding: 20,
        onFinish: () => called++,
738
        stdio: fakeStdio,
739
        stopwatch: FakeStopwatch(),
740 741 742
      );
    });

743 744
    List<String> outputStdout() => fakeStdio.writtenToStdout.join().split('\n');
    List<String> outputStderr() => fakeStdio.writtenToStderr.join().split('\n');
745

746 747 748
    testWithoutContext('Error logs are wrapped', () async {
      final Logger logger = StdoutLogger(
        terminal: AnsiTerminal(
749
          stdio: fakeStdio,
750 751
          platform: _kNoAnsiPlatform,
        ),
752
        stdio: fakeStdio,
753
        outputPreferences: OutputPreferences.test(wrapText: true, wrapColumn: 40),
754
      );
755
      logger.printError('0123456789' * 15);
756
      final List<String> lines = outputStderr();
757

758 759 760 761 762 763 764 765
      expect(outputStdout().length, equals(1));
      expect(outputStdout().first, isEmpty);
      expect(lines[0], equals('0123456789' * 4));
      expect(lines[1], equals('0123456789' * 4));
      expect(lines[2], equals('0123456789' * 4));
      expect(lines[3], equals('0123456789' * 3));
    });

766
    testWithoutContext('AppRunLogger writes plain text statuses when no app is active', () async {
767 768 769
      final BufferLogger buffer = BufferLogger.test();
      final AppRunLogger logger = AppRunLogger(parent: buffer);

770
      logger.startProgress('Test status...').stop();
771 772 773 774

      expect(buffer.statusText.trim(), equals('Test status...'));
    });

775 776 777
    testWithoutContext('Error logs are wrapped and can be indented.', () async {
      final Logger logger = StdoutLogger(
        terminal: AnsiTerminal(
778
          stdio: fakeStdio,
779 780
          platform: _kNoAnsiPlatform,
        ),
781
        stdio: fakeStdio,
782
        outputPreferences: OutputPreferences.test(wrapText: true, wrapColumn: 40),
783
      );
784
      logger.printError('0123456789' * 15, indent: 5);
785
      final List<String> lines = outputStderr();
786

787 788 789 790 791 792 793 794 795 796 797
      expect(outputStdout().length, equals(1));
      expect(outputStdout().first, isEmpty);
      expect(lines.length, equals(6));
      expect(lines[0], equals('     01234567890123456789012345678901234'));
      expect(lines[1], equals('     56789012345678901234567890123456789'));
      expect(lines[2], equals('     01234567890123456789012345678901234'));
      expect(lines[3], equals('     56789012345678901234567890123456789'));
      expect(lines[4], equals('     0123456789'));
      expect(lines[5], isEmpty);
    });

798 799 800
    testWithoutContext('Error logs are wrapped and can have hanging indent.', () async {
      final Logger logger = StdoutLogger(
        terminal: AnsiTerminal(
801
          stdio: fakeStdio,
802 803
          platform: _kNoAnsiPlatform,
        ),
804
        stdio: fakeStdio,
805
        outputPreferences: OutputPreferences.test(wrapText: true, wrapColumn: 40),
806
      );
807
      logger.printError('0123456789' * 15, hangingIndent: 5);
808
      final List<String> lines = outputStderr();
809

810 811 812 813 814 815 816 817 818 819 820
      expect(outputStdout().length, equals(1));
      expect(outputStdout().first, isEmpty);
      expect(lines.length, equals(6));
      expect(lines[0], equals('0123456789012345678901234567890123456789'));
      expect(lines[1], equals('     01234567890123456789012345678901234'));
      expect(lines[2], equals('     56789012345678901234567890123456789'));
      expect(lines[3], equals('     01234567890123456789012345678901234'));
      expect(lines[4], equals('     56789'));
      expect(lines[5], isEmpty);
    });

821 822 823
    testWithoutContext('Error logs are wrapped, indented, and can have hanging indent.', () async {
      final Logger logger = StdoutLogger(
        terminal: AnsiTerminal(
824
          stdio: fakeStdio,
825 826
          platform: _kNoAnsiPlatform,
        ),
827
        stdio: fakeStdio,
828
        outputPreferences: OutputPreferences.test(wrapText: true, wrapColumn: 40),
829
      );
830
      logger.printError('0123456789' * 15, indent: 4, hangingIndent: 5);
831
      final List<String> lines = outputStderr();
832

833 834 835 836 837 838 839 840 841 842 843
      expect(outputStdout().length, equals(1));
      expect(outputStdout().first, isEmpty);
      expect(lines.length, equals(6));
      expect(lines[0], equals('    012345678901234567890123456789012345'));
      expect(lines[1], equals('         6789012345678901234567890123456'));
      expect(lines[2], equals('         7890123456789012345678901234567'));
      expect(lines[3], equals('         8901234567890123456789012345678'));
      expect(lines[4], equals('         901234567890123456789'));
      expect(lines[5], isEmpty);
    });

844 845 846
    testWithoutContext('Stdout logs are wrapped', () async {
      final Logger logger = StdoutLogger(
        terminal: AnsiTerminal(
847
          stdio: fakeStdio,
848 849
          platform: _kNoAnsiPlatform,
        ),
850
        stdio: fakeStdio,
851
        outputPreferences: OutputPreferences.test(wrapText: true, wrapColumn: 40),
852
      );
853
      logger.printStatus('0123456789' * 15);
854
      final List<String> lines = outputStdout();
855

856 857 858 859 860 861 862 863
      expect(outputStderr().length, equals(1));
      expect(outputStderr().first, isEmpty);
      expect(lines[0], equals('0123456789' * 4));
      expect(lines[1], equals('0123456789' * 4));
      expect(lines[2], equals('0123456789' * 4));
      expect(lines[3], equals('0123456789' * 3));
    });

864 865 866
    testWithoutContext('Stdout logs are wrapped and can be indented.', () async {
      final Logger logger = StdoutLogger(
        terminal: AnsiTerminal(
867
          stdio: fakeStdio,
868 869
          platform: _kNoAnsiPlatform,
        ),
870
        stdio: fakeStdio,
871
        outputPreferences: OutputPreferences.test(wrapText: true, wrapColumn: 40),
872
      );
873
      logger.printStatus('0123456789' * 15, indent: 5);
874
      final List<String> lines = outputStdout();
875

876 877 878 879 880 881 882 883 884 885 886
      expect(outputStderr().length, equals(1));
      expect(outputStderr().first, isEmpty);
      expect(lines.length, equals(6));
      expect(lines[0], equals('     01234567890123456789012345678901234'));
      expect(lines[1], equals('     56789012345678901234567890123456789'));
      expect(lines[2], equals('     01234567890123456789012345678901234'));
      expect(lines[3], equals('     56789012345678901234567890123456789'));
      expect(lines[4], equals('     0123456789'));
      expect(lines[5], isEmpty);
    });

887 888 889
    testWithoutContext('Stdout logs are wrapped and can have hanging indent.', () async {
      final Logger logger = StdoutLogger(
        terminal: AnsiTerminal(
890
          stdio: fakeStdio,
891 892
          platform: _kNoAnsiPlatform,
        ),
893
        stdio: fakeStdio,
894
        outputPreferences: OutputPreferences.test(wrapText: true, wrapColumn: 40)
895
      );
896
      logger.printStatus('0123456789' * 15, hangingIndent: 5);
897
      final List<String> lines = outputStdout();
898

899 900 901 902 903 904 905 906 907 908 909
      expect(outputStderr().length, equals(1));
      expect(outputStderr().first, isEmpty);
      expect(lines.length, equals(6));
      expect(lines[0], equals('0123456789012345678901234567890123456789'));
      expect(lines[1], equals('     01234567890123456789012345678901234'));
      expect(lines[2], equals('     56789012345678901234567890123456789'));
      expect(lines[3], equals('     01234567890123456789012345678901234'));
      expect(lines[4], equals('     56789'));
      expect(lines[5], isEmpty);
    });

910
    testWithoutContext('Stdout logs are wrapped, indented, and can have hanging indent.', () async {
911 912
      final Logger logger = StdoutLogger(
        terminal: AnsiTerminal(
913
          stdio: fakeStdio,
914 915
          platform: _kNoAnsiPlatform,
        ),
916
        stdio: fakeStdio,
917
        outputPreferences: OutputPreferences.test(wrapText: true, wrapColumn: 40),
918
      );
919
      logger.printStatus('0123456789' * 15, indent: 4, hangingIndent: 5);
920
      final List<String> lines = outputStdout();
921

922 923 924 925 926 927 928 929 930 931
      expect(outputStderr().length, equals(1));
      expect(outputStderr().first, isEmpty);
      expect(lines.length, equals(6));
      expect(lines[0], equals('    012345678901234567890123456789012345'));
      expect(lines[1], equals('         6789012345678901234567890123456'));
      expect(lines[2], equals('         7890123456789012345678901234567'));
      expect(lines[3], equals('         8901234567890123456789012345678'));
      expect(lines[4], equals('         901234567890123456789'));
      expect(lines[5], isEmpty);
    });
932

933 934 935
    testWithoutContext('Error logs are red', () async {
      final Logger logger = StdoutLogger(
        terminal: AnsiTerminal(
936
          stdio: fakeStdio,
937
          platform: FakePlatform(stdoutSupportsAnsi: true),
938
        ),
939
        stdio: fakeStdio,
940 941
        outputPreferences: OutputPreferences.test(showColor: true),
      );
942
      logger.printError('Pants on fire!');
943
      final List<String> lines = outputStderr();
944

945 946
      expect(outputStdout().length, equals(1));
      expect(outputStdout().first, isEmpty);
947
      expect(lines[0], equals('${AnsiTerminal.red}Pants on fire!${AnsiTerminal.resetColor}'));
948 949
    });

950 951 952
    testWithoutContext('Stdout logs are not colored', () async {
      final Logger logger = StdoutLogger(
        terminal: AnsiTerminal(
953
          stdio: fakeStdio,
954 955
          platform: FakePlatform(),
        ),
956
        stdio: fakeStdio,
957 958
        outputPreferences:  OutputPreferences.test(showColor: true),
      );
959
      logger.printStatus('All good.');
960

961 962 963 964 965 966
      final List<String> lines = outputStdout();
      expect(outputStderr().length, equals(1));
      expect(outputStderr().first, isEmpty);
      expect(lines[0], equals('All good.'));
    });

967 968 969 970 971 972 973 974 975 976
    testWithoutContext('Stdout printBox puts content inside a box', () {
      final Logger logger = StdoutLogger(
        terminal: AnsiTerminal(
          stdio: fakeStdio,
          platform: FakePlatform(),
        ),
        stdio: fakeStdio,
        outputPreferences: OutputPreferences.test(showColor: true),
      );
      logger.printBox('Hello world', title: 'Test title');
977
      final String stdout = fakeStdio.writtenToStdout.join();
978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997
      expect(stdout,
        contains(
          '\n'
          '┌─ Test title ┐\n'
          '│ Hello world │\n'
          '└─────────────┘\n'
        ),
      );
    });

    testWithoutContext('Stdout printBox does not require title', () {
      final Logger logger = StdoutLogger(
        terminal: AnsiTerminal(
          stdio: fakeStdio,
          platform: FakePlatform(),
        ),
        stdio: fakeStdio,
        outputPreferences: OutputPreferences.test(showColor: true),
      );
      logger.printBox('Hello world');
998
      final String stdout = fakeStdio.writtenToStdout.join();
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
      expect(stdout,
        contains(
          '\n'
          '┌─────────────┐\n'
          '│ Hello world │\n'
          '└─────────────┘\n'
        ),
      );
    });

    testWithoutContext('Stdout printBox handles new lines', () {
      final Logger logger = StdoutLogger(
        terminal: AnsiTerminal(
          stdio: fakeStdio,
          platform: FakePlatform(),
        ),
        stdio: fakeStdio,
        outputPreferences: OutputPreferences.test(showColor: true),
      );
      logger.printBox('Hello world\nThis is a new line', title: 'Test title');
1019
      final String stdout = fakeStdio.writtenToStdout.join();
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
      expect(stdout,
        contains(
          '\n'
          '┌─ Test title ───────┐\n'
          '│ Hello world        │\n'
          '│ This is a new line │\n'
          '└────────────────────┘\n'
        ),
      );
    });

    testWithoutContext('Stdout printBox handles content with ANSI escape characters', () {
      final Logger logger = StdoutLogger(
        terminal: AnsiTerminal(
          stdio: fakeStdio,
          platform: FakePlatform(),
        ),
        stdio: fakeStdio,
        outputPreferences: OutputPreferences.test(showColor: true),
      );
      const String bold = '\u001B[1m';
      const String clear = '\u001B[2J\u001B[H';
      logger.printBox('${bold}Hello world$clear', title: 'Test title');
1043
      final String stdout = fakeStdio.writtenToStdout.join();
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
      expect(stdout,
        contains(
          '\n'
          '┌─ Test title ┐\n'
          '│ ${bold}Hello world$clear\n'
          '└─────────────┘\n'
        ),
      );
    });

    testWithoutContext('Stdout printBox handles column limit', () {
      const int columnLimit = 14;
      final Logger logger = StdoutLogger(
        terminal: AnsiTerminal(
          stdio: fakeStdio,
          platform: FakePlatform(),
        ),
        stdio: fakeStdio,
        outputPreferences: OutputPreferences.test(showColor: true, wrapColumn: columnLimit),
      );
      logger.printBox('This line is longer than $columnLimit characters', title: 'Test');
1065
      final String stdout = fakeStdio.writtenToStdout.join();
1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
      final List<String> stdoutLines = stdout.split('\n');

      expect(stdoutLines.length, greaterThan(1));
      expect(stdoutLines[1].length, equals(columnLimit));
      expect(stdout,
        contains(
          '\n'
          '┌─ Test ─────┐\n'
          '│ This line  │\n'
          '│ is longer  │\n'
          '│ than 14    │\n'
          '│ characters │\n'
          '└────────────┘\n'
        ),
      );
    });

    testWithoutContext('Stdout printBox handles column limit and respects new lines', () {
      const int columnLimit = 14;
      final Logger logger = StdoutLogger(
        terminal: AnsiTerminal(
          stdio: fakeStdio,
          platform: FakePlatform(),
        ),
        stdio: fakeStdio,
        outputPreferences: OutputPreferences.test(showColor: true, wrapColumn: columnLimit),
      );
      logger.printBox('This\nline is longer than\n\n$columnLimit characters', title: 'Test');
1094
      final String stdout = fakeStdio.writtenToStdout.join();
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
      final List<String> stdoutLines = stdout.split('\n');

      expect(stdoutLines.length, greaterThan(1));
      expect(stdoutLines[1].length, equals(columnLimit));
      expect(stdout,
        contains(
          '\n'
          '┌─ Test ─────┐\n'
          '│ This       │\n'
          '│ line is    │\n'
          '│ longer     │\n'
          '│ than       │\n'
          '│            │\n'
          '│ 14         │\n'
          '│ characters │\n'
          '└────────────┘\n'
        ),
      );
    });

    testWithoutContext('Stdout printBox breaks long words that exceed the column limit', () {
      const int columnLimit = 14;
      final Logger logger = StdoutLogger(
        terminal: AnsiTerminal(
          stdio: fakeStdio,
          platform: FakePlatform(),
        ),
        stdio: fakeStdio,
        outputPreferences: OutputPreferences.test(showColor: true, wrapColumn: columnLimit),
      );
      logger.printBox('Thiswordislongerthan${columnLimit}characters', title: 'Test');
1126
      final String stdout = fakeStdio.writtenToStdout.join();
1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
      final List<String> stdoutLines = stdout.split('\n');

      expect(stdoutLines.length, greaterThan(1));
      expect(stdoutLines[1].length, equals(columnLimit));
      expect(stdout,
        contains(
          '\n'
          '┌─ Test ─────┐\n'
          '│ Thiswordis │\n'
          '│ longerthan │\n'
          '│ 14characte │\n'
          '│ rs         │\n'
          '└────────────┘\n'
        ),
      );
    });


1145
    testWithoutContext('Stdout startProgress on non-color terminal', () async {
1146 1147 1148
      final FakeStopwatch fakeStopwatch = FakeStopwatch();
      final Logger logger = StdoutLogger(
        terminal: AnsiTerminal(
1149
          stdio: fakeStdio,
1150 1151
          platform: _kNoAnsiPlatform,
        ),
1152
        stdio: fakeStdio,
1153
        outputPreferences: OutputPreferences.test(),
1154
        stopwatchFactory: FakeStopwatchFactory(stopwatch: fakeStopwatch),
1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
      );
      final Status status = logger.startProgress(
        'Hello',
        progressIndicatorPadding: 20, // this minus the "Hello" equals the 15 below.
      );
      expect(outputStderr().length, equals(1));
      expect(outputStderr().first, isEmpty);
      // the 5 below is the margin that is always included between the message and the time.
      expect(outputStdout().join('\n'), matches(r'^Hello {15} {5}$'));

      fakeStopwatch.elapsed = const Duration(seconds: 4, milliseconds: 123);
      status.stop();

      expect(outputStdout(), <String>['Hello                        4.1s', '']);
1169 1170
    });

1171 1172 1173 1174 1175
    testWithoutContext('SummaryStatus works when canceled', () async {
      final SummaryStatus summaryStatus = SummaryStatus(
        message: 'Hello world',
        padding: 20,
        onFinish: () => called++,
1176
        stdio: fakeStdio,
1177 1178
        stopwatch: FakeStopwatch(),
      );
1179
      summaryStatus.start();
1180
      final List<String> lines = outputStdout();
1181 1182 1183 1184 1185 1186
      expect(lines[0], startsWith('Hello world              '));
      expect(lines.length, equals(1));
      expect(lines[0].endsWith('\n'), isFalse);

      // Verify a cancel does _not_ print the time and prints a newline.
      summaryStatus.cancel();
1187 1188 1189 1190
      expect(outputStdout(), <String>[
        'Hello world              ',
        '',
      ]);
1191 1192

      // Verify that stopping or canceling multiple times throws.
Dan Field's avatar
Dan Field committed
1193 1194
      expect(summaryStatus.cancel, throwsAssertionError);
      expect(summaryStatus.stop, throwsAssertionError);
1195
    });
1196

1197
    testWithoutContext('SummaryStatus works when stopped', () async {
1198
      summaryStatus.start();
1199
      final List<String> lines = outputStdout();
1200 1201 1202 1203 1204
      expect(lines[0], startsWith('Hello world              '));
      expect(lines.length, equals(1));

      // Verify a stop prints the time.
      summaryStatus.stop();
1205 1206 1207 1208
      expect(outputStdout(), <String>[
        'Hello world                   0ms',
        '',
      ]);
1209 1210

      // Verify that stopping or canceling multiple times throws.
Dan Field's avatar
Dan Field committed
1211 1212
      expect(summaryStatus.stop, throwsAssertionError);
      expect(summaryStatus.cancel, throwsAssertionError);
1213
    });
1214

1215
    testWithoutContext('sequential startProgress calls with StdoutLogger', () async {
1216 1217
      final Logger logger = StdoutLogger(
        terminal: AnsiTerminal(
1218
          stdio: fakeStdio,
1219 1220
          platform: _kNoAnsiPlatform,
        ),
1221
        stdio: fakeStdio,
1222
        outputPreferences: OutputPreferences.test(),
1223
      );
1224 1225
      logger.startProgress('AAA').stop();
      logger.startProgress('BBB').stop();
1226
      final List<String> output = outputStdout();
1227

1228
      expect(output.length, equals(3));
1229

1230 1231 1232 1233 1234
      // There's 61 spaces at the start: 59 (padding default) - 3 (length of AAA) + 5 (margin).
      // Then there's a left-padded "0ms" 8 characters wide, so 5 spaces then "0ms"
      // (except sometimes it's randomly slow so we handle up to "99,999ms").
      expect(output[0], matches(RegExp(r'AAA[ ]{61}[\d, ]{5}[\d]ms')));
      expect(output[1], matches(RegExp(r'BBB[ ]{61}[\d, ]{5}[\d]ms')));
1235
    });
1236

1237
    testWithoutContext('sequential startProgress calls with VerboseLogger and StdoutLogger', () async {
1238 1239 1240
      final Logger logger = VerboseLogger(
        StdoutLogger(
          terminal: AnsiTerminal(
1241
            stdio: fakeStdio,
1242 1243
            platform: _kNoAnsiPlatform,
          ),
1244
          stdio: fakeStdio,
1245 1246
          outputPreferences: OutputPreferences.test(),
        ),
1247
        stopwatchFactory: FakeStopwatchFactory(),
1248
      );
1249 1250
      logger.startProgress('AAA').stop();
      logger.startProgress('BBB').stop();
1251

1252
      expect(outputStdout(), <Matcher>[
1253 1254 1255 1256
        matches(r'^\[ (?: {0,2}\+[0-9]{1,4} ms|       )\] AAA$'),
        matches(r'^\[ (?: {0,2}\+[0-9]{1,4} ms|       )\] AAA \(completed.*\)$'),
        matches(r'^\[ (?: {0,2}\+[0-9]{1,4} ms|       )\] BBB$'),
        matches(r'^\[ (?: {0,2}\+[0-9]{1,4} ms|       )\] BBB \(completed.*\)$'),
1257 1258 1259
        matches(r'^$'),
      ]);
    });
1260

1261
    testWithoutContext('sequential startProgress calls with BufferLogger', () async {
1262 1263
      final BufferLogger logger = BufferLogger(
        terminal: AnsiTerminal(
1264
          stdio: fakeStdio,
1265 1266 1267 1268
          platform: _kNoAnsiPlatform,
        ),
        outputPreferences: OutputPreferences.test(),
      );
1269 1270
      logger.startProgress('AAA').stop();
      logger.startProgress('BBB').stop();
1271 1272

      expect(logger.statusText, 'AAA\nBBB\n');
1273
    });
1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288

    testWithoutContext('BufferLogger prints status, trace, error', () async {
      final BufferLogger mockLogger = BufferLogger.test(
        outputPreferences: OutputPreferences.test(),
      );

      mockLogger.printStatus('Hey Hey Hey Hey');
      mockLogger.printTrace('Oooh, I do I do I do');
      final StackTrace stackTrace = StackTrace.current;
      mockLogger.printError('Helpless!', stackTrace: stackTrace);

      expect(mockLogger.statusText, 'Hey Hey Hey Hey\n');
      expect(mockLogger.traceText, 'Oooh, I do I do I do\n');
      expect(mockLogger.errorText, 'Helpless!\n$stackTrace\n');
    });
1289
  });
1290
}
1291

1292 1293 1294
/// A fake [Logger] that throws the [Invocation] for any method call.
class FakeLogger implements Logger {
  @override
1295
  dynamic noSuchMethod(Invocation invocation) => throw invocation; // ignore: only_throw_errors
1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325
}

/// Returns the [Invocation] thrown from a call to [FakeLogger].
Invocation _invocationFor(dynamic Function() fakeCall) {
  try {
    fakeCall();
  } on Invocation catch (invocation) {
    return invocation;
  }
  throw UnsupportedError('_invocationFor can be used only with Fake objects '
    'that throw Invocations');
}

/// Returns a [Matcher] that matches against an expected [Invocation].
Matcher _matchesInvocation(Invocation expected) {
  return const TypeMatcher<Invocation>()
    // Compare Symbol strings instead of comparing Symbols directly for a nicer failure message.
    .having((Invocation actual) => actual.memberName.toString(), 'memberName', expected.memberName.toString())
    .having((Invocation actual) => actual.isGetter, 'isGetter', expected.isGetter)
    .having((Invocation actual) => actual.isSetter, 'isSetter', expected.isSetter)
    .having((Invocation actual) => actual.isMethod, 'isMethod', expected.isMethod)
    .having((Invocation actual) => actual.typeArguments, 'typeArguments', expected.typeArguments)
    .having((Invocation actual) => actual.positionalArguments, 'positionalArguments', expected.positionalArguments)
    .having((Invocation actual) => actual.namedArguments, 'namedArguments', expected.namedArguments);
}

/// Returns a [Matcher] that matches against an [Invocation] thrown from a call
/// to [FakeLogger].
Matcher _throwsInvocationFor(dynamic Function() fakeCall) =>
  throwsA(_matchesInvocation(_invocationFor(fakeCall)));
1326 1327

class FakeStdout extends Fake implements Stdout {
1328
  FakeStdout({required this.syncError, this.completeWithError = false});
1329 1330 1331 1332 1333 1334

  final bool syncError;
  final bool completeWithError;
  final Completer<void> _completer = Completer<void>();

  @override
1335
  void write(Object? object) {
1336
    if (syncError) {
1337
      throw Exception('Error!');
1338 1339 1340 1341 1342 1343
    }
    Zone.current.runUnaryGuarded<void>((_) {
      if (completeWithError) {
        _completer.completeError(Exception('Some pipe error'));
      } else {
        _completer.complete();
1344
        throw Exception('Error!');
1345 1346 1347 1348 1349 1350 1351
      }
    }, null);
  }

  @override
  Future<void> get done => _completer.future;
}