身份验证
简介
Playwright 在称为浏览器上下文的隔离环境中执行测试。这种隔离模型提高了可重现性并防止了级联测试失败。测试可以加载现有的已验证状态。这消除了在每次测试中进行身份验证的需要,并加快了测试执行速度。
核心概念
无论您选择哪种身份验证策略,您都可能会将已验证的浏览器状态存储在文件系统上。
我们建议创建 playwright/.auth
目录并将其添加到您的 .gitignore
中。您的身份验证例程将生成已验证的浏览器状态并将其保存到此 playwright/.auth
目录中的文件中。之后,测试将重用此状态并以已验证的身份开始。
浏览器状态文件可能包含敏感的 cookie 和标头,这些信息可能用于冒充您或您的测试账户。我们强烈不建议将其提交到私有或公共仓库。
- Bash
- PowerShell
- 批处理
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
每次测试前登录
Playwright API 可以自动化与登录表单的交互。
以下示例登录 GitHub。一旦执行这些步骤,浏览器上下文将进行身份验证。
- 同步
- 异步
page = context.new_page()
page.goto('https://github.com/login')
# Interact with login form
page.get_by_label("Username or email address").fill("username")
page.get_by_label("Password").fill("password")
page.get_by_role("button", name="Sign in").click()
# Continue with the test
page = await context.new_page()
await page.goto('https://github.com/login')
# Interact with login form
await page.get_by_label("Username or email address").fill("username")
await page.get_by_label("Password").fill("password")
await page.get_by_role("button", name="Sign in").click()
# Continue with the test
每次测试都重新登录会降低测试执行速度。为了缓解这种情况,请改为重用现有的身份验证状态。
重用已登录状态
Playwright 提供了一种在测试中重用已登录状态的方法。这样,您只需登录一次,然后即可跳过所有测试的登录步骤。
Web 应用程序使用基于 cookie 或基于令牌的身份验证,其中已验证状态存储为cookie,在本地存储或IndexedDB中。Playwright 提供了browser_context.storage_state() 方法,可用于从已验证的上下文检索存储状态,然后使用预填充的状态创建新的上下文。
Cookie、本地存储和 IndexedDB 状态可以在不同的浏览器中共享。它们取决于您的应用程序的身份验证模型,可能需要 cookie、本地存储或 IndexedDB 的某种组合。
以下代码片段从已验证的上下文中检索状态并使用该状态创建新的上下文。
- 同步
- 异步
# Save storage state into the file.
storage = context.storage_state(path="state.json")
# Create a new context with the saved storage state.
context = browser.new_context(storage_state="state.json")
# Save storage state into the file.
storage = await context.storage_state(path="state.json")
# Create a new context with the saved storage state.
context = await browser.new_context(storage_state="state.json")
高级场景
会话存储
重用已验证状态涵盖了基于cookie、本地存储和IndexedDB的身份验证。很少有将会话存储用于存储与已登录状态相关的信息的情况。会话存储特定于特定域,并且在页面加载之间不会持久化。Playwright 不提供持久化会话存储的 API,但可以使用以下代码片段来保存/加载会话存储。
- 同步
- 异步
import os
# Get session storage and store as env variable
session_storage = page.evaluate("() => JSON.stringify(sessionStorage)")
os.environ["SESSION_STORAGE"] = session_storage
# Set session storage in a new context
session_storage = os.environ["SESSION_STORAGE"]
context.add_init_script("""(storage => {
if (window.location.hostname === 'example.com') {
const entries = JSON.parse(storage)
for (const [key, value] of Object.entries(entries)) {
window.sessionStorage.setItem(key, value)
}
}
})('""" + session_storage + "')")
import os
# Get session storage and store as env variable
session_storage = await page.evaluate("() => JSON.stringify(sessionStorage)")
os.environ["SESSION_STORAGE"] = session_storage
# Set session storage in a new context
session_storage = os.environ["SESSION_STORAGE"]
await context.add_init_script("""(storage => {
if (window.location.hostname === 'example.com') {
const entries = JSON.parse(storage)
for (const [key, value] of Object.entries(entries)) {
window.sessionStorage.setItem(key, value)
}
}
})('""" + session_storage + "')")