logger_test.dart 40.3 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 6
// @dart = 2.8

7
import 'dart:async';
8

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

19
import '../../src/common.dart';
20
import '../../src/fakes.dart';
21

22
final Platform _kNoAnsiPlatform = FakePlatform(stdoutSupportsAnsi: false);
23 24 25 26
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);
27

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

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

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

    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']);
  });

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 228 229
  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),
230
      throwsStateError,
231 232 233
    );
  });

234
  group('AppContext', () {
235 236 237 238 239
    FakeStopwatch fakeStopWatch;

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

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

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

254 255
      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$'));
256
      expect(mockLogger.traceText, '');
257
      expect(mockLogger.errorText, matches( r'^\[ (?: {0,2}\+[0-9]{1,4} ms|       )\] Helpless!\n$'));
258
    });
259

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

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

      expect(
          mockLogger.statusText,
278 279
          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$'));
280 281 282
      expect(mockLogger.traceText, '');
      expect(
          mockLogger.errorText,
283
          matches('^$red' r'\[ (?: {0,2}\+[0-9]{1,4} ms|       )\] ' '${bold}Helpless!$resetBold$resetColor' r'\n$'));
284
    });
285
  });
286

287
  testWithoutContext('Logger does not throw when stdio write throws synchronously', () async {
288 289
    final FakeStdout stdout = FakeStdout(syncError: true);
    final FakeStdout stderr = FakeStdout(syncError: true);
290
    final Stdio stdio = Stdio.test(stdout: stdout, stderr: stderr);
291 292 293 294 295 296 297 298
    final Logger logger = StdoutLogger(
      terminal: AnsiTerminal(
        stdio: stdio,
        platform: _kNoAnsiPlatform,
      ),
      stdio: stdio,
      outputPreferences: OutputPreferences.test(),
    );
299

300 301
    logger.printStatus('message');
    logger.printError('error message');
302 303 304
  });

  testWithoutContext('Logger does not throw when stdio write throws asynchronously', () async {
305 306
    final FakeStdout stdout = FakeStdout(syncError: false);
    final FakeStdout stderr = FakeStdout(syncError: false);
307
    final Stdio stdio = Stdio.test(stdout: stdout, stderr: stderr);
308 309 310 311 312 313 314 315 316 317
    final Logger logger = StdoutLogger(
      terminal: AnsiTerminal(
        stdio: stdio,
        platform: _kNoAnsiPlatform,
      ),
      stdio: stdio,
      outputPreferences: OutputPreferences.test(),
    );
    logger.printStatus('message');
    logger.printError('error message');
318 319 320

    await stdout.done;
    await stderr.done;
321 322
  });

323
  testWithoutContext('Logger does not throw when stdio completes done with an error', () async {
324 325
    final FakeStdout stdout = FakeStdout(syncError: false, completeWithError: true);
    final FakeStdout stderr = FakeStdout(syncError: false, completeWithError: true);
326 327 328 329 330 331 332 333 334 335 336
    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');
337

338 339
    expect(() async => stdout.done, throwsException);
    expect(() async => stderr.done, throwsException);
340 341
  });

