logger_test.dart 32.9 KB
Newer Older
1 2 3 4
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5 6
import 'dart:convert' show jsonEncode;

7
import 'package:flutter_tools/src/base/context.dart';
8
import 'package:flutter_tools/src/base/io.dart';
9
import 'package:flutter_tools/src/base/logger.dart';
10
import 'package:flutter_tools/src/base/platform.dart';
11
import 'package:flutter_tools/src/base/terminal.dart';
12
import 'package:quiver/testing/async.dart';
13

14 15 16
import '../../src/common.dart';
import '../../src/context.dart';
import '../../src/mocks.dart';
17

18 19
final Generator _kNoAnsiPlatform = () => FakePlatform.fromPlatform(const LocalPlatform())..stdoutSupportsAnsi = false;

20
void main() {
21 22
  final String red = RegExp.escape(AnsiTerminal.red);
  final String bold = RegExp.escape(AnsiTerminal.bold);
23 24
  final String resetBold = RegExp.escape(AnsiTerminal.resetBold);
  final String resetColor = RegExp.escape(AnsiTerminal.resetColor);
25

26
  group('AppContext', () {
27
    testUsingContext('error', () async {
28 29
      final BufferLogger mockLogger = BufferLogger();
      final VerboseLogger verboseLogger = VerboseLogger(mockLogger);
30 31 32 33 34

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

35 36
      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$'));
37
      expect(mockLogger.traceText, '');
38
      expect(mockLogger.errorText, matches( r'^\[ (?: {0,2}\+[0-9]{1,4} ms|       )\] Helpless!\n$'));
39
    }, overrides: <Type, Generator>{
40
      OutputPreferences: () => OutputPreferences(showColor: false),
41
      Platform: _kNoAnsiPlatform,
42
    });
43

44
    testUsingContext('ANSI colored errors', () async {
45 46 47 48 49 50 51 52 53
      final BufferLogger mockLogger = BufferLogger();
      final VerboseLogger verboseLogger = VerboseLogger(mockLogger);

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

      expect(
          mockLogger.statusText,
54 55
          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$'));
56 57 58
      expect(mockLogger.traceText, '');
      expect(
          mockLogger.errorText,
59
          matches('^$red' r'\[ (?: {0,2}\+[0-9]{1,4} ms|       )\] ' '${bold}Helpless!$resetBold$resetColor' r'\n$'));
60
    }, overrides: <Type, Generator>{
61 62
      OutputPreferences: () => OutputPreferences(showColor: true),
      Platform: () => FakePlatform()..stdoutSupportsAnsi = true,
63
    });
64
  });
65 66 67

  group('Spinners', () {
    MockStdio mockStdio;
68
    FakeStopwatch mockStopwatch;
69
    int called;
70
    const List<String> testPlatforms = <String>['linux', 'macos', 'windows', 'fuchsia'];
71
    final RegExp secondDigits = RegExp(r'[0-9,.]*[0-9]m?s');
72

73 74 75
    AnsiStatus _createAnsiStatus() {
      mockStopwatch = FakeStopwatch();
      return AnsiStatus(
76
        message: 'Hello world',
77
        timeout: const Duration(seconds: 2),
78
        padding: 20,
79
        onFinish: () => called += 1,
80
      );
81 82 83 84 85
    }

    setUp(() {
      mockStdio = MockStdio();
      called = 0;
86 87
    });

88 89
    List<String> outputStdout() => mockStdio.writtenToStdout.join('').split('\n');
    List<String> outputStderr() => mockStdio.writtenToStderr.join('').split('\n');
90

91 92 93 94
    void doWhileAsync(FakeAsync time, bool doThis()) {
      do {
        time.elapse(const Duration(milliseconds: 1));
      } while (doThis());
95 96
    }

97
    for (String testOs in testPlatforms) {
98
      testUsingContext('AnsiSpinner works for $testOs (1)', () async {
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
        bool done = false;
        FakeAsync().run((FakeAsync time) {
          final AnsiSpinner ansiSpinner = AnsiSpinner(
            timeout: const Duration(hours: 10),
          )..start();
          doWhileAsync(time, () => ansiSpinner.ticks < 10);
          List<String> lines = outputStdout();
          expect(lines[0], startsWith(
            platform.isWindows
              ? ' \b\\\b|\b/\b-\b\\\b|\b/\b-'
              : ' \b⣽\b⣻\b⢿\b⡿\b⣟\b⣯\b⣷\b⣾\b⣽\b⣻'
            ),
          );
          expect(lines[0].endsWith('\n'), isFalse);
          expect(lines.length, equals(1));
114
          ansiSpinner.stop();
115 116 117 118 119 120 121 122 123 124 125 126 127 128
          lines = outputStdout();
          expect(lines[0], endsWith('\b \b'));
          expect(lines.length, equals(1));

          // Verify that stopping or canceling multiple times throws.
          expect(() {
            ansiSpinner.stop();
          }, throwsA(isInstanceOf<AssertionError>()));
          expect(() {
            ansiSpinner.cancel();
          }, throwsA(isInstanceOf<AssertionError>()));
          done = true;
        });
        expect(done, isTrue);
129 130
      }, overrides: <Type, Generator>{
        Platform: () => FakePlatform(operatingSystem: testOs),
131
        Stdio: () => mockStdio,
132 133
      });

134
      testUsingContext('AnsiSpinner works for $testOs (2)', () async {
135
        bool done = false;
136 137
        mockStopwatch = FakeStopwatch();
        FakeAsync().run((FakeAsync time) {
138
          final AnsiSpinner ansiSpinner = AnsiSpinner(
139
            timeout: const Duration(seconds: 2),
140
          )..start();
141
          mockStopwatch.elapsed = const Duration(seconds: 1);
142
          doWhileAsync(time, () => ansiSpinner.ticks < 10); // one second
143
          expect(ansiSpinner.seemsSlow, isFalse);
144
          expect(outputStdout().join('\n'), isNot(contains('This is taking an unexpectedly long time.')));
145
          mockStopwatch.elapsed = const Duration(seconds: 3);
146
          doWhileAsync(time, () => ansiSpinner.ticks < 30); // three seconds
147
          expect(ansiSpinner.seemsSlow, isTrue);
148 149
          // Check the 2nd line to verify there's a newline before the warning
          expect(outputStdout()[1], contains('This is taking an unexpectedly long time.'));
150 151 152 153 154 155 156 157
          ansiSpinner.stop();
          expect(outputStdout().join('\n'), isNot(contains('(!)')));
          done = true;
        });
        expect(done, isTrue);
      }, overrides: <Type, Generator>{
        Platform: () => FakePlatform(operatingSystem: testOs),
        Stdio: () => mockStdio,
158
        Stopwatch: () => mockStopwatch,
159 160 161 162 163
      });

      testUsingContext('Stdout startProgress on colored terminal for $testOs', () async {
        bool done = false;
        FakeAsync().run((FakeAsync time) {
164
          final Logger logger = context.get<Logger>();
165 166 167
          final Status status = logger.startProgress(
            'Hello',
            progressId: null,
168
            timeout: timeoutConfiguration.slowOperation,
169 170 171 172 173 174 175 176 177 178 179 180 181
            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(platform.isWindows ? r'^Hello {15} {5} {8}[\b]{8} {7}\\$' :
                                                                         r'^Hello {15} {5} {8}[\b]{8} {7}⣽$'));
          status.stop();
          expect(outputStdout().join('\n'), matches(platform.isWindows ? r'^Hello {15} {5} {8}[\b]{8} {7}\\[\b]{8} {8}[\b]{8}[\d, ]{4}[\d]\.[\d]s[\n]$' :
                                                                         r'^Hello {15} {5} {8}[\b]{8} {7}⣽[\b]{8} {8}[\b]{8}[\d, ]{4}[\d]\.[\d]s[\n]$'));
          done = true;
        });
        expect(done, isTrue);
182
      }, overrides: <Type, Generator>{
183 184 185
        Logger: () => StdoutLogger(),
        OutputPreferences: () => OutputPreferences(showColor: true),
        Platform: () => FakePlatform(operatingSystem: testOs)..stdoutSupportsAnsi = true,
186 187 188
        Stdio: () => mockStdio,
      });

189 190 191
      testUsingContext('Stdout startProgress on colored terminal pauses on $testOs', () async {
        bool done = false;
        FakeAsync().run((FakeAsync time) {
192
          final Logger logger = context.get<Logger>();
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
          final Status status = logger.startProgress(
            'Knock Knock, Who\'s There',
            timeout: const Duration(days: 10),
            progressIndicatorPadding: 10,
          );
          logger.printStatus('Rude Interrupting Cow');
          status.stop();
          final String a = platform.isWindows ? '\\' : '⣽';
          final String b = platform.isWindows ? '|' : '⣻';
          expect(
            outputStdout().join('\n'),
            'Knock Knock, Who\'s There     ' // initial message
            '        ' // placeholder so that spinner can backspace on its first tick
            '\b\b\b\b\b\b\b\b       $a' // first tick
            '\b\b\b\b\b\b\b\b        ' // clearing the spinner
            '\b\b\b\b\b\b\b\b' // clearing the clearing of the spinner
            '\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b                             ' // clearing the message
            '\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b' // clearing the clearing of the message
            'Rude Interrupting Cow\n' // message
            'Knock Knock, Who\'s There     ' // message restoration
            '        ' // placeholder so that spinner can backspace on its second tick
            '\b\b\b\b\b\b\b\b       $b' // second tick
            '\b\b\b\b\b\b\b\b        ' // clearing the spinner to put the time
            '\b\b\b\b\b\b\b\b' // clearing the clearing of the spinner
            '    0.0s\n', // replacing it with the time
          );
          done = true;
        });
        expect(done, isTrue);
      }, overrides: <Type, Generator>{
        Logger: () => StdoutLogger(),
        OutputPreferences: () => OutputPreferences(showColor: true),
        Platform: () => FakePlatform(operatingSystem: testOs)..stdoutSupportsAnsi = true,
        Stdio: () => mockStdio,
      });

229 230
      testUsingContext('AnsiStatus works for $testOs', () {
        final AnsiStatus ansiStatus = _createAnsiStatus();
231
        bool done = false;
232
        FakeAsync().run((FakeAsync time) {
233
          ansiStatus.start();
234
          mockStopwatch.elapsed = const Duration(seconds: 1);
235
          doWhileAsync(time, () => ansiStatus.ticks < 10); // one second
236
          expect(ansiStatus.seemsSlow, isFalse);
237 238
          expect(outputStdout().join('\n'), isNot(contains('This is taking an unexpectedly long time.')));
          expect(outputStdout().join('\n'), isNot(contains('(!)')));
239
          mockStopwatch.elapsed = const Duration(seconds: 3);
240
          doWhileAsync(time, () => ansiStatus.ticks < 30); // three seconds
241
          expect(ansiStatus.seemsSlow, isTrue);
242
          expect(outputStdout().join('\n'), contains('This is taking an unexpectedly long time.'));
243 244 245 246 247 248 249 250 251 252

          // Test that the number of '\b' is correct.
          for (String line in outputStdout()) {
            int currLength = 0;
            for (int i = 0; i < line.length; i += 1) {
              currLength += line[i] == '\b' ? -1 : 1;
              expect(currLength, isNonNegative, reason: 'The following line has overflow backtraces:\n' + jsonEncode(line));
            }
          }

253 254 255 256 257 258 259 260
          ansiStatus.stop();
          expect(outputStdout().join('\n'), contains('(!)'));
          done = true;
        });
        expect(done, isTrue);
      }, overrides: <Type, Generator>{
        Platform: () => FakePlatform(operatingSystem: testOs),
        Stdio: () => mockStdio,
261
        Stopwatch: () => mockStopwatch,
262 263
      });

264
      testUsingContext('AnsiStatus works when canceled for $testOs', () async {
265
        final AnsiStatus ansiStatus = _createAnsiStatus();
266 267 268
        bool done = false;
        FakeAsync().run((FakeAsync time) {
          ansiStatus.start();
269
          mockStopwatch.elapsed = const Duration(seconds: 1);
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
          doWhileAsync(time, () => ansiStatus.ticks < 10);
          List<String> lines = outputStdout();
          expect(lines[0], startsWith(platform.isWindows
              ? 'Hello world                      \b\b\b\b\b\b\b\b       \\\b\b\b\b\b\b\b\b       |\b\b\b\b\b\b\b\b       /\b\b\b\b\b\b\b\b       -\b\b\b\b\b\b\b\b       \\\b\b\b\b\b\b\b\b       |\b\b\b\b\b\b\b\b       /\b\b\b\b\b\b\b\b       -\b\b\b\b\b\b\b\b       \\\b\b\b\b\b\b\b\b       |'
              : 'Hello world                      \b\b\b\b\b\b\b\b       ⣽\b\b\b\b\b\b\b\b       ⣻\b\b\b\b\b\b\b\b       ⢿\b\b\b\b\b\b\b\b       ⡿\b\b\b\b\b\b\b\b       ⣟\b\b\b\b\b\b\b\b       ⣯\b\b\b\b\b\b\b\b       ⣷\b\b\b\b\b\b\b\b       ⣾\b\b\b\b\b\b\b\b       ⣽\b\b\b\b\b\b\b\b       ⣻'));
          expect(lines.length, equals(1));
          expect(lines[0].endsWith('\n'), isFalse);

          // Verify a cancel does _not_ print the time and prints a newline.
          ansiStatus.cancel();
          lines = outputStdout();
          final List<Match> matches = secondDigits.allMatches(lines[0]).toList();
          expect(matches, isEmpty);
          final String x = platform.isWindows ? '|' : '⣻';
          expect(lines[0], endsWith('$x\b\b\b\b\b\b\b\b        \b\b\b\b\b\b\b\b'));
          expect(called, equals(1));
          expect(lines.length, equals(2));
          expect(lines[1], equals(''));

          // Verify that stopping or canceling multiple times throws.
          expect(() { ansiStatus.cancel(); }, throwsA(isInstanceOf<AssertionError>()));
          expect(() { ansiStatus.stop(); }, throwsA(isInstanceOf<AssertionError>()));
          done = true;
        });
        expect(done, isTrue);
295 296
      }, overrides: <Type, Generator>{
        Platform: () => FakePlatform(operatingSystem: testOs),
297
        Stdio: () => mockStdio,
298
        Stopwatch: () => mockStopwatch,
299 300 301
      });

      testUsingContext('AnsiStatus works when stopped for $testOs', () async {
302
        final AnsiStatus ansiStatus = _createAnsiStatus();
303 304 305
        bool done = false;
        FakeAsync().run((FakeAsync time) {
          ansiStatus.start();
306
          mockStopwatch.elapsed = const Duration(seconds: 1);
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
          doWhileAsync(time, () => ansiStatus.ticks < 10);
          List<String> lines = outputStdout();
          expect(lines, hasLength(1));
          expect(lines[0],
            platform.isWindows
              ? 'Hello world                      \b\b\b\b\b\b\b\b       \\\b\b\b\b\b\b\b\b       |\b\b\b\b\b\b\b\b       /\b\b\b\b\b\b\b\b       -\b\b\b\b\b\b\b\b       \\\b\b\b\b\b\b\b\b       |\b\b\b\b\b\b\b\b       /\b\b\b\b\b\b\b\b       -\b\b\b\b\b\b\b\b       \\\b\b\b\b\b\b\b\b       |'
              : 'Hello world                      \b\b\b\b\b\b\b\b       ⣽\b\b\b\b\b\b\b\b       ⣻\b\b\b\b\b\b\b\b       ⢿\b\b\b\b\b\b\b\b       ⡿\b\b\b\b\b\b\b\b       ⣟\b\b\b\b\b\b\b\b       ⣯\b\b\b\b\b\b\b\b       ⣷\b\b\b\b\b\b\b\b       ⣾\b\b\b\b\b\b\b\b       ⣽\b\b\b\b\b\b\b\b       ⣻',
          );

          // Verify a stop prints the time.
          ansiStatus.stop();
          lines = outputStdout();
          expect(lines, hasLength(2));
          expect(lines[0], matches(
            platform.isWindows
              ? r'Hello world               {8}[\b]{8} {7}\\[\b]{8} {7}|[\b]{8} {7}/[\b]{8} {7}-[\b]{8} {7}\\[\b]{8} {7}|[\b]{8} {7}/[\b]{8} {7}-[\b]{8} {7}\\[\b]{8} {7}|[\b]{8} {7} [\b]{8}[\d., ]{6}[\d]ms$'
              : r'Hello world               {8}[\b]{8} {7}⣽[\b]{8} {7}⣻[\b]{8} {7}⢿[\b]{8} {7}⡿[\b]{8} {7}⣟[\b]{8} {7}⣯[\b]{8} {7}⣷[\b]{8} {7}⣾[\b]{8} {7}⣽[\b]{8} {7}⣻[\b]{8} {7} [\b]{8}[\d., ]{5}[\d]ms$'
          ));
          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.
          expect(() { ansiStatus.stop(); }, throwsA(isInstanceOf<AssertionError>()));
          expect(() { ansiStatus.cancel(); }, throwsA(isInstanceOf<AssertionError>()));
          done = true;
        });
        expect(done, isTrue);
341 342
      }, overrides: <Type, Generator>{
        Platform: () => FakePlatform(operatingSystem: testOs),
343
        Stdio: () => mockStdio,
344
        Stopwatch: () => mockStopwatch,
345 346
      });
    }
347 348 349 350 351 352 353 354 355 356 357 358
  });
  group('Output format', () {
    MockStdio mockStdio;
    SummaryStatus summaryStatus;
    int called;
    final RegExp secondDigits = RegExp(r'[^\b]\b\b\b\b\b[0-9]+[.][0-9]+(?:s|ms)');

    setUp(() {
      mockStdio = MockStdio();
      called = 0;
      summaryStatus = SummaryStatus(
        message: 'Hello world',
359
        timeout: timeoutConfiguration.slowOperation,
360 361 362 363 364 365 366 367 368
        padding: 20,
        onFinish: () => called++,
      );
    });

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

    testUsingContext('Error logs are wrapped', () async {
369
      final Logger logger = context.get<Logger>();
370
      logger.printError('0123456789' * 15);
371 372 373 374 375 376 377 378 379 380 381
      final List<String> lines = outputStderr();
      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));
    }, overrides: <Type, Generator>{
      Logger: () => StdoutLogger(),
      OutputPreferences: () => OutputPreferences(wrapText: true, wrapColumn: 40, showColor: false),
      Stdio: () => mockStdio,
382
      Platform: _kNoAnsiPlatform,
383 384 385
    });

    testUsingContext('Error logs are wrapped and can be indented.', () async {
386
      final Logger logger = context.get<Logger>();
387
      logger.printError('0123456789' * 15, indent: 5);
388 389 390 391 392 393 394 395 396 397 398 399 400 401
      final List<String> lines = outputStderr();
      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);
    }, overrides: <Type, Generator>{
      Logger: () => StdoutLogger(),
      OutputPreferences: () => OutputPreferences(wrapText: true, wrapColumn: 40, showColor: false),
      Stdio: () => mockStdio,
402
      Platform: _kNoAnsiPlatform,
403 404 405
    });

    testUsingContext('Error logs are wrapped and can have hanging indent.', () async {
406
      final Logger logger = context.get<Logger>();
407
      logger.printError('0123456789' * 15, hangingIndent: 5);
408 409 410 411 412 413 414 415 416 417 418 419 420 421
      final List<String> lines = outputStderr();
      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);
    }, overrides: <Type, Generator>{
      Logger: () => StdoutLogger(),
      OutputPreferences: () => OutputPreferences(wrapText: true, wrapColumn: 40, showColor: false),
      Stdio: () => mockStdio,
422
      Platform: _kNoAnsiPlatform,
423 424 425
    });

    testUsingContext('Error logs are wrapped, indented, and can have hanging indent.', () async {
426
      final Logger logger = context.get<Logger>();
427
      logger.printError('0123456789' * 15, indent: 4, hangingIndent: 5);
428 429 430 431 432 433 434 435 436 437 438 439 440 441
      final List<String> lines = outputStderr();
      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);
    }, overrides: <Type, Generator>{
      Logger: () => StdoutLogger(),
      OutputPreferences: () => OutputPreferences(wrapText: true, wrapColumn: 40, showColor: false),
      Stdio: () => mockStdio,
442
      Platform: _kNoAnsiPlatform,
443 444 445
    });

    testUsingContext('Stdout logs are wrapped', () async {
446
      final Logger logger = context.get<Logger>();
447
      logger.printStatus('0123456789' * 15);
448 449 450 451 452 453 454 455 456 457 458
      final List<String> lines = outputStdout();
      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));
    }, overrides: <Type, Generator>{
      Logger: () => StdoutLogger(),
      OutputPreferences: () => OutputPreferences(wrapText: true, wrapColumn: 40, showColor: false),
      Stdio: () => mockStdio,
459
      Platform: _kNoAnsiPlatform,
460 461 462
    });

    testUsingContext('Stdout logs are wrapped and can be indented.', () async {
463
      final Logger logger = context.get<Logger>();
464
      logger.printStatus('0123456789' * 15, indent: 5);
465 466 467 468 469 470 471 472 473 474 475 476 477 478
      final List<String> lines = outputStdout();
      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);
    }, overrides: <Type, Generator>{
      Logger: () => StdoutLogger(),
      OutputPreferences: () => OutputPreferences(wrapText: true, wrapColumn: 40, showColor: false),
      Stdio: () => mockStdio,
479
      Platform: _kNoAnsiPlatform,
480 481 482
    });

    testUsingContext('Stdout logs are wrapped and can have hanging indent.', () async {
483
      final Logger logger = context.get<Logger>();
484
      logger.printStatus('0123456789' * 15, hangingIndent: 5);
485 486 487 488 489 490 491 492 493 494 495 496 497 498
      final List<String> lines = outputStdout();
      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);
    }, overrides: <Type, Generator>{
      Logger: () => StdoutLogger(),
      OutputPreferences: () => OutputPreferences(wrapText: true, wrapColumn: 40, showColor: false),
      Stdio: () => mockStdio,
499
      Platform: _kNoAnsiPlatform,
500 501 502
    });

    testUsingContext('Stdout logs are wrapped, indented, and can have hanging indent.', () async {
503
      final Logger logger = context.get<Logger>();
504
      logger.printStatus('0123456789' * 15, indent: 4, hangingIndent: 5);
505 506 507 508 509 510 511 512 513 514 515 516 517 518
      final List<String> lines = outputStdout();
      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);
    }, overrides: <Type, Generator>{
      Logger: () => StdoutLogger(),
      OutputPreferences: () => OutputPreferences(wrapText: true, wrapColumn: 40, showColor: false),
      Stdio: () => mockStdio,
519
      Platform: _kNoAnsiPlatform,
520
    });
