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

import 'dart:async';

7
import 'package:file/memory.dart';
8
import 'package:file_testing/file_testing.dart';
9
import 'package:flutter_tools/src/base/file_system.dart';
10
import 'package:flutter_tools/src/base/logger.dart';
11
import 'package:flutter_tools/src/base/os.dart';
12
import 'package:flutter_tools/src/base/platform.dart';
13
import 'package:flutter_tools/src/web/chrome.dart';
14

15
import '../../src/common.dart';
16 17
import '../../src/fake_process_manager.dart';
import '../../src/fakes.dart';
18

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

30 31 32 33 34 35
const List<String> kCodeCache = <String>[
  'Cache',
  'Code Cache',
  'GPUCache',
];

36
const String kDevtoolsStderr = '\n\nDevTools listening\n\n';
37 38

void main() {
39 40 41 42 43 44
  late FileExceptionHandler exceptionHandler;
  late ChromiumLauncher chromeLauncher;
  late FileSystem fileSystem;
  late Platform platform;
  late FakeProcessManager processManager;
  late OperatingSystemUtils operatingSystemUtils;
45 46

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

64 65
  testWithoutContext('can launch chrome and connect to the devtools', () async {
    expect(
66
      () async => _testLaunchChrome(
67 68 69 70 71 72
        '/.tmp_rand0/flutter_tools_chrome_device.rand0',
        processManager,
        chromeLauncher,
      ),
      returnsNormally,
    );
73 74
  });

75
  testWithoutContext('cannot have two concurrent instances of chrome', () async {
76
    await _testLaunchChrome(
77 78 79 80
      '/.tmp_rand0/flutter_tools_chrome_device.rand0',
      processManager,
      chromeLauncher,
    );
81

82
    expect(
83
      () async => _testLaunchChrome(
84 85 86 87
        '/.tmp_rand0/flutter_tools_chrome_device.rand1',
        processManager,
        chromeLauncher,
      ),
88
      throwsToolExit(message: 'Only one instance of chrome can be started'),
89
    );
90 91
  });

92
  testWithoutContext('can launch new chrome after stopping a previous chrome', () async {
93
    final Chromium chrome = await _testLaunchChrome(
94 95 96 97
      '/.tmp_rand0/flutter_tools_chrome_device.rand0',
      processManager,
      chromeLauncher,
    );
98
    await chrome.close();
99 100

    expect(
101
      () async => _testLaunchChrome(
102 103 104 105 106 107
        '/.tmp_rand0/flutter_tools_chrome_device.rand1',
        processManager,
        chromeLauncher,
      ),
      returnsNormally,
    );
108
  });
109

110 111 112
  testWithoutContext('does not crash if saving profile information fails due to a file system exception.', () async {
    final BufferLogger logger = BufferLogger.test();
    chromeLauncher = ChromiumLauncher(
113
      fileSystem: fileSystem,
114 115 116 117 118 119 120 121 122 123
      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',
124
        '--remote-debugging-port=12345',
125 126 127 128 129 130 131 132 133 134 135 136
        ...kChromeArgs,
        'example_url',
      ],
      stderr: kDevtoolsStderr,
    ));

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

137 138 139 140
    // Create cache dir that the Chrome launcher will atttempt to persist, and a file
    // 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')
141
      .createSync(recursive: true);
142 143 144 145 146 147 148
    final File file = fileSystem.file('$directoryPrefix/Local Storage/foo')
      ..createSync(recursive: true);
    exceptionHandler.addError(
      file,
      FileSystemOp.read,
      const FileSystemException(),
    );
149 150 151 152 153

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

154 155
  testWithoutContext('does not crash if restoring profile information fails due to a file system exception.', () async {
    final BufferLogger logger = BufferLogger.test();
156 157 158 159 160 161 162
    final File file = fileSystem.file('/Default/foo')
      ..createSync(recursive: true);
    exceptionHandler.addError(
      file,
      FileSystemOp.read,
      const FileSystemException(),
    );
163
    chromeLauncher = ChromiumLauncher(
164
      fileSystem: fileSystem,
165 166 167 168 169 170
      platform: platform,
      processManager: processManager,
      operatingSystemUtils: operatingSystemUtils,
      browserFinder: findChromeExecutable,
      logger: logger,
    );
171

172 173 174 175
    processManager.addCommand(const FakeCommand(
      command: <String>[
        'example_chrome',
        '--user-data-dir=/.tmp_rand0/flutter_tools_chrome_device.rand0',
176
        '--remote-debugging-port=12345',
177 178 179 180 181 182 183 184 185 186
        ...kChromeArgs,
        'example_url',
      ],
      stderr: kDevtoolsStderr,
    ));

    fileSystem.currentDirectory.childDirectory('Default').createSync();
    final Chromium chrome = await chromeLauncher.launch(
      'example_url',
      skipCheck: true,
187
      cacheDir: fileSystem.currentDirectory,
188 189 190 191 192 193 194 195 196 197
    );

    // Create cache dir that the Chrome launcher will atttempt to persist.
    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'));
  });

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 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
  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,
      )
    ]);

    expect(
          () async => chromiumLauncher.launch(
        'example_url',
        skipCheck: true,
      ),
      returnsNormally,
    );
  });

  testWithoutContext('can launch x86_64 Chrome on ARM macOS', () async {
    final OperatingSystemUtils macOSUtils = FakeOperatingSystemUtils(hostPlatform: HostPlatform.darwin_arm);
    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,
      )
    ]);

    expect(
          () async => chromiumLauncher.launch(
        'example_url',
        skipCheck: true,
      ),
      returnsNormally,
    );
  });

  testWithoutContext('can launch ARM Chrome natively on ARM macOS when installed', () async {
    final OperatingSystemUtils macOSUtils = FakeOperatingSystemUtils(hostPlatform: HostPlatform.darwin_arm);
    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,
      ),
    ]);

    expect(
      () async => chromiumLauncher.launch(
        'example_url',
        skipCheck: true,
      ),
      returnsNormally,
    );
  });