342
  group('Spinners', () {
343
    FakeStdio mockStdio;
344
    FakeStopwatch mockStopwatch;
345
    FakeStopwatchFactory stopwatchFactory;
346
    int called;
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
    final List<Platform> testPlatforms = <Platform>[
      FakePlatform(
        operatingSystem: 'linux',
        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>[],
      ),
    ];
374
    final RegExp secondDigits = RegExp(r'[0-9,.]*[0-9]m?s');
375

376
    setUp(() {
377
      mockStopwatch = FakeStopwatch();
378
      mockStdio = FakeStdio();
379
      called = 0;
380
      stopwatchFactory = FakeStopwatchFactory(stopwatch: mockStopwatch);
381 382
    });

383 384
    List<String> outputStdout() => mockStdio.writtenToStdout.join('').split('\n');
    List<String> outputStderr() => mockStdio.writtenToStderr.join('').split('\n');
385

386
    void doWhileAsync(FakeAsync time, bool Function() doThis) {
387
      do {
388
        mockStopwatch.elapsed += const Duration(milliseconds: 1);
389 390
        time.elapse(const Duration(milliseconds: 1));
      } while (doThis());
391 392
    }

393 394 395 396 397 398
    for (final Platform testPlatform in testPlatforms) {
      group('(${testPlatform.operatingSystem})', () {
        Platform platform;
        Platform ansiPlatform;
        AnsiTerminal terminal;
        AnsiTerminal coloredTerminal;
399
        SpinnerStatus spinnerStatus;
400

401
        setUp(() {
402 403
          platform = FakePlatform(stdoutSupportsAnsi: false);
          ansiPlatform = FakePlatform(stdoutSupportsAnsi: true);
404 405 406 407 408 409 410 411 412 413

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

414
          spinnerStatus = SpinnerStatus(
415 416 417
            message: 'Hello world',
            padding: 20,
            onFinish: () => called += 1,
418
            stdio: mockStdio,
419
            stopwatch: stopwatchFactory.createStopwatch(),
420
            terminal: terminal,
421
          );
422
        });
423

424
        testWithoutContext('AnonymousSpinnerStatus works (1)', () async {
425 426 427
          bool done = false;
          mockStopwatch = FakeStopwatch();
          FakeAsync().run((FakeAsync time) {
428
            final AnonymousSpinnerStatus spinner = AnonymousSpinnerStatus(
429 430 431 432
              stdio: mockStdio,
              stopwatch: stopwatchFactory.createStopwatch(),
              terminal: terminal,
            )..start();
433
            doWhileAsync(time, () => spinner.ticks < 10);
434 435 436
            List<String> lines = outputStdout();
            expect(lines[0], startsWith(
              terminal.supportsEmoji
437 438
                ? '⣽\b⣻\b⢿\b⡿\b⣟\b⣯\b⣷\b⣾\b⣽\b⣻'
                : '\\\b|\b/\b-\b\\\b|\b/\b-'
439 440 441 442 443
              ),
            );
            expect(lines[0].endsWith('\n'), isFalse);
            expect(lines.length, equals(1));

444
            spinner.stop();
445 446 447 448 449 450
            lines = outputStdout();

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

            // Verify that stopping or canceling multiple times throws.
451 452
            expect(spinner.stop, throwsAssertionError);
            expect(spinner.cancel, throwsAssertionError);
453 454 455
            done = true;
          });
          expect(done, isTrue);
456
        });
457

458
        testWithoutContext('Stdout startProgress on colored terminal', () async {
459 460 461 462 463 464 465 466 467 468 469 470 471
          final Logger logger = StdoutLogger(
            terminal: coloredTerminal,
            stdio: mockStdio,
            outputPreferences: OutputPreferences.test(showColor: true),
            stopwatchFactory: stopwatchFactory,
          );
          final Status status = logger.startProgress(
            'Hello',
            progressId: null,
            progressIndicatorPadding: 20, // this minus the "Hello" equals the 15 below.
          );
          expect(outputStderr().length, equals(1));
          expect(outputStderr().first, isEmpty);
472 473
          // 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.
474 475 476
          expect(
            outputStdout().join('\n'),
            matches(terminal.supportsEmoji
477 478
              ? r'^Hello {15} {4} {8}⣽$'
              : r'^Hello {15} {4} {8}\\$'),
479 480 481 482 483 484 485
          );
          mockStopwatch.elapsed = const Duration(seconds: 4, milliseconds: 100);
          status.stop();
          expect(
            outputStdout().join('\n'),
            matches(
              terminal.supportsEmoji
486 487
              ? 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]$',
488 489
            ),
          );
490
        });
491

492 493 494 495 496 497
        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,
498
              stdio: mockStdio,
499 500 501
              outputPreferences: OutputPreferences.test(showColor: true),
              stopwatchFactory: stopwatchFactory,
            );
502
            const String message = "Knock Knock, Who's There";
503
            final Status status = logger.startProgress(
504 505
              message,
              progressIndicatorPadding: 10, // ignored
506 507 508 509 510
            );
            logger.printStatus('Rude Interrupting Cow');
            status.stop();
            final String a = terminal.supportsEmoji ? '⣽' : r'\';
            final String b = terminal.supportsEmoji ? '⣻' : '|';
511
            const String blankLine = '\r\x1B[K';
512 513
            expect(
              outputStdout().join('\n'),
514 515
              '$message' // initial message
              '${" " * 4}${" " * 8}' // margin (4) and space for the time at the end (8)
516
              // ignore: missing_whitespace_between_adjacent_strings
517 518
              '$a' // first tick
              '$blankLine' // clearing the line
519
              'Rude Interrupting Cow\n' // message
520 521 522
              '$message' // message restoration
              '${" " * 4}${" " * 8}' // margin (4) and space for the time at the end (8)
              '$b' // second tick
523
              // ignore: missing_whitespace_between_adjacent_strings
524 525
              '\b \b' // backspace the tick, wipe the tick, backspace the wipe
              '\b\b\b\b\b\b\b' // backspace the space for the time
526 527 528 529 530
              '    5.0s\n', // replacing it with the time
            );
            done = true;
          });
          expect(done, isTrue);
531 532
        });

