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

import 'dart:async';
6
import 'dart:io' as io;
7

8
import 'package:fake_async/fake_async.dart';
9
import 'package:file/memory.dart';
10
import 'package:file_testing/file_testing.dart';
11
import 'package:flutter_tools/src/base/file_system.dart';
12
import 'package:flutter_tools/src/base/logger.dart';
13
import 'package:flutter_tools/src/base/os.dart';
14
import 'package:flutter_tools/src/base/platform.dart';
15
import 'package:flutter_tools/src/web/chrome.dart';
16 17
import 'package:test/fake.dart';
import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart';
18

19 20
import '../src/common.dart';
import '../src/fake_process_manager.dart';
21
import '../src/fakes.dart' hide FakeProcess;
22

23
const List<String> kChromeArgs = <String>[
24 25 26 27 28 29 30 31 32 33
  '--disable-background-timer-throttling',
  '--disable-extensions',
  '--disable-popup-blocking',
  '--bwsi',
  '--no-first-run',
  '--no-default-browser-check',
  '--disable-default-apps',
  '--disable-translate',
];

34 35 36 37 38 39
const List<String> kCodeCache = <String>[
  'Cache',
  'Code Cache',
  'GPUCache',
];

40
const String kDevtoolsStderr = '\n\nDevTools listening\n\n';
41 42