313
  testWithoutContext('can launch chrome with a custom debug port', () async {
314 315 316
    processManager.addCommand(const FakeCommand(
      command: <String>[
        'example_chrome',
317
        '--user-data-dir=/.tmp_rand0/flutter_tools_chrome_device.rand0',
318
        '--remote-debugging-port=10000',
319
        ...kChromeArgs,
320 321 322 323 324
        'example_url',
      ],
      stderr: kDevtoolsStderr,
    ));

325
    expect(
326
      () async => chromeLauncher.launch(
327 328 329 330 331
        'example_url',
        skipCheck: true,
        debugPort: 10000,
      ),
      returnsNormally,
332 333
    );
  });
334

335
  testWithoutContext('can launch chrome headless', () async {
336 337 338
    processManager.addCommand(const FakeCommand(
      command: <String>[
        'example_chrome',
339
        '--user-data-dir=/.tmp_rand0/flutter_tools_chrome_device.rand0',
340
        '--remote-debugging-port=12345',
341
        ...kChromeArgs,
342 343 344 345 346 347 348 349 350
        '--headless',
        '--disable-gpu',
        '--no-sandbox',
        '--window-size=2400,1800',
        'example_url',
      ],
      stderr: kDevtoolsStderr,
    ));

351
    expect(
352
      () async => chromeLauncher.launch(
353 354 355 356 357
        'example_url',
        skipCheck: true,
        headless: true,
      ),
      returnsNormally,
358 359
    );
  });
360

361
  testWithoutContext('can seed chrome temp directory with existing session data, excluding Cache folder', () async {
362 363
    final Completer<void> exitCompleter = Completer<void>.sync();
    final Directory dataDir = fileSystem.directory('chrome-stuff');
364 365 366 367 368
    final File preferencesFile = dataDir
      .childDirectory('Default')
      .childFile('preferences');
    preferencesFile
      ..createSync(recursive: true)
369
      ..writeAsStringSync('"exit_type":"Crashed"');
370

371
    final Directory defaultContentDirectory = dataDir
372 373 374 375 376 377
      .childDirectory('Default')
      .childDirectory('Foo');
    defaultContentDirectory.createSync(recursive: true);
    // Create Cache directories that should be skipped
    for (final String cache in kCodeCache) {
      dataDir
378
        .childDirectory('Default')
379 380 381
        .childDirectory(cache)
        .createSync(recursive: true);
    }
382

383 384 385 386
    processManager.addCommand(FakeCommand(
      command: const <String>[
        'example_chrome',
        '--user-data-dir=/.tmp_rand0/flutter_tools_chrome_device.rand0',
387
        '--remote-debugging-port=12345',
388 389 390 391 392 393
        ...kChromeArgs,
        'example_url',
      ],
      completer: exitCompleter,
      stderr: kDevtoolsStderr,
    ));
394 395 396 397

    await chromeLauncher.launch(
      'example_url',
      skipCheck: true,
398
      cacheDir: dataDir,
399 400 401
    );

    exitCompleter.complete();
402
    await Future<void>.delayed(const Duration(milliseconds: 1));
403 404 405

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

407 408 409

    // validate any Default content is copied
    final Directory defaultContentDir = fileSystem
410
        .directory('.tmp_rand0/flutter_tools_chrome_device.rand0')
411
        .childDirectory('Default')
412
        .childDirectory('Foo');
413

414 415 416 417 418 419 420 421 422
    expect(defaultContentDir, exists);

    // 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));
    }
423
  });
424 425 426 427 428

  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',
429
      '--remote-debugging-port=12345',
430 431 432 433 434 435 436 437 438 439 440 441 442 443
      ...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 '
444
                "<= GL(dl_tls_generation)' failed!",
445 446 447 448 449 450 451 452 453 454
      ));
    }

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

    expect(
455
      () async => chromeLauncher.launch(
456 457 458 459 460 461 462 463 464 465 466 467 468
        'example_url',
        skipCheck: true,
        headless: true,
      ),
      returnsNormally,
    );
  });

  testWithoutContext('gives up retrying when a non-glibc error happens', () async {
    processManager.addCommand(const FakeCommand(
      command: <String>[
        'example_chrome',
        '--user-data-dir=/.tmp_rand0/flutter_tools_chrome_device.rand0',
469
        '--remote-debugging-port=12345',
470 471 472 473 474 475 476 477 478 479 480
        ...kChromeArgs,
        '--headless',
        '--disable-gpu',
        '--no-sandbox',
        '--window-size=2400,1800',
        'example_url',
      ],
      stderr: 'nothing in the std error indicating glibc error',
    ));

    expect(
481
      () async => chromeLauncher.launch(
482 483 484 485 486 487 488
        'example_url',
        skipCheck: true,
        headless: true,
      ),
      throwsToolExit(message: 'Failed to launch browser.'),
    );
  });
489 490
}

491
Future<Chromium> _testLaunchChrome(String userDataDir, FakeProcessManager processManager, ChromiumLauncher chromeLauncher) {
492 493 494 495
  processManager.addCommand(FakeCommand(
    command: <String>[
      'example_chrome',
      '--user-data-dir=$userDataDir',
496
      '--remote-debugging-port=12345',
497
      ...kChromeArgs,
498 499 500 501 502 503 504 505 506 507
      'example_url',
    ],
    stderr: kDevtoolsStderr,
  ));

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