521

522
    testUsingContext('Error logs are red', () async {
523
      final Logger logger = context.get<Logger>();
524
      logger.printError('Pants on fire!');
525 526 527
      final List<String> lines = outputStderr();
      expect(outputStdout().length, equals(1));
      expect(outputStdout().first, isEmpty);
528
      expect(lines[0], equals('${AnsiTerminal.red}Pants on fire!${AnsiTerminal.resetColor}'));
529
    }, overrides: <Type, Generator>{
530 531 532
      Logger: () => StdoutLogger(),
      OutputPreferences: () => OutputPreferences(showColor: true),
      Platform: () => FakePlatform()..stdoutSupportsAnsi = true,
533 534 535 536
      Stdio: () => mockStdio,
    });

    testUsingContext('Stdout logs are not colored', () async {
537
      final Logger logger = context.get<Logger>();
538
      logger.printStatus('All good.');
539 540 541 542 543
      final List<String> lines = outputStdout();
      expect(outputStderr().length, equals(1));
      expect(outputStderr().first, isEmpty);
      expect(lines[0], equals('All good.'));
    }, overrides: <Type, Generator>{
544 545
      Logger: () => StdoutLogger(),
      OutputPreferences: () => OutputPreferences(showColor: true),
546 547 548 549
      Stdio: () => mockStdio,
    });

    testUsingContext('Stdout printStatus handle null inputs on colored terminal', () async {
550
      final Logger logger = context.get<Logger>();
551 552 553 554 555 556 557
      logger.printStatus(
        null,
        emphasis: null,
        color: null,
        newline: null,
        indent: null,
      );
558 559 560 561 562
      final List<String> lines = outputStdout();
      expect(outputStderr().length, equals(1));
      expect(outputStderr().first, isEmpty);
      expect(lines[0], equals(''));
    }, overrides: <Type, Generator>{
563 564
      Logger: () => StdoutLogger(),
      OutputPreferences: () => OutputPreferences(showColor: true),
565 566 567
      Stdio: () => mockStdio,
    });

