python playwright pytest 源码
时间: 2023-08-27 09:06:30 浏览: 168
首先,需要安装 Python 的 Playwright 和 pytest 扩展:
```
pip install playwright pytest-playwright
```
然后,在 Python 中编写测试用例,使用 Playwright 进行浏览器自动化测试。以下是一个简单的示例:
```python
import pytest
from playwright.sync_api import Playwright, Browser, BrowserContext, Page
@pytest.fixture(scope="session")
def playwright() -> Playwright:
with Playwright() as playwright:
yield playwright
@pytest.fixture(scope="session")
def browser(playwright: Playwright) -> Browser:
with playwright.chromium.launch(headless=True) as browser:
yield browser
@pytest.fixture(scope="session")
def context(browser: Browser) -> BrowserContext:
with browser.new_context() as context:
yield context
@pytest.fixture(scope="session")
def page(context: BrowserContext) -> Page:
with context.new_page() as page:
yield page
def test_playwright(page: Page):
page.goto("https://www.google.com")
assert page.title() == "Google"
search_input = page.locator("[name='q']")
search_input.fill("Playwright")
search_input.press("Enter")
assert page.title() == "Playwright - Google Search"
```
在这个示例中,我们定义了四个 fixture,分别是:
- `playwright`:Playwright 实例,用于创建浏览器实例。
- `browser`:浏览器实例,用于创建上下文。
- `context`:浏览器上下文,用于创建页面实例。
- `page`:页面实例,用于进行测试操作。
在测试函数 `test_playwright` 中,我们使用 Playwright 进行浏览器自动化测试。我们首先打开谷歌搜索页面,然后在搜索框中输入 `Playwright` 并按下回车键。最后,我们断言页面标题是否为 `Playwright - Google Search`。
最后,我们可以使用 pytest 运行测试:
```
pytest test_playwright.py
```
阅读全文