void main() {
43 44 45 46 47 48
  late FileExceptionHandler exceptionHandler;
  late ChromiumLauncher chromeLauncher;
  late FileSystem fileSystem;
  late Platform platform;
  late FakeProcessManager processManager;
  late OperatingSystemUtils operatingSystemUtils;
49
  late BufferLogger testLogger;
50 51

  setUp(() {
52
    exceptionHandler = FileExceptionHandler();
53
    operatingSystemUtils = FakeOperatingSystemUtils();
54 55
    platform = FakePlatform(operatingSystem: 'macos', environment: <String, String>{
      kChromeEnvironment: 'example_chrome',
56
    });
57
    fileSystem = MemoryFileSystem.test(opHandle: exceptionHandler.opHandle);
58
    processManager = FakeProcessManager.empty();
59
    chromeLauncher = ChromiumLauncher(
60 61 62 63
      fileSystem: fileSystem,
      platform: platform,
      processManager: processManager,
      operatingSystemUtils: operatingSystemUtils,
64
      browserFinder: findChromeExecutable,
65
      logger: testLogger = BufferLogger.test(),
66
    );
67 68
  });

69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
  Future<Chromium> testLaunchChrome(String userDataDir, FakeProcessManager processManager, ChromiumLauncher chromeLauncher) {
    if (testLogger.isVerbose) {
      processManager.addCommand(const FakeCommand(
        command: <String>[
          'example_chrome',
          '--version',
        ],
        stdout: 'Chromium 115',
      ));
    }

    processManager.addCommand(FakeCommand(
      command: <String>[
        'example_chrome',
        '--user-data-dir=$userDataDir',
        '--remote-debugging-port=12345',
        ...kChromeArgs,
        'example_url',
      ],
      stderr: kDevtoolsStderr,
    ));

    return chromeLauncher.launch(
      'example_url',
      skipCheck: true,
    );
  }

97
  testWithoutContext('can launch chrome and connect to the devtools', () async {
98
    await expectReturnsNormallyLater(
99
      testLaunchChrome(
100 101 102
        '/.tmp_rand0/flutter_tools_chrome_device.rand0',
        processManager,
        chromeLauncher,
103
      )
104
    );
105 106
  });

107 108 109 110 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
  testWithoutContext('can launch chrome in verbose mode', () async {
    chromeLauncher = ChromiumLauncher(
      fileSystem: fileSystem,
      platform: platform,
      processManager: processManager,
      operatingSystemUtils: operatingSystemUtils,
      browserFinder: findChromeExecutable,
      logger: testLogger = BufferLogger.test(verbose: true),
    );

    await expectReturnsNormallyLater(
      testLaunchChrome(
        '/.tmp_rand0/flutter_tools_chrome_device.rand0',
        processManager,
        chromeLauncher,
      )
    );

    expect(
      testLogger.traceText.trim(),
      'Launching Chromium (url = example_url, headless = false, skipCheck = true, debugPort = null)\n'
      'Will use Chromium executable at example_chrome\n'
      'Using Chromium 115\n'
      '[CHROME]: \n'
      '[CHROME]: \n'
      '[CHROME]: DevTools listening',
    );
  });

136
  testWithoutContext('cannot have two concurrent instances of chrome', () async {
137
    await testLaunchChrome(
138 139 140 141
      '/.tmp_rand0/flutter_tools_chrome_device.rand0',
      processManager,
      chromeLauncher,
    );
142

143
    await expectToolExitLater(
144
      testLaunchChrome(
145 146 147 148
        '/.tmp_rand0/flutter_tools_chrome_device.rand1',
        processManager,
        chromeLauncher,
      ),
149
      contains('Only one instance of chrome can be started'),
150
    );
151 152
  });

153
  testWithoutContext('can launch new chrome after stopping a previous chrome', () async {
154
    final Chromium chrome = await testLaunchChrome(
155 156 157 158
      '/.tmp_rand0/flutter_tools_chrome_device.rand0',
      processManager,
      chromeLauncher,
    );
159
    await chrome.close();
160

161
    await expectReturnsNormallyLater(
162
      testLaunchChrome(
163 164 165
        '/.tmp_rand0/flutter_tools_chrome_device.rand1',
        processManager,
        chromeLauncher,
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 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
  testWithoutContext('exits normally using SIGTERM', () async {
    final BufferLogger logger = BufferLogger.test();
    final FakeAsync fakeAsync = FakeAsync();

    fakeAsync.run((_) {
      () async {
        final FakeChromeConnection chromeConnection = FakeChromeConnection(maxRetries: 4);
        final ChromiumLauncher chromiumLauncher = ChromiumLauncher(
          fileSystem: fileSystem,
          platform: platform,
          processManager: processManager,
          operatingSystemUtils: operatingSystemUtils,
          browserFinder: findChromeExecutable,
          logger: logger,
        );

        final FakeProcess process = FakeProcess(
          duration: const Duration(seconds: 3),
        );

        final Chromium chrome = Chromium(0, chromeConnection, chromiumLauncher: chromiumLauncher, process: process, logger: logger);

        final Future<void> closeFuture = chrome.close();
        fakeAsync.elapse(const Duration(seconds: 4));
        await closeFuture;

        expect(process.signals, <io.ProcessSignal>[io.ProcessSignal.sigterm]);
      }();
    });

    fakeAsync.flushTimers();
    expect(logger.warningText, isEmpty);
  });

  testWithoutContext('falls back to SIGKILL if SIGTERM did not work', () async {
    final BufferLogger logger = BufferLogger.test();
    final FakeAsync fakeAsync = FakeAsync();

    fakeAsync.run((_) {
      () async {
        final FakeChromeConnection chromeConnection = FakeChromeConnection(maxRetries: 4);
        final ChromiumLauncher chromiumLauncher = ChromiumLauncher(
          fileSystem: fileSystem,
          platform: platform,
          processManager: processManager,
          operatingSystemUtils: operatingSystemUtils,
          browserFinder: findChromeExecutable,
          logger: logger,
        );

        final FakeProcess process = FakeProcess(
          duration: const Duration(seconds: 6),
        );

        final Chromium chrome = Chromium(0, chromeConnection, chromiumLauncher: chromiumLauncher, process: process, logger: logger);

        final Future<void> closeFuture = chrome.close();
        fakeAsync.elapse(const Duration(seconds: 7));
        await closeFuture;

        expect(process.signals, <io.ProcessSignal>[io.ProcessSignal.sigterm, io.ProcessSignal.sigkill]);
      }();
    });

    fakeAsync.flushTimers();
    expect(
      logger.warningText,
      'Failed to exit Chromium (pid: 1234) using SIGTERM. Will try sending SIGKILL instead.\n',
    );
  });

  testWithoutContext('falls back to a warning if SIGKILL did not work', () async {
    final BufferLogger logger = BufferLogger.test();
    final FakeAsync fakeAsync = FakeAsync();

    fakeAsync.run((_) {
      () async {
        final FakeChromeConnection chromeConnection = FakeChromeConnection(maxRetries: 4);
        final ChromiumLauncher chromiumLauncher = ChromiumLauncher(
          fileSystem: fileSystem,
          platform: platform,
          processManager: processManager,
          operatingSystemUtils: operatingSystemUtils,
          browserFinder: findChromeExecutable,
          logger: logger,
        );

        final FakeProcess process = FakeProcess(
          duration: const Duration(seconds: 20),
        );

        final Chromium chrome = Chromium(0, chromeConnection, chromiumLauncher: chromiumLauncher, process: process, logger: logger);

        final Future<void> closeFuture = chrome.close();
        fakeAsync.elapse(const Duration(seconds: 30));
        await closeFuture;
        expect(process.signals, <io.ProcessSignal>[io.ProcessSignal.sigterm, io.ProcessSignal.sigkill]);
      }();
    });

    fakeAsync.flushTimers();
    expect(
      logger.warningText,
      'Failed to exit Chromium (pid: 1234) using SIGTERM. Will try sending SIGKILL instead.\n'
      'Failed to exit Chromium (pid: 1234) using SIGKILL. Giving up. Will continue, assuming '
      'Chromium has exited successfully, but it is possible that this left a dangling Chromium '
      'process running on the system.\n',
    );
  });

280 281 282
  testWithoutContext('does not crash if saving profile information fails due to a file system exception.', () async {
    final BufferLogger logger = BufferLogger.test();
    chromeLauncher = ChromiumLauncher(
283
      fileSystem: fileSystem,
284 285 286 287 288 289 290 291 292 293
      platform: platform,
      processManager: processManager,
      operatingSystemUtils: operatingSystemUtils,
      browserFinder: findChromeExecutable,
      logger: logger,
    );
    processManager.addCommand(const FakeCommand(
      command: <String>[
        'example_chrome',
        '--user-data-dir=/.tmp_rand0/flutter_tools_chrome_device.rand0',
294
        '--remote-debugging-port=12345',
295 296 297 298 299 300 301 302 303 304 305 306
        ...kChromeArgs,
        'example_url',
      ],
      stderr: kDevtoolsStderr,
    ));

    final Chromium chrome = await chromeLauncher.launch(
      'example_url',
      skipCheck: true,
      cacheDir: fileSystem.currentDirectory,
    );

307
    // Create cache dir that the Chrome launcher will attempt to persist, and a file
308 309 310
    // that will thrown an exception when it is read.
    const String directoryPrefix = '/.tmp_rand0/flutter_tools_chrome_device.rand0/Default';
    fileSystem.directory('$directoryPrefix/Local Storage')
311
      .createSync(recursive: true);
312 313 314 315 316 317 318
    final File file = fileSystem.file('$directoryPrefix/Local Storage/foo')
      ..createSync(recursive: true);
    exceptionHandler.addError(
      file,
      FileSystemOp.read,
      const FileSystemException(),
    );
319 320 321 322 323

    await chrome.close(); // does not exit with error.
    expect(logger.errorText, contains('Failed to save Chrome preferences'));
  });

324 325
  testWithoutContext('does not crash if restoring profile information fails due to a file system exception.', () async {
    final BufferLogger logger = BufferLogger.test();
326 327 328 329 330 331 332
    final File file = fileSystem.file('/Default/foo')
      ..createSync(recursive: true);
    exceptionHandler.addError(
      file,
      FileSystemOp.read,
      const FileSystemException(),
    );
333
    chromeLauncher = ChromiumLauncher(
334
      fileSystem: fileSystem,
335 336 337 338 339 340
      platform: platform,
      processManager: processManager,
      operatingSystemUtils: operatingSystemUtils,
      browserFinder: findChromeExecutable,
      logger: logger,
    );
341

342 343 344 345
    processManager.addCommand(const FakeCommand(
      command: <String>[
        'example_chrome',
        '--user-data-dir=/.tmp_rand0/flutter_tools_chrome_device.rand0',
346
        '--remote-debugging-port=12345',
347 348 349 350 351 352 353 354 355 356
        ...kChromeArgs,
        'example_url',
      ],
      stderr: kDevtoolsStderr,
    ));

    fileSystem.currentDirectory.childDirectory('Default').createSync();
    final Chromium chrome = await chromeLauncher.launch(
      'example_url',
      skipCheck: true,
357
      cacheDir: fileSystem.currentDirectory,
358 359
    );

360
    // Create cache dir that the Chrome launcher will attempt to persist.
361 362 363 364 365 366 367
    fileSystem.directory('/.tmp_rand0/flutter_tools_chrome_device.rand0/Default/Local Storage')
      .createSync(recursive: true);

    await chrome.close(); // does not exit with error.
    expect(logger.errorText, contains('Failed to restore Chrome preferences'));
  });

368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
  testWithoutContext('can launch Chrome on x86_64 macOS', () async {
    final OperatingSystemUtils macOSUtils = FakeOperatingSystemUtils(hostPlatform: HostPlatform.darwin_x64);
    final ChromiumLauncher chromiumLauncher = ChromiumLauncher(
      fileSystem: fileSystem,
      platform: platform,
      processManager: processManager,
      operatingSystemUtils: macOSUtils,
      browserFinder: findChromeExecutable,
      logger: BufferLogger.test(),
    );

    processManager.addCommands(<FakeCommand>[
      const FakeCommand(
        command: <String>[
          'example_chrome',
          '--user-data-dir=/.tmp_rand0/flutter_tools_chrome_device.rand0',
          '--remote-debugging-port=12345',
          ...kChromeArgs,
          'example_url',
        ],
        stderr: kDevtoolsStderr,
389
      ),
390 391
    ]);

392 393
    await expectReturnsNormallyLater(
      chromiumLauncher.launch(
394 395
        'example_url',
        skipCheck: true,
396
      )
397 398 399 400
    );
  });

  testWithoutContext('can launch x86_64 Chrome on ARM macOS', () async {
401
    final OperatingSystemUtils macOSUtils = FakeOperatingSystemUtils(hostPlatform: HostPlatform.darwin_arm64);
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
    final ChromiumLauncher chromiumLauncher = ChromiumLauncher(
      fileSystem: fileSystem,
      platform: platform,
      processManager: processManager,
      operatingSystemUtils: macOSUtils,
      browserFinder: findChromeExecutable,
      logger: BufferLogger.test(),
    );

    processManager.addCommands(<FakeCommand>[
      const FakeCommand(
        command: <String>[
          'file',
          'example_chrome',
        ],
        stdout: 'Mach-O 64-bit executable x86_64',
      ),
      const FakeCommand(
        command: <String>[
          'example_chrome',
          '--user-data-dir=/.tmp_rand0/flutter_tools_chrome_device.rand0',
          '--remote-debugging-port=12345',
          ...kChromeArgs,
          'example_url',
        ],
        stderr: kDevtoolsStderr,
428
      ),
429 430
    ]);

431 432
    await expectReturnsNormallyLater(
      chromiumLauncher.launch(
433 434
        'example_url',
        skipCheck: true,
435
      )
436 437 438 439
    );
  });

  testWithoutContext('can launch ARM Chrome natively on ARM macOS when installed', () async {
440
    final OperatingSystemUtils macOSUtils = FakeOperatingSystemUtils(hostPlatform: HostPlatform.darwin_arm64);
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
    final ChromiumLauncher chromiumLauncher = ChromiumLauncher(
      fileSystem: fileSystem,
      platform: platform,
      processManager: processManager,
      operatingSystemUtils: macOSUtils,
      browserFinder: findChromeExecutable,
      logger: BufferLogger.test(),
    );

    processManager.addCommands(<FakeCommand>[
      const FakeCommand(
        command: <String>[
          'file',
          'example_chrome',
        ],
        stdout: 'Mach-O 64-bit executable arm64',
      ),
      const FakeCommand(
        command: <String>[
          '/usr/bin/arch',
          '-arm64',
          'example_chrome',
          '--user-data-dir=/.tmp_rand0/flutter_tools_chrome_device.rand0',
          '--remote-debugging-port=12345',
          ...kChromeArgs,
          'example_url',
        ],
        stderr: kDevtoolsStderr,
      ),
    ]);

472 473
    await expectReturnsNormallyLater(
      chromiumLauncher.launch(
474 475
        'example_url',
        skipCheck: true,
476
      )
477 478 479
    );
  });

480
  testWithoutContext('can launch chrome with a custom debug port', () async {
481 482 483
    processManager.addCommand(const FakeCommand(
      command: <String>[
        'example_chrome',
484
        '--user-data-dir=/.tmp_rand0/flutter_tools_chrome_device.rand0',
485
        '--remote-debugging-port=10000',
486
        ...kChromeArgs,
487 488 489 490 491
        'example_url',
      ],
      stderr: kDevtoolsStderr,
    ));

492 493
    await expectReturnsNormallyLater(
      chromeLauncher.launch(
494 495 496
        'example_url',
        skipCheck: true,
        debugPort: 10000,
497
      )
498 499
    );
  });
500

501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
  testWithoutContext('can launch chrome with arbitrary flags', () async {
    processManager.addCommand(const FakeCommand(
      command: <String>[
        'example_chrome',
        '--user-data-dir=/.tmp_rand0/flutter_tools_chrome_device.rand0',
        '--remote-debugging-port=12345',
        ...kChromeArgs,
        '--autoplay-policy=no-user-gesture-required',
        '--incognito',
        '--auto-select-desktop-capture-source="Entire screen"',
        'example_url',
      ],
      stderr: kDevtoolsStderr,
    ));

    await expectReturnsNormallyLater(chromeLauncher.launch(
      'example_url',
      skipCheck: true,
      webBrowserFlags: <String>[
        '--autoplay-policy=no-user-gesture-required',
        '--incognito',
        '--auto-select-desktop-capture-source="Entire screen"',
      ],
    ));
  });

527
  testWithoutContext('can launch chrome headless', () async {
528 529 530
    processManager.addCommand(const FakeCommand(
      command: <String>[
        'example_chrome',
531
        '--user-data-dir=/.tmp_rand0/flutter_tools_chrome_device.rand0',
532
        '--remote-debugging-port=12345',
533
        ...kChromeArgs,
534 535 536 537 538 539 540 541 542
        '--headless',
        '--disable-gpu',
        '--no-sandbox',
        '--window-size=2400,1800',
        'example_url',
      ],
      stderr: kDevtoolsStderr,
    ));

543 544
    await expectReturnsNormallyLater(
      chromeLauncher.launch(
545 546 547
        'example_url',
        skipCheck: true,
        headless: true,
548
      )
549 550
    );
  });
551

552
  testWithoutContext('can seed chrome temp directory with existing session data, excluding Cache folder', () async {
553 554
    final Completer<void> exitCompleter = Completer<void>.sync();
    final Directory dataDir = fileSystem.directory('chrome-stuff');
555 556 557 558 559
    final File preferencesFile = dataDir
      .childDirectory('Default')
      .childFile('preferences');
    preferencesFile
      ..createSync(recursive: true)
560
      ..writeAsStringSync('"exit_type":"Crashed"');
561

562
    final Directory defaultContentDirectory = dataDir
563 564 565 566 567 568
      .childDirectory('Default')
      .childDirectory('Foo');
    defaultContentDirectory.createSync(recursive: true);
    // Create Cache directories that should be skipped
    for (final String cache in kCodeCache) {
      dataDir
569
        .childDirectory('Default')
570 571 572
        .childDirectory(cache)
        .createSync(recursive: true);
    }
573

574 575 576 577
    processManager.addCommand(FakeCommand(
      command: const <String>[
        'example_chrome',
        '--user-data-dir=/.tmp_rand0/flutter_tools_chrome_device.rand0',
578
        '--remote-debugging-port=12345',
579 580 581 582 583 584
        ...kChromeArgs,
        'example_url',
      ],
      completer: exitCompleter,
      stderr: kDevtoolsStderr,
    ));
585 586 587 588

    await chromeLauncher.launch(
      'example_url',
      skipCheck: true,
589
      cacheDir: dataDir,
590 591
    );

592 593
    // validate any Default content is copied
    final Directory defaultContentDir = fileSystem
594
        .directory('.tmp_rand0/flutter_tools_chrome_device.rand0')
595
        .childDirectory('Default')
596
        .childDirectory('Foo');
597

598 599
    expect(defaultContentDir, exists);

600 601 602 603 604 605
    exitCompleter.complete();
    await Future<void>.delayed(const Duration(milliseconds: 1));

    // writes non-crash back to dart_tool
    expect(preferencesFile.readAsStringSync(), '"exit_type":"Normal"');

606 607 608 609 610 611 612
    // Validate cache dirs are not copied.
    for (final String cache in kCodeCache) {
      expect(fileSystem
        .directory('.tmp_rand0/flutter_tools_chrome_device.rand0')
        .childDirectory('Default')
        .childDirectory(cache), isNot(exists));
    }
613 614 615

    // validate defaultContentDir is deleted after exit, data is in cache
    expect(defaultContentDir, isNot(exists));
616
  });
617 618 619 620 621

  testWithoutContext('can retry launch when glibc bug happens', () async {
    const List<String> args = <String>[
      'example_chrome',
      '--user-data-dir=/.tmp_rand0/flutter_tools_chrome_device.rand0',
622
      '--remote-debugging-port=12345',
623 624 625 626 627 628 629 630 631 632 633 634 635 636
      ...kChromeArgs,
      '--headless',
      '--disable-gpu',
      '--no-sandbox',
      '--window-size=2400,1800',
      'example_url',
    ];

    // Pretend to hit glibc bug 3 times.
    for (int i = 0; i < 3; i++) {
      processManager.addCommand(const FakeCommand(
        command: args,
        stderr: 'Inconsistency detected by ld.so: ../elf/dl-tls.c: 493: '
                '_dl_allocate_tls_init: Assertion `listp->slotinfo[cnt].gen '
637
                "<= GL(dl_tls_generation)' failed!",
638 639 640 641 642 643 644 645 646
      ));
    }

    // Succeed on the 4th try.
    processManager.addCommand(const FakeCommand(
      command: args,
      stderr: kDevtoolsStderr,
    ));

647 648
    await expectReturnsNormallyLater(
      chromeLauncher.launch(
649 650 651
        'example_url',
        skipCheck: true,
        headless: true,
652
      )
653 654 655
    );
  });

656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677
  testWithoutContext('can retry launch when chrome fails to start', () async {
    const List<String> args = <String>[
      'example_chrome',
      '--user-data-dir=/.tmp_rand0/flutter_tools_chrome_device.rand0',
      '--remote-debugging-port=12345',
      ...kChromeArgs,
      '--headless',
      '--disable-gpu',
      '--no-sandbox',
      '--window-size=2400,1800',
      'example_url',
    ];

    // Pretend to random error 3 times.
    for (int i = 0; i < 3; i++) {
      processManager.addCommand(const FakeCommand(
        command: args,
        stderr: 'BLAH BLAH',
      ));
    }

    // Succeed on the 4th try.
678
    processManager.addCommand(const FakeCommand(
679 680
      command: args,
      stderr: kDevtoolsStderr,
681 682
    ));

683 684
    await expectReturnsNormallyLater(
      chromeLauncher.launch(
685 686 687
        'example_url',
        skipCheck: true,
        headless: true,
688
      )
689 690 691 692
    );
  });

  testWithoutContext('gives up retrying when an error happens more than 3 times', () async {
693 694 695 696 697 698 699 700 701
    final BufferLogger logger = BufferLogger.test();
    final ChromiumLauncher chromiumLauncher = ChromiumLauncher(
      fileSystem: fileSystem,
      platform: platform,
      processManager: processManager,
      operatingSystemUtils: operatingSystemUtils,
      browserFinder: findChromeExecutable,
      logger: logger,
    );
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
    for (int i = 0; i < 4; i++) {
      processManager.addCommand(const FakeCommand(
        command: <String>[
          'example_chrome',
          '--user-data-dir=/.tmp_rand0/flutter_tools_chrome_device.rand0',
          '--remote-debugging-port=12345',
          ...kChromeArgs,
          '--headless',
          '--disable-gpu',
          '--no-sandbox',
          '--window-size=2400,1800',
          'example_url',
        ],
        stderr: 'nothing in the std error indicating glibc error',
      ));
    }

719
    await expectToolExitLater(
720
      chromiumLauncher.launch(
721 722 723 724
        'example_url',
        skipCheck: true,
        headless: true,
      ),
725
      contains('Failed to launch browser.'),
726
    );
727
    expect(logger.errorText, contains('nothing in the std error indicating glibc error'));
728
  });
729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757

  testWithoutContext('Logs an error and exits if connection check fails.', () async {
    final BufferLogger logger = BufferLogger.test();
    final ChromiumLauncher chromiumLauncher = ChromiumLauncher(
      fileSystem: fileSystem,
      platform: platform,
      processManager: processManager,
      operatingSystemUtils: operatingSystemUtils,
      browserFinder: findChromeExecutable,
      logger: logger,
    );
    processManager.addCommand(const FakeCommand(
      command: <String>[
        'example_chrome',
        '--user-data-dir=/.tmp_rand0/flutter_tools_chrome_device.rand0',
        '--remote-debugging-port=12345',
        ...kChromeArgs,
        'example_url',
      ],
      stderr: kDevtoolsStderr,
    ));

    await expectToolExitLater(
      chromiumLauncher.launch(
        'example_url',
      ),
      contains('Unable to connect to Chrome debug port:'),
    );
    expect(logger.errorText, contains('SocketException'));
758
  });
759 760 761 762 763 764 765 766 767 768 769 770

  test('can recover if getTabs throws a connection exception', () async {
    final BufferLogger logger = BufferLogger.test();
    final FakeChromeConnection chromeConnection = FakeChromeConnection(maxRetries: 4);
    final ChromiumLauncher chromiumLauncher = ChromiumLauncher(
      fileSystem: fileSystem,
      platform: platform,
      processManager: processManager,
      operatingSystemUtils: operatingSystemUtils,
      browserFinder: findChromeExecutable,
      logger: logger,
    );
771 772
    final FakeProcess process = FakeProcess();
    final Chromium chrome = Chromium(0, chromeConnection, chromiumLauncher: chromiumLauncher, process: process, logger: logger);
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
    expect(await chromiumLauncher.connect(chrome, false), equals(chrome));
    expect(logger.errorText, isEmpty);
  });

  test('exits if getTabs throws a connection exception consistently', () async {
    final BufferLogger logger = BufferLogger.test();
    final FakeChromeConnection chromeConnection = FakeChromeConnection();
    final ChromiumLauncher chromiumLauncher = ChromiumLauncher(
      fileSystem: fileSystem,
      platform: platform,
      processManager: processManager,
      operatingSystemUtils: operatingSystemUtils,
      browserFinder: findChromeExecutable,
      logger: logger,
    );
788 789
    final FakeProcess process = FakeProcess();
    final Chromium chrome = Chromium(0, chromeConnection, chromiumLauncher: chromiumLauncher, process: process, logger: logger);
790 791 792 793 794 795 796 797 798 799 800 801 802
    await expectToolExitLater(
      chromiumLauncher.connect(chrome, false),
        allOf(
          contains('Unable to connect to Chrome debug port'),
          contains('incorrect format'),
        ));
    expect(logger.errorText,
      allOf(
          contains('incorrect format'),
          contains('OK'),
          contains('<html> ...'),
        ));
  });
803 804
}

805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836
/// Fake chrome connection that fails to get tabs a few times.
class FakeChromeConnection extends Fake implements ChromeConnection {

  /// Create a connection that throws a connection exception on first
  /// [maxRetries] calls to [getTabs].
  /// If [maxRetries] is `null`, [getTabs] calls never succeed.
  FakeChromeConnection({this.maxRetries}): _retries = 0;

  final List<ChromeTab> tabs = <ChromeTab>[];
  final int? maxRetries;
  int _retries;

  @override
  Future<ChromeTab?> getTab(bool Function(ChromeTab tab) accept, {Duration? retryFor}) async {
    return tabs.firstWhere(accept);
  }

  @override
  Future<List<ChromeTab>> getTabs({Duration? retryFor}) async {
    _retries ++;
    if (maxRetries == null || _retries < maxRetries!) {
      throw ConnectionException(
        formatException: const FormatException('incorrect format'),
        responseStatus: 'OK,',
        responseBody: '<html> ...');
    }
    return tabs;
  }

  @override
  void close() {}
}