logger_test.dart 47.4 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 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
        testWithoutContext('AnonymousSpinnerStatus logs warning after timeout', () 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: terminal,
              slowWarningCallback: () => warningMessage,
              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(warningMessage),
            );

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

512
        testWithoutContext('Stdout startProgress on colored terminal', () async {
513 514 515 516 517 518 519 520 521 522 523 524
          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);
525 526
          // 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.
527 528 529
          expect(
            outputStdout().join('\n'),
            matches(terminal.supportsEmoji
530 531
              ? r'^Hello {15} {4} {8}⣽$'
              : r'^Hello {15} {4} {8}\\$'),
532 533 534 535 536 537 538
          );
          mockStopwatch.elapsed = const Duration(seconds: 4, milliseconds: 100);
          status.stop();
          expect(
            outputStdout().join('\n'),
            matches(
              terminal.supportsEmoji
539 540
              ? 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]$',
541 542
            ),
          );
543
        });
544

545 546 547 548 549 550
        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,
551
              stdio: mockStdio,
552 553 554
              outputPreferences: OutputPreferences.test(showColor: true),
              stopwatchFactory: stopwatchFactory,
            );
555
            const String message = "Knock Knock, Who's There";
556
            final Status status = logger.startProgress(
557 558
              message,
              progressIndicatorPadding: 10, // ignored
559 560 561 562 563
            );
            logger.printStatus('Rude Interrupting Cow');
            status.stop();
            final String a = terminal.supportsEmoji ? '⣽' : r'\';
            final String b = terminal.supportsEmoji ? '⣻' : '|';
564
            const String blankLine = '\r\x1B[K';
565 566
            expect(
              outputStdout().join('\n'),
567 568 569 570
              '$message' // initial message
              '${" " * 4}${" " * 8}' // margin (4) and space for the time at the end (8)
              '$a' // first tick
              '$blankLine' // clearing the line
571
              'Rude Interrupting Cow\n' // message
572 573 574
              '$message' // message restoration
              '${" " * 4}${" " * 8}' // margin (4) and space for the time at the end (8)
              '$b' // second tick
575
              // ignore: missing_whitespace_between_adjacent_strings
576 577
              '\b \b' // backspace the tick, wipe the tick, backspace the wipe
              '\b\b\b\b\b\b\b' // backspace the space for the time
578 579 580 581 582
              '    5.0s\n', // replacing it with the time
            );
            done = true;
          });
          expect(done, isTrue);
583 584
        });

585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
        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 {
616 617
          bool done = false;
          FakeAsync().run((FakeAsync time) {
618
            spinnerStatus.start();
619
            mockStopwatch.elapsed = const Duration(seconds: 1);
620
            doWhileAsync(time, () => spinnerStatus.ticks < 10);
621 622 623 624
            List<String> lines = outputStdout();

            expect(lines[0], startsWith(
              terminal.supportsEmoji
625 626
              ? 'Hello world                     ⣽\b⣻\b⢿\b⡿\b⣟\b⣯\b⣷\b⣾\b⣽\b⣻'
              : 'Hello world                     \\\b|\b/\b-\b\\\b|\b/\b-\b\\\b|'
627 628 629 630 631
            ));
            expect(lines.length, equals(1));
            expect(lines[0].endsWith('\n'), isFalse);

            // Verify a cancel does _not_ print the time and prints a newline.
632
            spinnerStatus.cancel();
633 634 635 636 637
            lines = outputStdout();
            final List<Match> matches = secondDigits.allMatches(lines[0]).toList();
            expect(matches, isEmpty);
            final String leading = terminal.supportsEmoji ? '⣻' : '|';

638
            expect(lines[0], endsWith('$leading\b \b'));
639 640 641 642 643
            expect(called, equals(1));
            expect(lines.length, equals(2));
            expect(lines[1], equals(''));

            // Verify that stopping or canceling multiple times throws.
644 645
            expect(spinnerStatus.cancel, throwsAssertionError);
            expect(spinnerStatus.stop, throwsAssertionError);
646 647 648
            done = true;
          });
          expect(done, isTrue);
649 650
        });