568
    testUsingContext('Stdout printStatus handle null inputs on non-color terminal', () async {
569
      final Logger logger = context.get<Logger>();
570 571 572 573 574 575 576
      logger.printStatus(
        null,
        emphasis: null,
        color: null,
        newline: null,
        indent: null,
      );
577 578 579 580 581
      final List<String> lines = outputStdout();
      expect(outputStderr().length, equals(1));
      expect(outputStderr().first, isEmpty);
      expect(lines[0], equals(''));
    }, overrides: <Type, Generator>{
582 583
      Logger: () => StdoutLogger(),
      OutputPreferences: () => OutputPreferences(showColor: false),
584
      Stdio: () => mockStdio,
585
      Platform: _kNoAnsiPlatform,
586 587
    });

588 589 590
    testUsingContext('Stdout startProgress on non-color terminal', () async {
      bool done = false;
      FakeAsync().run((FakeAsync time) {
591
        final Logger logger = context.get<Logger>();
592 593 594
        final Status status = logger.startProgress(
          'Hello',
          progressId: null,
595
          timeout: timeoutConfiguration.slowOperation,
596 597 598 599 600 601 602 603 604 605 606 607 608
          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(platform.isWindows ? r'^Hello {15} {5}$' :
                                                                       r'^Hello {15} {5}$'));
        status.stop();
        expect(outputStdout().join('\n'), matches(platform.isWindows ? r'^Hello {15} {5}[\d, ]{4}[\d]\.[\d]s[\n]$' :
                                                                       r'^Hello {15} {5}[\d, ]{4}[\d]\.[\d]s[\n]$'));
        done = true;
      });
      expect(done, isTrue);
609
    }, overrides: <Type, Generator>{
610 611
      Logger: () => StdoutLogger(),
      OutputPreferences: () => OutputPreferences(showColor: false),
612
      Stdio: () => mockStdio,
613
      Platform: _kNoAnsiPlatform,
614 615
    });

