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

認証

はじめに

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リクエストによる認証

使用するケース

  • Webアプリケーションが、アプリの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.jsonuserStorageState.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');
});

セッションストレージ

認証済み状態の再利用は、クッキーローカルストレージ、および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 }) => {
// ...
});