651
        testWithoutContext('SpinnerStatus works when stopped', () async {
652 653
          bool done = false;
          FakeAsync().run((FakeAsync time) {
654
            spinnerStatus.start();
655
            mockStopwatch.elapsed = const Duration(seconds: 1);
656
            doWhileAsync(time, () => spinnerStatus.ticks < 10);
657 658 659 660 661 662
            List<String> lines = outputStdout();

            expect(lines, hasLength(1));
            expect(
              lines[0],
              terminal.supportsEmoji
663 664
                ? 'Hello world                     ⣽\b⣻\b⢿\b⡿\b⣟\b⣯\b⣷\b⣾\b⣽\b⣻'
                : 'Hello world                     \\\b|\b/\b-\b\\\b|\b/\b-\b\\\b|'
665 666 667
            );

            // Verify a stop prints the time.
668
            spinnerStatus.stop();
669 670 671 672
            lines = outputStdout();
            expect(lines, hasLength(2));
            expect(lines[0], matches(
              terminal.supportsEmoji
673 674
                ? 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$'
675 676 677 678 679 680 681
            ));
            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;

682
            expect(lines[0], endsWith(match.group(0)!));
683 684 685 686 687
            expect(called, equals(1));
            expect(lines.length, equals(2));
            expect(lines[1], equals(''));

            // Verify that stopping or canceling multiple times throws.
688 689
            expect(spinnerStatus.stop, throwsAssertionError);
            expect(spinnerStatus.cancel, throwsAssertionError);
690 691 692
            done = true;
          });
          expect(done, isTrue);
693
        });
694 695
      });
    }
696
  });
697

698
  group('Output format', () {
699 700 701
    late FakeStdio fakeStdio;
    late SummaryStatus summaryStatus;
    late int called;
702 703

    setUp(() {
704
      fakeStdio = FakeStdio();
705 706 707 708 709
      called = 0;
      summaryStatus = SummaryStatus(
        message: 'Hello world',
        padding: 20,
        onFinish: () => called++,
710
        stdio: fakeStdio,
711
        stopwatch: FakeStopwatch(),
712 713 714
      );
    });

715 716
    List<String> outputStdout() => fakeStdio.writtenToStdout.join().split('\n');
    List<String> outputStderr() => fakeStdio.writtenToStderr.join().split('\n');
717

718 719 720
    testWithoutContext('Error logs are wrapped', () async {
      final Logger logger = StdoutLogger(
        terminal: AnsiTerminal(
721
          stdio: fakeStdio,
722 723
          platform: _kNoAnsiPlatform,
        ),
724
        stdio: fakeStdio,
725
        outputPreferences: OutputPreferences.test(wrapText: true, wrapColumn: 40),
726
      );
727
      logger.printError('0123456789' * 15);
728
      final List<String> lines = outputStderr();
729

730 731 732 733 734 735 736 737
      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));
    });

738
    testWithoutContext('AppRunLogger writes plain text statuses when no app is active', () async {
739 740 741
      final BufferLogger buffer = BufferLogger.test();
      final AppRunLogger logger = AppRunLogger(parent: buffer);

742
      logger.startProgress('Test status...').stop();
743 744 745 746

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

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

759 760 761 762 763 764 765 766 767 768 769
      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);
    });

770 771 772
    testWithoutContext('Error logs are wrapped and can have hanging indent.', () async {
      final Logger logger = StdoutLogger(
        terminal: AnsiTerminal(
773
          stdio: fakeStdio,
774 775
          platform: _kNoAnsiPlatform,
        ),
776
        stdio: fakeStdio,
777
        outputPreferences: OutputPreferences.test(wrapText: true, wrapColumn: 40),
778
      );
779
      logger.printError('0123456789' * 15, hangingIndent: 5);
780
      final List<String> lines = outputStderr();
781

782 783 784 785 786 787 788 789 790 791 792
      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);
    });

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

805 806 807 808 809 810 811 812 813 814 815
      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);
    });

816 817 818
    testWithoutContext('Stdout logs are wrapped', () async {
      final Logger logger = StdoutLogger(
        terminal: AnsiTerminal(
819
          stdio: fakeStdio,
820 821
          platform: _kNoAnsiPlatform,
        ),
822
        stdio: fakeStdio,
823
        outputPreferences: OutputPreferences.test(wrapText: true, wrapColumn: 40),
824
      );
825
      logger.printStatus('0123456789' * 15);
826
      final List<String> lines = outputStdout();
827

828 829 830 831 832 833 834 835
      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));
    });

