testBootstrap function

Future<void> testBootstrap([
  1. BrowserConfig? config
])

Configures and initializes the browser testing environment.

Initializes the browser testing environment.

This function sets up the necessary infrastructure for browser testing, including:

  • Potentially installing the default browser binary if needed (most installation happens just-in-time when a specific browser is launched).
  • Starting the WebDriver server for the default browser.
  • Configuring global test hooks (setUpAll, tearDownAll) for driver cleanup.
  • Initializing global configuration access and override mechanisms.

config is an optional BrowserConfig that specifies the default browser settings (browserName, headless, baseUrl, etc.). If not provided, a default BrowserConfig() (usually defaulting to chromium/chrome) will be used.

Example:

void main() async {
  // Set up with default Chrome configuration
  await testBootstrap();

  // Or with custom configuration (e.g., default to Firefox)
  await testBootstrap(
    BrowserConfig(
      browserName: 'firefox',
      headless: false,
      baseUrl: 'https://example.com',
    )
  );

  // Run your browser tests
  browserTest('should display homepage', (browser) async {
    // This will use the default browser ('firefox' in the second example)
    await browser.visit('/');
    // Test implementation
  });

  browserTest('run explicitly in chrome', (browser) async {
    // This overrides the default and launches chrome
  }, browserType: chromium);
}

Call this function once at the beginning of your test suite, typically in the main function of your primary test file.

Implementation

Future<void> testBootstrap([BrowserConfig? config]) async {
  config ??= BrowserConfig();

  // Initialize the global config and registry/driver manager singletons first
  await TestBootstrap.initialize(config);

  final logger = BrowserLogger(
    logDir: config.logDir,
    verbose: config.verbose,
    enabled: config.loggingEnabled,
  );
  BrowserManagement.setLogger(logger);

  setUpAll(() async {
    logger.startTestLog('global_setup'); // More descriptive name
    logger.info('Setting up global browser test environment...');

    try {
      // Get the *initial* configuration used for bootstrap
      // Access the first element pushed onto the stack during initialize
      final initialConfig = TestBootstrap._configStack.first;
      logger.info(
        'Initial default browser from config: ${initialConfig.browserName}',
      );

      // Enhanced browser installation with auto-detection and better error handling
      final hasOverride =
          TestBootstrap.getBinaryOverride(initialConfig.browserName) != null;

      if (initialConfig.autoInstall && !hasOverride) {
        logger.info(
          'Auto-install is enabled, checking browser availability...',
        );

        // Try to auto-detect and install the best available browser
        final success = await _autoDetectAndInstallBrowser(
          initialConfig.browserName,
          force: initialConfig.forceReinstall,
          logger: logger,
        );

        if (!success) {
          logger.info(
            'Failed to auto-install browser, proceeding with manual installation check...',
          );
        }
      } else if (hasOverride) {
        logger.info(
          'Skipping auto-install because a binary override is configured for ${initialConfig.browserName}.',
        );
      } else {
        logger.info('Auto-install disabled via configuration.');
      }

      // 1. Ensure the DEFAULT browser binary (from initial config) is installed.
      //    This primes the environment for the most common case.
      //    Tests requesting other browsers will handle their own install via BrowserType.launch.
      logger.info(
        'Ensuring default browser binary (${initialConfig.browserName}) is installed...',
      );
      // Pass the specific initial browser name and force flag
      await TestBootstrap.ensureBrowserInstalled(
        initialConfig.browserName,
        force: initialConfig.forceReinstall,
      );
      logger.info('Default browser binary check complete.');

      // 2. Ensure the WebDriver server for the DEFAULT browser is running.
      //    This makes launching the default browser faster later.
      logger.info(
        'Ensuring WebDriver server for default browser (${initialConfig.browserName}) is running...',
      );
      // Pass the specific initial browser name
      // await bootstrap_driver.DriverManager.ensureDriver(
      //     initialConfig.browserName);
      // logger.info('WebDriver server for default browser is ready.');

      print('\nGlobal browser testing environment ready.');
    } catch (e, stack) {
      logger.error(
        'Failed to setup global browser testing environment:',
        error: e,
        stackTrace: stack,
      );
      rethrow; // Fail setup if critical parts fail
    }
  });

  tearDownAll(() async {
    print('\nCleaning up browser testing environment...');
    // Access static method directly on the class
    await bootstrap_driver.DriverManager.stopAll();
  });
}