メインコンテンツへスキップ

認証

はじめに

Playwright は、ブラウザコンテキストと呼ばれる隔離された環境でテストを実行します。この分離モデルは、再現性を向上させ、テストの連鎖的な失敗を防ぎます。テストは既存の認証済み状態をロードできます。これにより、すべてのテストで認証を行う必要がなくなり、テストの実行が高速化されます。

コアコンセプト

選択する認証戦略に関係なく、認証されたブラウザの状態をファイルシステムに保存する可能性があります。

playwright/.auth ディレクトリを作成し、それを .gitignore に追加することをお勧めします。認証ルーチンは、認証されたブラウザの状態を生成し、この playwright/.auth ディレクトリ内のファイルに保存します。後で、テストはこの状態を再利用し、すでに認証された状態で開始します。

mkdir -p playwright/.auth
echo $'\nplaywright/.auth' >> .gitignore

基本:すべてのテストで共有アカウントを使用

これは、サーバーサイドの状態がないテストに推奨されるアプローチです。セットアッププロジェクトで一度認証し、認証状態を保存し、それを再利用して、すでに認証されている各テストをブートストラップします。

使用する場合

  • すべてのテストが同じアカウントで同時に実行されても、互いに影響を与えない場合。

使用しない場合

  • テストがサーバーサイドの状態を変更する場合。たとえば、あるテストが設定ページのレンダリングをチェックし、別のテストが設定を変更し、並行してテストを実行する場合。この場合、テストは異なるアカウントを使用する必要があります。
  • 認証がブラウザ固有の場合。

詳細

他のすべてのテスト用に認証されたブラウザの状態を準備する tests/auth.setup.ts を作成します。

tests/auth.setup.ts
import { test as setup, expect } from '@playwright/test';
import path from 'path';

const authFile = path.join(__dirname, '../playwright/.auth/user.json');

setup('authenticate', async ({ page }) => {
// Perform authentication steps. Replace these actions with your own.
await page.goto('https://github.com/login');
await page.getByLabel('Username or email address').fill('username');
await page.getByLabel('Password').fill('password');
await page.getByRole('button', { name: 'Sign in' }).click();
// Wait until the page receives the cookies.
//
// Sometimes login flow sets cookies in the process of several redirects.
// Wait for the final URL to ensure that the cookies are actually set.
await page.waitForURL('https://github.com/');
// Alternatively, you can wait until the page reaches a state where all cookies are set.
await expect(page.getByRole('button', { name: 'View profile and more' })).toBeVisible();

// End of authentication steps.

await page.context().storageState({ path: authFile });
});

設定ファイルに新しい setup プロジェクトを作成し、すべてのテストプロジェクトの依存関係として宣言します。このプロジェクトは常に実行され、すべてのテストの前に認証を行います。すべてのテストプロジェクトは、認証された状態を storageState として使用する必要があります。

playwright.config.ts
import { defineConfig, devices } from '@playwright/test';

export default defineConfig({
projects: [
// Setup project
{ name: 'setup', testMatch: /.*\.setup\.ts/ },

{
name: 'chromium',
use: {
...devices['Desktop Chrome'],
// Use prepared auth state.
storageState: 'playwright/.auth/user.json',
},
dependencies: ['setup'],
},

{
name: 'firefox',
use: {
...devices['Desktop Firefox'],
// Use prepared auth state.
storageState: 'playwright/.auth/user.json',
},
dependencies: ['setup'],
},
],
});

設定ファイルで storageState を指定したため、テストはすでに認証された状態で開始されます。

tests/example.spec.ts
import { test } from '@playwright/test';

test('test', async ({ page }) => {
// page is authenticated
});

保存された状態が期限切れになったら削除する必要があることに注意してください。テスト実行間で状態を保持する必要がない場合は、testProject.outputDir の下にブラウザの状態を書き込みます。これは、すべてのテスト実行前に自動的にクリーンアップされます。

UI モードでの認証

UI モードは、テスト速度を向上させるために、デフォルトでは setup プロジェクトを実行しません。既存の認証が期限切れになるたびに、auth.setup.ts を手動で実行して認証することをお勧めします。

