Trouble authenticating parallel workers with different permission roles

160 views Asked by At

I am having trouble authenticating each parallel worker once per test with different accounts that have different permissions roles. I have been following playwrights authentication docs. What i have so far is that tests will authenticate each worker separately, but only with hardcoded admin role. However for the life of me i cannot figure out how to parameterize my tests to run as both admin and viewer. This is my extended test so far and ideally i would pass an user to my authenticate function.

EDIT: I have figured that i can pass metadata to my tests via playwright config

metadata: {user: ORG_VIEWER},

and read it inside my extended test that authenticates individual workers like so

const user = test.info().project?.metadata?.user;

Hoping that there is still a better way of doing this.


fixture.ts

export type TestOptions = { user: TestUser }

export const test = baseTest.extend<TestOptions, { workerStorageState: string }>({
  storageState: ({ workerStorageState }, use) => use(workerStorageState),
  user: ORG_ADMIN, // Set default user and maybe override from test??

  // Authenticate once per worker with a worker-scoped fixture.
  workerStorageState: [
    async ({ 
      browser,
      // user --- Property 'user' does not exist on type '{ workerStorageState: string; } & PlaywrightWorkerArgs & PlaywrightWorkerOptions'.
    }, use) => {
      // potential solution is to pass metadata from playwright config const user = test.info().project?.metadata?.user; 
      const id = test.info().parallelIndex;
      const fileName = path.resolve(test.info().project.outputDir, `.auth/${id}.json`);

      if (fs.existsSync(fileName)) {
        await use(fileName);
        return;
      }

// Authenticate with given user
await authenticate(
        browser,
        fileName,
      // user); -- Doesnt work since user is not available in this scope
    },
    { scope: 'worker' },
  ],
});

This is my thought process behind playwright config.

playwright.config.ts

export default defineConfig<TestOptions>({
  ...nxE2EPreset(__filename, { testDir: './e2e' }),
  ...playwrightCommonConfig,
  expect: {
    timeout: 15000,
  },
  projects: [
    {
      name: 'shell',
      testMatch: '*viewer.spec.ts',
      use: {
        user: ORG_VIEWER,
      },
    },
    {
      name: 'shell',
      testMatch: '*admin.spec.ts',
      use: {
        user: ORG_ADMIN,
      },
    },
  ],
});

Any help is appreciated.

0

There are 0 answers