616
    testUsingContext('SummaryStatus works when canceled', () async {
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635
      summaryStatus.start();
      List<String> lines = outputStdout();
      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();
      lines = outputStdout();
      final List<Match> matches = secondDigits.allMatches(lines[0]).toList();
      expect(matches, isEmpty);
      expect(lines[0], endsWith(' '));
      expect(called, equals(1));
      expect(lines.length, equals(2));
      expect(lines[1], equals(''));

      // Verify that stopping or canceling multiple times throws.
      expect(() { summaryStatus.cancel(); }, throwsA(isInstanceOf<AssertionError>()));
      expect(() { summaryStatus.stop(); }, throwsA(isInstanceOf<AssertionError>()));
636
    }, overrides: <Type, Generator>{Stdio: () => mockStdio, Platform: _kNoAnsiPlatform});
637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658

    testUsingContext('SummaryStatus works when stopped', () async {
      summaryStatus.start();
      List<String> lines = outputStdout();
      expect(lines[0], startsWith('Hello world              '));
      expect(lines.length, equals(1));

      // Verify a stop prints the time.
      summaryStatus.stop();
      lines = outputStdout();
      final List<Match> matches = secondDigits.allMatches(lines[0]).toList();
      expect(matches, isNotNull);
      expect(matches, hasLength(1));
      final Match match = matches.first;
      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.
      expect(() { summaryStatus.stop(); }, throwsA(isInstanceOf<AssertionError>()));
      expect(() { summaryStatus.cancel(); }, throwsA(isInstanceOf<AssertionError>()));
659
    }, overrides: <Type, Generator>{Stdio: () => mockStdio, Platform: _kNoAnsiPlatform});
