驗證
簡介
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
每次測試前登入
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.page.get_by_role("button", name="Sign in").click()
# Continue with the test
為每個測試重新登入可能會減慢測試執行速度。為了緩解這個問題,請改為重複使用現有的身份驗證狀態。
重複使用已登入狀態
Playwright 提供了一種在測試中重複使用已登入狀態的方法。這樣您只需登入一次,然後就可以跳過所有測試的登入步驟。
Web 應用程式使用基於 Cookie 或基於令牌的身份驗證,其中已驗證的狀態儲存在 Cookie 或 本地儲存中。Playwright 提供了 browser_context.storage_state() 方法,可用於從已驗證的上下文中檢索儲存狀態,然後使用預先填充的狀態建立新的上下文。
Cookie 和本地儲存狀態可以在不同的瀏覽器之間使用。它們取決於您的應用程式的身份驗證模型:某些應用程式可能需要 Cookie 和本地儲存。
以下程式碼片段從已驗證的上下文中檢索狀態,並使用該狀態建立新的上下文。
- 同步
- 非同步
# 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")
進階情境
Session Storage
重複使用已驗證的狀態涵蓋了基於 Cookie 和 本地儲存的身份驗證。極少數情況下,Session Storage 用於儲存與已登入狀態相關的資訊。Session Storage 專用於特定網域,並且不會跨頁面載入而持久保存。Playwright 沒有提供 API 來持久保存 Session Storage,但可以使用以下程式碼片段來儲存/載入 Session Storage。
- 同步
- 非同步
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 + "')")