533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
        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 {
564 565
          bool done = false;
          FakeAsync().run((FakeAsync time) {
566
            spinnerStatus.start();
567
            mockStopwatch.elapsed = const Duration(seconds: 1);
568
            doWhileAsync(time, () => spinnerStatus.ticks < 10);
569 570 571 572
            List<String> lines = outputStdout();

            expect(lines[0], startsWith(
              terminal.supportsEmoji
573 574
              ? 'Hello world                     ⣽\b⣻\b⢿\b⡿\b⣟\b⣯\b⣷\b⣾\b⣽\b⣻'
              : 'Hello world                     \\\b|\b/\b-\b\\\b|\b/\b-\b\\\b|'
575 576 577 578 579
            ));
            expect(lines.length, equals(1));
            expect(lines[0].endsWith('\n'), isFalse);

            // Verify a cancel does _not_ print the time and prints a newline.
580
            spinnerStatus.cancel();
581 582 583 584 585
            lines = outputStdout();
            final List<Match> matches = secondDigits.allMatches(lines[0]).toList();
            expect(matches, isEmpty);
            final String leading = terminal.supportsEmoji ? '⣻' : '|';

586
            expect(lines[0], endsWith('$leading\b \b'));
587 588 589 590 591
            expect(called, equals(1));
            expect(lines.length, equals(2));
            expect(lines[1], equals(''));

            // Verify that stopping or canceling multiple times throws.
592 593
            expect(spinnerStatus.cancel, throwsAssertionError);
            expect(spinnerStatus.stop, throwsAssertionError);
594 595 596
            done = true;
          });
          expect(done, isTrue);
597 598
        });

599
        testWithoutContext('SpinnerStatus works when stopped', () async {
600 601
          bool done = false;
          FakeAsync().run((FakeAsync time) {
602
            spinnerStatus.start();
603
            mockStopwatch.elapsed = const Duration(seconds: 1);
604
            doWhileAsync(time, () => spinnerStatus.ticks < 10);
605 606 607 608 609 610
            List<String> lines = outputStdout();

            expect(lines, hasLength(1));
            expect(
              lines[0],
              terminal.supportsEmoji
611 612
                ? 'Hello world                     ⣽\b⣻\b⢿\b⡿\b⣟\b⣯\b⣷\b⣾\b⣽\b⣻'
                : 'Hello world                     \\\b|\b/\b-\b\\\b|\b/\b-\b\\\b|'
613 614 615
            );

            // Verify a stop prints the time.
616
            spinnerStatus.stop();
617 618 619 620
            lines = outputStdout();
            expect(lines, hasLength(2));
            expect(lines[0], matches(
              terminal.supportsEmoji
621 622
                ? 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$'
623 624 625 626 627 628 629 630 631 632 633 634 635
            ));
            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;

            expect(lines[0], endsWith(match.group(0)));
            expect(called, equals(1));
            expect(lines.length, equals(2));
            expect(lines[1], equals(''));

            // Verify that stopping or canceling multiple times throws.
636 637
            expect(spinnerStatus.stop, throwsAssertionError);
            expect(spinnerStatus.cancel, throwsAssertionError);
638 639 640
            done = true;
          });
          expect(done, isTrue);
641
        });
642 643
      });
    }
644
  });
645