660

661
    testUsingContext('sequential startProgress calls with StdoutLogger', () async {
662
      final Logger logger = context.get<Logger>();
663 664
      logger.startProgress('AAA', timeout: timeoutConfiguration.fastOperation)..stop();
      logger.startProgress('BBB', timeout: timeoutConfiguration.fastOperation)..stop();
665 666 667 668 669 670 671
      final List<String> output = outputStdout();
      expect(output.length, equals(3));
      // 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')));
672
    }, overrides: <Type, Generator>{
673 674
      Logger: () => StdoutLogger(),
      OutputPreferences: () => OutputPreferences(showColor: false),
675
      Stdio: () => mockStdio,
676
      Platform: _kNoAnsiPlatform,
677
    });
678

679
    testUsingContext('sequential startProgress calls with VerboseLogger and StdoutLogger', () async {
680
      final Logger logger = context.get<Logger>();
681 682
      logger.startProgress('AAA', timeout: timeoutConfiguration.fastOperation)..stop();
      logger.startProgress('BBB', timeout: timeoutConfiguration.fastOperation)..stop();
683
      expect(outputStdout(), <Matcher>[
684 685 686 687
        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.*\)$'),
688 689 690
        matches(r'^$'),
      ]);
    }, overrides: <Type, Generator>{
691
      Logger: () => VerboseLogger(StdoutLogger()),
692
      Stdio: () => mockStdio,
693
      Platform: _kNoAnsiPlatform,
694
    });
