身份验证
简介
Playwright 在名为 浏览器上下文 的隔离环境中执行测试。这种隔离模式提高了可重复性,并防止了测试失败的级联效应。测试可以加载现有的已认证状态。这消除了在每次测试中进行身份验证的需要,并加快了测试执行速度。
核心概念
无论您选择哪种身份验证策略,您都可能将已认证的浏览器状态存储在文件系统中。
我们建议您创建 playwright/.auth
目录并将其添加到您的 .gitignore
中。您的身份验证例程将生成已认证的浏览器状态,并将其保存到此 playwright/.auth
目录中的文件。之后,测试将重用此状态并以已认证的方式启动。
- Bash
- PowerShell
- Batch
mkdir -p playwright/.auth
echo $'\nplaywright/.auth' >> .gitignore
New-Item -ItemType Directory -Force -Path playwright\.auth
Add-Content -path .gitignore "`r`nplaywright/.auth"
md playwright\.auth
echo. >> .gitignore
echo "playwright/.auth" >> .gitignore
基本:所有测试中的共享帐户
这是针对没有服务器端状态的测试的推荐方法。在设置项目中进行一次身份验证,保存身份验证状态,然后将其重复使用以启动已认证的每个测试。
何时使用
- 当您可以想象所有测试使用同一个帐户同时运行,且不会相互影响时。
何时不使用
- 您的测试修改了服务器端状态。例如,一个测试检查设置页面的渲染,而另一个测试正在更改设置,并且您并行运行测试。在这种情况下,测试必须使用不同的帐户。
- 您的身份验证是特定于浏览器的。
详细信息
创建 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
。
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
。
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
项目。
中等:每个并行工作线程一个帐户
这是针对修改服务器端状态的测试的推荐方法。在 Playwright 中,工作线程并行运行。在这种方法中,每个并行工作线程都进行一次身份验证。工作线程运行的所有测试都会重复使用相同的身份验证状态。我们将需要多个测试帐户,每个并行工作线程一个帐户。
何时使用
- 您的测试修改了共享的服务器端状态。例如,一个测试检查设置页面的渲染,而另一个测试正在更改设置。
何时不使用
- 您的测试没有修改任何共享的服务器端状态。在这种情况下,所有测试都可以使用一个共享帐户。
详细信息
我们将在每个 工作线程 上进行一次身份验证,每个工作线程使用一个唯一的帐户。
创建 playwright/fixtures.ts
文件,它将 覆盖 storageState
夹具 以对每个工作线程进行一次身份验证。使用 testInfo.parallelIndex 来区分工作线程。
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' }],
});
现在,每个测试文件都应从我们的夹具文件中导入 test
,而不是从 @playwright/test
中导入。配置中不需要进行任何更改。
// Important: import our fixtures.
import { test, expect } from '../playwright/fixtures';
test('test', async ({ page }) => {
// page is authenticated
});
高级场景
使用 API 请求进行身份验证
何时使用
- 您的 Web 应用程序支持通过 API 进行身份验证,这比与应用程序 UI 交互更容易/更快。
详细信息
我们将使用 APIRequestContext 发送 API 请求,然后像往常一样保存已认证的状态。
在 设置项目 中
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 });
});
或者,在 工作线程夹具 中
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' }],
});
多个已签名的角色
何时使用
- 您在端到端测试中有多个角色,但您可以在所有测试中重复使用帐户。
详细信息
我们将在设置项目中进行多次身份验证。
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
,而不是在配置中设置它。
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 模式中进行身份验证 的内容。
测试多个角色
何时使用
- 您需要测试多个已认证的角色如何在同一个测试中相互交互。
详细信息
在同一个测试中使用具有不同存储状态的多个 BrowserContext 和 Page。
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 夹具测试多个角色
何时使用
- 您需要测试多个已认证的角色如何在同一个测试中相互交互。
详细信息
您可以引入夹具,这些夹具将提供以每个角色身份验证的页面。
以下是一个示例,它 创建了两个 页面对象模型 的夹具 - 管理员 POM 和用户 POM。 它假设 adminStorageState.json
和 userStorageState.json
文件已在全局设置中创建。
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();
},
});
// 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 和 本地存储 基于身份验证。很少情况下,会话存储 用于存储与已签名的状态相关的信息。会话存储特定于某个域,不会在页面加载之间保留。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);
避免在某些测试中进行身份验证
您可以在测试文件中重置存储状态以避免为整个项目设置的身份验证。
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 }) => {
// ...
});