Python Playwright是一个Python库,用于控制Chrome、Firefox和WebKit(Safari)的自动化测试。而pytest-playwright和pytest-base-url是基于Python Playwright的两个插件,前者用于在pytest中集成Playwright测试框架,后者用于设置pytest的默认基础URL。
以下是编写用例的完整攻略:
1. 安装Python Playwright及其插件
pip install -U playwright pytest-playwright pytest-base-url
2. 创建pytest fixtures
编写步骤如下:
- 新建一个名为
conftest.py
的文件,并放置在pytest根目录下; - 编写
browser_type
和browser
的fixture函数,如下:
import pytest
from playwright.sync_api import Playwright, BrowserType, Browser
@pytest.fixture(scope="session")
def browser_type() -> BrowserType:
with Playwright() as playwright:
# 设置可选的浏览器,支持Chromium、Firefox、WebKit(Safari)
browser_type = playwright.chromium if "pytest_playwright_chromium" in pytest.config.option.browser else playwright.firefox
yield browser_type
@pytest.fixture
def browser(browser_type: BrowserType) -> Browser:
# 启动浏览器,完成测试时自动关闭浏览器并清理痕迹
with browser_type.launch(headless=True) as browser:
yield browser
- 添加
browser_type
和browser
到pytest.fixture
装饰器中,比如:
def test_example(browser_type: BrowserType, browser: Browser):
...
3. 编写测试用例
编写示例代码如下:
# test_google_search.py
from playwright.sync_api import Page
def test_google_search(base_url: str, page: Page):
page.goto(base_url)
page.type('input[name="q"]', "pytest")
page.press('input[name="q"]', "Enter")
assert "pytest" in page.title()
在该示例中,我们调用了page.goto
方法访问基础URL,然后在搜索栏输入pytest,最后按Enter键。最后,我们检查当前页面是否包含标题pytest。
4. 设置基础URL
在conftest.py
文件中定义baseurl。比如:
@pytest.fixture
def base_url() -> Optional[str]:
return 'https://www.google.com'
在example测试中,我们可以直接使用该base_url:
def test_example(base_url, page):
page.goto(f'{base_url}/search?q=pytest')
assert "pytest" in page.title()
这样我们就完成了以上两部分示例代码。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:python playwright–pytest-playwright、pytest-base-url插件编写用例 - Python技术站