playwright icon indicating copy to clipboard operation
playwright copied to clipboard

[Question] How to create a new Browser instance per test in @playwright/test

Open archlichking opened this issue 5 years ago • 4 comments

Hi team, this question is about the Browserstack integration with @playwright/test and relates to https://github.com/microsoft/playwright/issues/8379.

According to Playwright's doc, all tests in one worker run in one browser instance, and I observe the same behavior. With code in https://github.com/microsoft/playwright/issues/8379#issuecomment-905741931, all tests in the same test file, which are assigned to the same worker, run in the same browser session in Browserstack. This behavior results in one single long Browserstack test session, and we cannot really mark test status (pass/fail) for a test on Browserstack.

The expected behavior would be, to run one test per Browserstack session. I didn't find a better way to do this by overriding browser fixture, so I override the page fixture like this

  page: async ({ page, browser }, use, testInfo) => {
    const caps = {
      browser: 'chrome',
      os: 'osx',
      os_version: 'catalina',
      name: 'My first playwright test',
      build: 'playwright-build-1',
      'browserstack.username': process.env.BROWSERSTACK_USERNAME,
      'browserstack.accessKey': process.env.BROWSERSTACK_ACCESS_KEY,
      'client.playwrightVersion': '1.13.1',
    };
    const vBrowser = await chromium.connect({
      wsEndpoint:
        `wss://cdp.browserstack.com/playwright?caps=` +
        `${encodeURIComponent(JSON.stringify(caps))}`,
    });
    // new browser context per page per test
    const vPage = await vBrowser.newPage(testInfo.project.use);
    await use(vPage);

    const testResult = {
      action: 'setSessionStatus',
      arguments: {
        status: testInfo.status,
        reason: JSON.stringify(testInfo?.error),
      },
    };
    await vPage.evaluate(() => {}, `browserstack_executor: ${JSON.stringify(testResult)}`);

    await vBrowser.close();
  },

In this way each test runs as a separate Browserstack session and we can mark its status successfully.

However, when I run tests in parallel (like more than 2 workers), frequently this error shows up

browserType.connect: connect ETIMEDOUT 207.254.8.24:443. Most likely ws endpoint is incorrect

When this error shows up, no websocket connection is established for current test.

I'm using @playwright/[email protected]. When use the same version 1.13.1 in Browserstack's example repo, tests are correctly executed and queued from Browserstack side.

I suspect something goes wrong in @playwright/test as there is always one browser instance up and doing nothing in the way how I override the page fixture. Please let me know if there is a better way of creating a new browser instance per test, or any more info we need to reproduce this.

archlichking avatar Aug 26 '21 01:08 archlichking

Not sure if it helps but that's what I'm using to create a fresh browser for each test:

import { test, expect, chromium } from "@playwright/test";
import { join } from "path";
import { tmpdir } from "os";
import fs from "fs";
import rimraf from "rimraf";

const testPersistent = test.extend({
  page: async ({}, use) => {
    const pathToExtension = join(__dirname, "/utils/extensions");
    const dir = await fs.promises.mkdtemp(join(tmpdir(), "user-data-dir-"));
    const context = await chromium.launchPersistentContext(dir, {
      headless: false,
      args: [
        `--disable-extensions-except=${pathToExtension}`,
        `--load-extension=${pathToExtension}`,
      ],
    });
    await use(context.pages()[0]);
    await context.close();
    rimraf.sync(dir);
  },
});

testPersistent("basic test", async ({ page }) => {
  expect(1).toBe(2);
});

As you can see it's made to start the browser with the extension but I'm pretty sure it's possible to modify it.

cat-ninja avatar Aug 26 '21 09:08 cat-ninja

@archlichking that reminds me of issues I had when using test-runner workers with browserstack and nightwatch.js. I looked back at the history and browserstack has provided a code example around it. It would be worth reaching out to browserstack considering playwright support is still in beta

unlikelyzero avatar Aug 26 '21 14:08 unlikelyzero

@unlikelyzero What makes things interesting here is, the example browserstack provides works well when tests run in parallel. I don't see the same ETIMEDOUT error in their example. All test sessions can be established successfully. Also I've tried to bump playwright version to the same as I'm currently using (1.11.1 in browserstack's example to 1.13.1), and it also works well.

That's why I'm reaching back to playwright team to see if there is a better way of creating a new browser instance (to call chromium.connect() to create a new browserstack session) per test.

archlichking avatar Aug 26 '21 17:08 archlichking

You should probably direct this question to browserstack!

pavelfeldman avatar Sep 07 '21 20:09 pavelfeldman