836 837 838
    testWithoutContext('Stdout logs are wrapped and can be indented.', () async {
      final Logger logger = StdoutLogger(
        terminal: AnsiTerminal(
839
          stdio: fakeStdio,
840 841
          platform: _kNoAnsiPlatform,
        ),
842
        stdio: fakeStdio,
843
        outputPreferences: OutputPreferences.test(wrapText: true, wrapColumn: 40),
844
      );
845
      logger.printStatus('0123456789' * 15, indent: 5);
846
      final List<String> lines = outputStdout();
847

848 849 850 851 852 853 854 855 856 857 858
      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);
    });

859 860 861
    testWithoutContext('Stdout logs are wrapped and can have hanging indent.', () async {
      final Logger logger = StdoutLogger(
        terminal: AnsiTerminal(
862
          stdio: fakeStdio,
863 864
          platform: _kNoAnsiPlatform,
        ),
865
        stdio: fakeStdio,
866
        outputPreferences: OutputPreferences.test(wrapText: true, wrapColumn: 40)
867
      );
868
      logger.printStatus('0123456789' * 15, hangingIndent: 5);
869
      final List<String> lines = outputStdout();
870

871 872 873 874 875 876 877 878 879 880 881
      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);
    });

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

894 895 896 897 898 899 900 901 902 903
      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);
    });
904

905 906 907
    testWithoutContext('Error logs are red', () async {
      final Logger logger = StdoutLogger(
        terminal: AnsiTerminal(
908
          stdio: fakeStdio,
909
          platform: FakePlatform(stdoutSupportsAnsi: true),
910
        ),
911
        stdio: fakeStdio,
912 913
        outputPreferences: OutputPreferences.test(showColor: true),
      );
914
      logger.printError('Pants on fire!');
915
      final List<String> lines = outputStderr();
916

917 918
      expect(outputStdout().length, equals(1));
      expect(outputStdout().first, isEmpty);
919
      expect(lines[0], equals('${AnsiTerminal.red}Pants on fire!${AnsiTerminal.resetColor}'));
920 921
    });

922 923 924
    testWithoutContext('Stdout logs are not colored', () async {
      final Logger logger = StdoutLogger(
        terminal: AnsiTerminal(
925
          stdio: fakeStdio,
926 927
          platform: FakePlatform(),
        ),
928
        stdio: fakeStdio,
929 930
        outputPreferences:  OutputPreferences.test(showColor: true),
      );
931
      logger.printStatus('All good.');
932

933 934 935 936 937 938
      final List<String> lines = outputStdout();
      expect(outputStderr().length, equals(1));
      expect(outputStderr().first, isEmpty);
      expect(lines[0], equals('All good.'));
    });

939 940 941 942 943 944 945 946 947 948
    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');
949
      final String stdout = fakeStdio.writtenToStdout.join();
950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969
      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');
970
      final String stdout = fakeStdio.writtenToStdout.join();
971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990
      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');
991
      final String stdout = fakeStdio.writtenToStdout.join();
992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
      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');
1015
      final String stdout = fakeStdio.writtenToStdout.join();
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
      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');
1037
      final String stdout = fakeStdio.writtenToStdout.join();
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
      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');
1066
      final String stdout = fakeStdio.writtenToStdout.join();
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 1094 1095 1096 1097
      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');
1098
      final String stdout = fakeStdio.writtenToStdout.join();
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
      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'
        ),
      );
    });


1117
    testWithoutContext('Stdout startProgress on non-color terminal', () async {
1118 1119 1120
      final FakeStopwatch fakeStopwatch = FakeStopwatch();
      final Logger logger = StdoutLogger(
        terminal: AnsiTerminal(
1121
          stdio: fakeStdio,
1122 1123
          platform: _kNoAnsiPlatform,
        ),
1124
        stdio: fakeStdio,
1125
        outputPreferences: OutputPreferences.test(),
1126
        stopwatchFactory: FakeStopwatchFactory(stopwatch: fakeStopwatch),
1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140
      );
      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', '']);
1141 1142
    });