646
  group('Output format', () {
647
    FakeStdio fakeStdio;
648 649 650 651
    SummaryStatus summaryStatus;
    int called;

    setUp(() {
652
      fakeStdio = FakeStdio();
653 654 655 656 657
      called = 0;
      summaryStatus = SummaryStatus(
        message: 'Hello world',
        padding: 20,
        onFinish: () => called++,
658
        stdio: fakeStdio,
659
        stopwatch: FakeStopwatch(),
660 661 662
      );
    });

663 664
    List<String> outputStdout() => fakeStdio.writtenToStdout.join('').split('\n');
    List<String> outputStderr() => fakeStdio.writtenToStderr.join('').split('\n');
665

666 667 668
    testWithoutContext('Error logs are wrapped', () async {
      final Logger logger = StdoutLogger(
        terminal: AnsiTerminal(
669
          stdio: fakeStdio,
670 671
          platform: _kNoAnsiPlatform,
        ),
672
        stdio: fakeStdio,
673 674
        outputPreferences: OutputPreferences.test(wrapText: true, wrapColumn: 40, showColor: false),
      );
675
      logger.printError('0123456789' * 15);
676
      final List<String> lines = outputStderr();
677

678 679 680 681 682 683 684 685
      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));
    });

686
    testWithoutContext('AppRunLogger writes plain text statuses when no app is active', () async {
687 688 689 690 691 692 693 694
      final BufferLogger buffer = BufferLogger.test();
      final AppRunLogger logger = AppRunLogger(parent: buffer);

      logger.startProgress('Test status...', timeout: null).stop();

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

695 696 697
    testWithoutContext('Error logs are wrapped and can be indented.', () async {
      final Logger logger = StdoutLogger(
        terminal: AnsiTerminal(
698
          stdio: fakeStdio,
699 700
          platform: _kNoAnsiPlatform,
        ),
701
        stdio: fakeStdio,
702 703
        outputPreferences: OutputPreferences.test(wrapText: true, wrapColumn: 40, showColor: false),
      );
704
      logger.printError('0123456789' * 15, indent: 5);
705
      final List<String> lines = outputStderr();
706

707 708 709 710 711 712 713 714 715 716 717
      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);
    });

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

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

741 742 743
    testWithoutContext('Error logs are wrapped, indented, and can have hanging indent.', () async {
      final Logger logger = StdoutLogger(
        terminal: AnsiTerminal(
744
          stdio: fakeStdio,
745 746
          platform: _kNoAnsiPlatform,
        ),
747
        stdio: fakeStdio,
748 749
        outputPreferences: OutputPreferences.test(wrapText: true, wrapColumn: 40, showColor: false),
      );
750
      logger.printError('0123456789' * 15, indent: 4, hangingIndent: 5);
751
      final List<String> lines = outputStderr();
752

753 754 755 756 757 758 759 760 761 762 763
      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);
    });

764 765 766
    testWithoutContext('Stdout logs are wrapped', () async {
      final Logger logger = StdoutLogger(
        terminal: AnsiTerminal(
767
          stdio: fakeStdio,
768 769
          platform: _kNoAnsiPlatform,
        ),
770
        stdio: fakeStdio,
771 772
        outputPreferences: OutputPreferences.test(wrapText: true, wrapColumn: 40, showColor: false),
      );
773
      logger.printStatus('0123456789' * 15);
774
      final List<String> lines = outputStdout();
775

776 777 778 779 780 781 782 783
      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));
    });

784 785 786
    testWithoutContext('Stdout logs are wrapped and can be indented.', () async {
      final Logger logger = StdoutLogger(
        terminal: AnsiTerminal(
787
          stdio: fakeStdio,
788 789
          platform: _kNoAnsiPlatform,
        ),
790
        stdio: fakeStdio,
791 792
        outputPreferences: OutputPreferences.test(wrapText: true, wrapColumn: 40, showColor: false),
      );
793
      logger.printStatus('0123456789' * 15, indent: 5);
794
      final List<String> lines = outputStdout();
795

796 797 798 799 800 801 802 803 804 805 806
      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);
    });

807 808 809
    testWithoutContext('Stdout logs are wrapped and can have hanging indent.', () async {
      final Logger logger = StdoutLogger(
        terminal: AnsiTerminal(
810
          stdio: fakeStdio,
811 812
          platform: _kNoAnsiPlatform,
        ),
813
        stdio: fakeStdio,
814
        outputPreferences: OutputPreferences.test(wrapText: true, wrapColumn: 40, showColor: false)
815
      );
816
      logger.printStatus('0123456789' * 15, hangingIndent: 5);
817
      final List<String> lines = outputStdout();
818

819 820 821 822 823 824 825 826 827 828 829
      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);
    });