最初に、フィルターで setup プロジェクトを有効にし、次に auth.setup.ts ファイルの横にある三角形ボタンをクリックし、再度フィルターで setup プロジェクトを無効にします。

中程度:並列ワーカーごとに 1 つのアカウント

これは、サーバーサイドの状態を変更するテストに推奨されるアプローチです。Playwright では、ワーカープロセスは並行して実行されます。このアプローチでは、各並列ワーカーは一度認証されます。ワーカーによって実行されるすべてのテストは、同じ認証状態を再利用します。各並列ワーカーに 1 つずつ、複数のテストアカウントが必要になります。

使用する場合

  • テストが共有サーバーサイドの状態を変更する場合。たとえば、あるテストが設定ページのレンダリングをチェックし、別のテストが設定を変更する場合。

使用しない場合

  • テストが共有サーバーサイドの状態を変更しない場合。この場合、すべてのテストは単一の共有アカウントを使用できます。

詳細

ワーカープロセスごとに一度、それぞれ一意のアカウントで認証します。

storageState フィクスチャをオーバーライドしてワーカーごとに一度認証する playwright/fixtures.ts ファイルを作成します。ワーカーを区別するには、testInfo.parallelIndex を使用します。

playwright/fixtures.ts
import { test as baseTest, expect } from '@playwright/test';
import fs from 'fs';
import path from 'path';

export * from '@playwright/test';
export const test = baseTest.extend<{}, { workerStorageState: string }>({
// Use the same storage state for all tests in this worker.
storageState: ({ workerStorageState }, use) => use(workerStorageState),

// Authenticate once per worker with a worker-scoped fixture.
workerStorageState: [async ({ browser }, use) => {
// Use parallelIndex as a unique identifier for each worker.
const id = test.info().parallelIndex;
const fileName = path.resolve(test.info().project.outputDir, `.auth/${id}.json`);

if (fs.existsSync(fileName)) {
// Reuse existing authentication state if any.
await use(fileName);
return;
}

// Important: make sure we authenticate in a clean environment by unsetting storage state.
const page = await browser.newPage({ storageState: undefined });

// Acquire a unique account, for example create a new one.
// Alternatively, you can have a list of precreated accounts for testing.
// Make sure that accounts are unique, so that multiple team members
// can run tests at the same time without interference.
const account = await acquireAccount(id);

// Perform authentication steps. Replace these actions with your own.
await page.goto('https://github.com/login');
await page.getByLabel('Username or email address').fill(account.username);
await page.getByLabel('Password').fill(account.password);
await page.getByRole('button', { name: 'Sign in' }).click();
// Wait until the page receives the cookies.
//
// Sometimes login flow sets cookies in the process of several redirects.
// Wait for the final URL to ensure that the cookies are actually set.
await page.waitForURL('https://github.com/');
// Alternatively, you can wait until the page reaches a state where all cookies are set.
await expect(page.getByRole('button', { name: 'View profile and more' })).toBeVisible();

// End of authentication steps.

await page.context().storageState({ path: fileName });
await page.close();
await use(fileName);
}, { scope: 'worker' }],
});

これで、各テストファイルは @playwright/test の代わりにフィクスチャファイルから test をインポートする必要があります。設定ファイルに変更は必要ありません。

tests/example.spec.ts
// Important: import our fixtures.
import { test, expect } from '../playwright/fixtures';

test('test', async ({ page }) => {
// page is authenticated
});

高度なシナリオ

API リクエストで認証する

使用する場合

  • ウェブアプリケーションは、アプリの UI を操作するよりも簡単/高速な API 経由での認証をサポートしています。

詳細

APIRequestContext で API リクエストを送信し、通常どおり認証された状態を保存します。

セットアッププロジェクト

tests/auth.setup.ts
import { test as setup } from '@playwright/test';

const authFile = 'playwright/.auth/user.json';

setup('authenticate', async ({ request }) => {
// Send authentication request. Replace with your own.
await request.post('https://github.com/login', {
form: {
'user': 'user',
'password': 'password'
}
});
await request.storageState({ path: authFile });
});

または、ワーカーフィクスチャ