695

696
    testUsingContext('sequential startProgress calls with BufferLogger', () async {
697
      final BufferLogger logger = context.get<Logger>();
698 699
      logger.startProgress('AAA', timeout: timeoutConfiguration.fastOperation)..stop();
      logger.startProgress('BBB', timeout: timeoutConfiguration.fastOperation)..stop();
700 701
      expect(logger.statusText, 'AAA\nBBB\n');
    }, overrides: <Type, Generator>{
702
      Logger: () => BufferLogger(),
703
      Platform: _kNoAnsiPlatform,
704
    });
705
  });
706
}
707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742

class FakeStopwatch implements Stopwatch {
  @override
  bool get isRunning => _isRunning;
  bool _isRunning = false;

  @override
  void start() => _isRunning = true;

  @override
  void stop() => _isRunning = false;

  @override
  Duration elapsed = Duration.zero;

  @override
  int get elapsedMicroseconds => elapsed.inMicroseconds;

  @override
  int get elapsedMilliseconds => elapsed.inMilliseconds;

  @override
  int get elapsedTicks => elapsed.inMilliseconds;

  @override
  int get frequency => 1000;

  @override
  void reset() {
    _isRunning = false;
    elapsed = Duration.zero;
  }

  @override
  String toString() => '$runtimeType $elapsed $isRunning';
}