830
    testWithoutContext('Stdout logs are wrapped, indented, and can have hanging indent.', () async {
831 832
      final Logger logger = StdoutLogger(
        terminal: AnsiTerminal(
833
          stdio: fakeStdio,
834 835
          platform: _kNoAnsiPlatform,
        ),
836
        stdio: fakeStdio,
837 838
        outputPreferences: OutputPreferences.test(wrapText: true, wrapColumn: 40, showColor: false),
      );
839
      logger.printStatus('0123456789' * 15, indent: 4, hangingIndent: 5);
840
      final List<String> lines = outputStdout();
841

842 843 844 845 846 847 848 849 850 851
      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);
    });
852

853 854 855
    testWithoutContext('Error logs are red', () async {
      final Logger logger = StdoutLogger(
        terminal: AnsiTerminal(
856
          stdio: fakeStdio,
857
          platform: FakePlatform(stdoutSupportsAnsi: true),
858
        ),
859
        stdio: fakeStdio,
860 861
        outputPreferences: OutputPreferences.test(showColor: true),
      );
862
      logger.printError('Pants on fire!');
863
      final List<String> lines = outputStderr();
864

865 866
      expect(outputStdout().length, equals(1));
      expect(outputStdout().first, isEmpty);
867
      expect(lines[0], equals('${AnsiTerminal.red}Pants on fire!${AnsiTerminal.resetColor}'));
868 869
    });

870 871 872
    testWithoutContext('Stdout logs are not colored', () async {
      final Logger logger = StdoutLogger(
        terminal: AnsiTerminal(
873
          stdio: fakeStdio,
874 875
          platform: FakePlatform(),
        ),
876
        stdio: fakeStdio,
877 878
        outputPreferences:  OutputPreferences.test(showColor: true),
      );
879
      logger.printStatus('All good.');
880

881 882 883 884 885 886
      final List<String> lines = outputStdout();
      expect(outputStderr().length, equals(1));
      expect(outputStderr().first, isEmpty);
      expect(lines[0], equals('All good.'));
    });

887 888 889
    testWithoutContext('Stdout printStatus handle null inputs on colored terminal', () async {
      final Logger logger = StdoutLogger(
        terminal: AnsiTerminal(
890
          stdio: fakeStdio,
891 892
          platform: FakePlatform(),
        ),
893
        stdio: fakeStdio,
894 895
        outputPreferences: OutputPreferences.test(showColor: true),
      );
896 897 898 899 900 901 902
      logger.printStatus(
        null,
        emphasis: null,
        color: null,
        newline: null,
        indent: null,
      );
903
      final List<String> lines = outputStdout();
904

905 906 907 908 909
      expect(outputStderr().length, equals(1));
      expect(outputStderr().first, isEmpty);
      expect(lines[0], equals(''));
    });

910 911 912
    testWithoutContext('Stdout printStatus handle null inputs on non-color terminal', () async {
      final Logger logger = StdoutLogger(
        terminal: AnsiTerminal(
913
          stdio: fakeStdio,
914 915
          platform: _kNoAnsiPlatform,
        ),
916
        stdio: fakeStdio,
917 918
        outputPreferences: OutputPreferences.test(showColor: false),
      );
919 920 921 922 923 924 925
      logger.printStatus(
        null,
        emphasis: null,
        color: null,
        newline: null,
        indent: null,
      );
926 927 928 929 930 931
      final List<String> lines = outputStdout();
      expect(outputStderr().length, equals(1));
      expect(outputStderr().first, isEmpty);
      expect(lines[0], equals(''));
    });

