Isolation
Tests written with Playwright execute in isolated clean-slate environments called browser contexts. This isolation model improves reproducibility and prevents cascading test failures.
BrowserContexts are equivalent to incognito-like profiles, they are fast and cheap to create and completely isolated, even when running in a single browser. Playwright creates a context for each test, and provides a default Page in that context.
When using Playwright as a Test Runner, this happens out of the box for each test. Otherwise, you can create browser contexts manually.
- Sync
- Async
browser = playwright.chromium.launch()
context = browser.new_context()
page = context.new_page()
browser = await playwright.chromium.launch()
context = await browser.new_context()
page = await context.new_page()
Browser contexts can also be used to emulate multi-page scenarios involving mobile devices, permissions, locale and color scheme. Check out our Emulation guide for more details.
Multiple contexts in a single test
Playwright can create multiple browser contexts within a single scenario. This is useful when you want to test for multi-user functionality, like a chat.
- Sync
- Async
from playwright.sync_api import sync_playwright
def run(playwright):
# create a chromium browser instance
chromium = playwright.chromium
browser = chromium.launch()
# create two isolated browser contexts
user_context = browser.new_context()
admin_context = browser.new_context()
# create pages and interact with contexts independently
with sync_playwright() as playwright:
run(playwright)
import asyncio
from playwright.async_api import async_playwright
async def run(playwright):
# create a chromium browser instance
chromium = playwright.chromium
browser = await chromium.launch()
# create two isolated browser contexts
user_context = await browser.new_context()
admin_context = await browser.new_context()
# create pages and interact with contexts independently
async def main():
async with async_playwright() as playwright:
await run(playwright)
asyncio.run(main())