playwright/fixtures.ts
import { test as baseTest, request } from '@playwright/test';
import fs from 'fs';
import path from 'path';

export * from '@playwright/test';
export const test = baseTest.extend<{}, { workerStorageState: string }>({
// Use the same storage state for all tests in this worker.
storageState: ({ workerStorageState }, use) => use(workerStorageState),

// Authenticate once per worker with a worker-scoped fixture.
workerStorageState: [async ({}, use) => {
// Use parallelIndex as a unique identifier for each worker.
const id = test.info().parallelIndex;
const fileName = path.resolve(test.info().project.outputDir, `.auth/${id}.json`);

if (fs.existsSync(fileName)) {
// Reuse existing authentication state if any.
await use(fileName);
return;
}

// Important: make sure we authenticate in a clean environment by unsetting storage state.
const context = await request.newContext({ storageState: undefined });

// Acquire a unique account, for example create a new one.
// Alternatively, you can have a list of precreated accounts for testing.
// Make sure that accounts are unique, so that multiple team members
// can run tests at the same time without interference.
const account = await acquireAccount(id);

// Send authentication request. Replace with your own.
await context.post('https://github.com/login', {
form: {
'user': 'user',
'password': 'password'
}
});

await context.storageState({ path: fileName });
await context.dispose();
await use(fileName);
}, { scope: 'worker' }],
});

複数のサインインロール

使用する場合

  • エンドツーエンドテストで複数のロールがありますが、すべてのアカウントでアカウントを再利用できます。

詳細

セットアッププロジェクトで複数回認証します。

tests/auth.setup.ts
import { test as setup, expect } from '@playwright/test';

const adminFile = 'playwright/.auth/admin.json';

setup('authenticate as admin', async ({ page }) => {
// Perform authentication steps. Replace these actions with your own.
await page.goto('https://github.com/login');
await page.getByLabel('Username or email address').fill('admin');
await page.getByLabel('Password').fill('password');
await page.getByRole('button', { name: 'Sign in' }).click();
// Wait until the page receives the cookies.
//
// Sometimes login flow sets cookies in the process of several redirects.
// Wait for the final URL to ensure that the cookies are actually set.
await page.waitForURL('https://github.com/');
// Alternatively, you can wait until the page reaches a state where all cookies are set.
await expect(page.getByRole('button', { name: 'View profile and more' })).toBeVisible();

// End of authentication steps.

await page.context().storageState({ path: adminFile });
});

const userFile = 'playwright/.auth/user.json';

setup('authenticate as user', async ({ page }) => {
// Perform authentication steps. Replace these actions with your own.
await page.goto('https://github.com/login');
await page.getByLabel('Username or email address').fill('user');
await page.getByLabel('Password').fill('password');
await page.getByRole('button', { name: 'Sign in' }).click();
// Wait until the page receives the cookies.
//
// Sometimes login flow sets cookies in the process of several redirects.
// Wait for the final URL to ensure that the cookies are actually set.
await page.waitForURL('https://github.com/');
// Alternatively, you can wait until the page reaches a state where all cookies are set.
await expect(page.getByRole('button', { name: 'View profile and more' })).toBeVisible();

// End of authentication steps.

await page.context().storageState({ path: userFile });
});

その後、設定ファイルで設定する代わりに、各テストファイルまたはテストグループの storageState を指定します。

tests/example.spec.ts
import { test } from '@playwright/test';

test.use({ storageState: 'playwright/.auth/admin.json' });

test('admin test', async ({ page }) => {
// page is authenticated as admin
});

test.describe(() => {
test.use({ storageState: 'playwright/.auth/user.json' });

test('user test', async ({ page }) => {
// page is authenticated as a user
});
});

UI モードでの認証についても参照してください。

複数のロールを一緒にテストする

使用する場合

  • 単一のテストで、複数の認証されたロールがどのように相互作用するかをテストする必要があります。

詳細

同じテストで、異なるストレージ状態を持つ複数の BrowserContextPage を使用します。

tests/example.spec.ts
import { test } from '@playwright/test';