932
    testWithoutContext('Stdout startProgress on non-color terminal', () async {
933 934 935
      final FakeStopwatch fakeStopwatch = FakeStopwatch();
      final Logger logger = StdoutLogger(
        terminal: AnsiTerminal(
936
          stdio: fakeStdio,
937 938
          platform: _kNoAnsiPlatform,
        ),
939
        stdio: fakeStdio,
940
        outputPreferences: OutputPreferences.test(showColor: false),
941
        stopwatchFactory: FakeStopwatchFactory(stopwatch: fakeStopwatch),
942 943 944 945 946 947 948 949 950 951 952 953 954 955 956
      );
      final Status status = logger.startProgress(
        'Hello',
        progressId: null,
        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', '']);
957 958
    });

959 960 961 962 963
    testWithoutContext('SummaryStatus works when canceled', () async {
      final SummaryStatus summaryStatus = SummaryStatus(
        message: 'Hello world',
        padding: 20,
        onFinish: () => called++,
964
        stdio: fakeStdio,
965 966
        stopwatch: FakeStopwatch(),
      );
967
      summaryStatus.start();
968
      final List<String> lines = outputStdout();
969 970 971 972 973 974
      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();
975 976 977 978
      expect(outputStdout(), <String>[
        'Hello world              ',
        '',
      ]);
979 980

      // Verify that stopping or canceling multiple times throws.
Dan Field's avatar
Dan Field committed
981 982
      expect(summaryStatus.cancel, throwsAssertionError);
      expect(summaryStatus.stop, throwsAssertionError);
983
    });
984

985
    testWithoutContext('SummaryStatus works when stopped', () async {
986
      summaryStatus.start();
987
      final List<String> lines = outputStdout();
988 989 990 991 992
      expect(lines[0], startsWith('Hello world              '));
      expect(lines.length, equals(1));

      // Verify a stop prints the time.
      summaryStatus.stop();
993 994 995 996
      expect(outputStdout(), <String>[
        'Hello world                   0ms',
        '',
      ]);
997 998

      // Verify that stopping or canceling multiple times throws.
Dan Field's avatar
Dan Field committed
999 1000
      expect(summaryStatus.stop, throwsAssertionError);
      expect(summaryStatus.cancel, throwsAssertionError);
1001
    });
1002

1003
    testWithoutContext('sequential startProgress calls with StdoutLogger', () async {
1004 1005
      final Logger logger = StdoutLogger(
        terminal: AnsiTerminal(
1006
          stdio: fakeStdio,
1007 1008
          platform: _kNoAnsiPlatform,
        ),
1009
        stdio: fakeStdio,
1010 1011
        outputPreferences: OutputPreferences.test(showColor: false),
      );
1012 1013
      logger.startProgress('AAA').stop();
      logger.startProgress('BBB').stop();
1014
      final List<String> output = outputStdout();
1015

1016
      expect(output.length, equals(3));
1017

1018 1019 1020 1021 1022
      // 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')));
1023
    });
1024

1025
    testWithoutContext('sequential startProgress calls with VerboseLogger and StdoutLogger', () async {
1026 1027 1028
      final Logger logger = VerboseLogger(
        StdoutLogger(
          terminal: AnsiTerminal(
1029
            stdio: fakeStdio,
1030 1031
            platform: _kNoAnsiPlatform,
          ),
1032
          stdio: fakeStdio,
1033 1034
          outputPreferences: OutputPreferences.test(),
        ),
1035
        stopwatchFactory: FakeStopwatchFactory(),
1036
      );
1037 1038
      logger.startProgress('AAA').stop();
      logger.startProgress('BBB').stop();
1039

1040
      expect(outputStdout(), <Matcher>[
1041 1042 1043 1044
        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.*\)$'),
1045 1046 1047
        matches(r'^$'),
      ]);
    });
1048

1049
    testWithoutContext('sequential startProgress calls with BufferLogger', () async {
1050 1051
      final BufferLogger logger = BufferLogger(
        terminal: AnsiTerminal(
1052
          stdio: fakeStdio,
1053 1054 1055 1056
          platform: _kNoAnsiPlatform,
        ),
        outputPreferences: OutputPreferences.test(),
      );
1057 1058
      logger.startProgress('AAA').stop();
      logger.startProgress('BBB').stop();
1059 1060

      expect(logger.statusText, 'AAA\nBBB\n');
1061
    });
1062
  });
1063
}
1064

1065 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 1094 1095 1096 1097 1098
/// A fake [Logger] that throws the [Invocation] for any method call.
class FakeLogger implements Logger {
  @override
  dynamic noSuchMethod(Invocation invocation) => throw invocation;
}

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

class FakeStdout extends Fake implements Stdout {
  FakeStdout({@required this.syncError, this.completeWithError = false});

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

  @override
  void write(Object object) {
    if (syncError) {
      throw 'Error!';
    }
    Zone.current.runUnaryGuarded<void>((_) {
      if (completeWithError) {
        _completer.completeError(Exception('Some pipe error'));
      } else {
        _completer.complete();
        throw 'Error!';
      }
    }, null);
  }

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