1143 1144 1145 1146 1147
    testWithoutContext('SummaryStatus works when canceled', () async {
      final SummaryStatus summaryStatus = SummaryStatus(
        message: 'Hello world',
        padding: 20,
        onFinish: () => called++,
1148
        stdio: fakeStdio,
1149 1150
        stopwatch: FakeStopwatch(),
      );
1151
      summaryStatus.start();
1152
      final List<String> lines = outputStdout();
1153 1154 1155 1156 1157 1158
      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();
1159 1160 1161 1162
      expect(outputStdout(), <String>[
        'Hello world              ',
        '',
      ]);
1163 1164

      // Verify that stopping or canceling multiple times throws.
Dan Field's avatar
Dan Field committed
1165 1166
      expect(summaryStatus.cancel, throwsAssertionError);
      expect(summaryStatus.stop, throwsAssertionError);
1167
    });
1168

1169
    testWithoutContext('SummaryStatus works when stopped', () async {
1170
      summaryStatus.start();
1171
      final List<String> lines = outputStdout();
1172 1173 1174 1175 1176
      expect(lines[0], startsWith('Hello world              '));
      expect(lines.length, equals(1));

      // Verify a stop prints the time.
      summaryStatus.stop();
1177 1178 1179 1180
      expect(outputStdout(), <String>[
        'Hello world                   0ms',
        '',
      ]);
1181 1182

      // Verify that stopping or canceling multiple times throws.
Dan Field's avatar
Dan Field committed
1183 1184
      expect(summaryStatus.stop, throwsAssertionError);
      expect(summaryStatus.cancel, throwsAssertionError);
1185
    });
1186

1187
    testWithoutContext('sequential startProgress calls with StdoutLogger', () async {
1188 1189
      final Logger logger = StdoutLogger(
        terminal: AnsiTerminal(
1190
          stdio: fakeStdio,
1191 1192
          platform: _kNoAnsiPlatform,
        ),
1193
        stdio: fakeStdio,
1194
        outputPreferences: OutputPreferences.test(),
1195
      );
1196 1197
      logger.startProgress('AAA').stop();
      logger.startProgress('BBB').stop();
1198
      final List<String> output = outputStdout();
1199

1200
      expect(output.length, equals(3));
1201

1202 1203 1204 1205 1206
      // 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')));
1207
    });
1208

1209
    testWithoutContext('sequential startProgress calls with VerboseLogger and StdoutLogger', () async {
1210 1211 1212
      final Logger logger = VerboseLogger(
        StdoutLogger(
          terminal: AnsiTerminal(
1213
            stdio: fakeStdio,
1214 1215
            platform: _kNoAnsiPlatform,
          ),
1216
          stdio: fakeStdio,
1217 1218
          outputPreferences: OutputPreferences.test(),
        ),
1219
        stopwatchFactory: FakeStopwatchFactory(),
1220
      );
1221 1222
      logger.startProgress('AAA').stop();
      logger.startProgress('BBB').stop();
1223

1224
      expect(outputStdout(), <Matcher>[
1225 1226 1227 1228
        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.*\)$'),
1229 1230 1231
        matches(r'^$'),
      ]);
    });
1232

1233
    testWithoutContext('sequential startProgress calls with BufferLogger', () async {
1234 1235
      final BufferLogger logger = BufferLogger(
        terminal: AnsiTerminal(
1236
          stdio: fakeStdio,
1237 1238 1239 1240
          platform: _kNoAnsiPlatform,
        ),
        outputPreferences: OutputPreferences.test(),
      );
1241 1242
      logger.startProgress('AAA').stop();
      logger.startProgress('BBB').stop();
1243 1244

      expect(logger.statusText, 'AAA\nBBB\n');
1245
    });
1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260

    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');
    });
1261
  });
1262
}
1263

1264 1265 1266
/// A fake [Logger] that throws the [Invocation] for any method call.
class FakeLogger implements Logger {
  @override
1267
  dynamic noSuchMethod(Invocation invocation) => throw invocation; // ignore: only_throw_errors
1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297
}

/// 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)));
1298 1299

class FakeStdout extends Fake implements Stdout {
1300
  FakeStdout({required this.syncError, this.completeWithError = false});
1301 1302 1303 1304 1305 1306

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

  @override
1307
  void write(Object? object) {
1308
    if (syncError) {
1309
      throw Exception('Error!');
1310 1311 1312 1313 1314 1315
    }
    Zone.current.runUnaryGuarded<void>((_) {
      if (completeWithError) {
        _completer.completeError(Exception('Some pipe error'));
      } else {
        _completer.complete();
1316
        throw Exception('Error!');
1317 1318 1319 1320 1321 1322 1323
      }
    }, null);
  }

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