test('admin and user', async ({ browser }) => {
// adminContext and all pages inside, including adminPage, are signed in as "admin".
const adminContext = await browser.newContext({ storageState: 'playwright/.auth/admin.json' });
const adminPage = await adminContext.newPage();

// userContext and all pages inside, including userPage, are signed in as "user".
const userContext = await browser.newContext({ storageState: 'playwright/.auth/user.json' });
const userPage = await userContext.newPage();

// ... interact with both adminPage and userPage ...

await adminContext.close();
await userContext.close();
});

POM フィクスチャを使用した複数のロールのテスト

使用する場合

  • 単一のテストで、複数の認証されたロールがどのように相互作用するかをテストする必要があります。

詳細

各ロールとして認証されたページを提供するフィクスチャを導入できます。

以下は、2 つのページオブジェクトモデル(admin POM と user POM)のフィクスチャを作成する例です。adminStorageState.json ファイルと userStorageState.json ファイルがグローバルセットアップで作成されていることを前提としています。

playwright/fixtures.ts
import { test as base, type Page, type Locator } from '@playwright/test';

// Page Object Model for the "admin" page.
// Here you can add locators and helper methods specific to the admin page.
class AdminPage {
// Page signed in as "admin".
page: Page;

// Example locator pointing to "Welcome, Admin" greeting.
greeting: Locator;

constructor(page: Page) {
this.page = page;
this.greeting = page.locator('#greeting');
}
}

// Page Object Model for the "user" page.
// Here you can add locators and helper methods specific to the user page.
class UserPage {
// Page signed in as "user".
page: Page;

// Example locator pointing to "Welcome, User" greeting.
greeting: Locator;

constructor(page: Page) {
this.page = page;
this.greeting = page.locator('#greeting');
}
}

// Declare the types of your fixtures.
type MyFixtures = {
adminPage: AdminPage;
userPage: UserPage;
};

export * from '@playwright/test';
export const test = base.extend<MyFixtures>({
adminPage: async ({ browser }, use) => {
const context = await browser.newContext({ storageState: 'playwright/.auth/admin.json' });
const adminPage = new AdminPage(await context.newPage());
await use(adminPage);
await context.close();
},
userPage: async ({ browser }, use) => {
const context = await browser.newContext({ storageState: 'playwright/.auth/user.json' });
const userPage = new UserPage(await context.newPage());
await use(userPage);
await context.close();
},
});

tests/example.spec.ts
// Import test with our new fixtures.
import { test, expect } from '../playwright/fixtures';

// Use adminPage and userPage fixtures in the test.
test('admin and user', async ({ adminPage, userPage }) => {
// ... interact with both adminPage and userPage ...
await expect(adminPage.greeting).toHaveText('Welcome, Admin');
await expect(userPage.greeting).toHaveText('Welcome, User');
});

セッションストレージ

認証された状態の再利用は、cookieローカルストレージ、および IndexedDB ベースの認証をカバーします。まれに、セッションストレージは、サインイン状態に関連付けられた情報を保存するために使用されます。セッションストレージは、特定のドメインに固有であり、ページロード間で永続化されません。Playwright はセッションストレージを永続化するための API を提供していませんが、次のスニペットを使用してセッションストレージを保存/ロードできます。

// Get session storage and store as env variable
const sessionStorage = await page.evaluate(() => JSON.stringify(sessionStorage));
fs.writeFileSync('playwright/.auth/session.json', sessionStorage, 'utf-8');

// Set session storage in a new context
const sessionStorage = JSON.parse(fs.readFileSync('playwright/.auth/session.json', 'utf-8'));
await context.addInitScript(storage => {
if (window.location.hostname === 'example.com') {
for (const [key, value] of Object.entries(storage))
window.sessionStorage.setItem(key, value);
}
}, sessionStorage);

一部のテストで認証を回避する

プロジェクト全体に対して設定された認証を回避するために、テストファイルでストレージ状態をリセットできます。

not-signed-in.spec.ts
import { test } from '@playwright/test';

// Reset storage state for this file to avoid being authenticated
test.use({ storageState: { cookies: [], origins: [] } });

test('not signed in test', async ({ page }) => {
// ...
});