Playwright是专门为端到端测试的需求而创建的。Playwright支持所有现代渲染引擎,包括Chromium、WebKit和Firefox。可以在Windows、Linux和macOS上本地或CI中进行测试,可以无头(headless)或有界面(headed)进行测试,还支持原生移动设备仿真。
Playwright推荐使用官方的Playwright Pytest
插件编写端到端测试。该插件提供了上下文隔离功能,并且可以立即在多个浏览器配置上运行。或者,您也可以使用该库手动编写适合您所选测试运行器的测试基础架构。Pytest插件使用的是Playwright的同步版本,该库还提供了一个异步版本。
首先安装Playwright并运行示例测试,以查看其运行效果。
安装Pytest插件:
pip install pytest-playwright
安装所需的浏览器:
playwright install
添加示例测试
在当前工作目录或子目录中创建一个文件,文件名为test_my_application.py
,内容如下:
import re
from playwright.sync_api import Page, expect
def test_homepage_has_Playwright_in_title_and_get_started_link_linking_to_the_intro_page(page: Page):
page.goto("https://playwright.dev/")
# 期望标题中包含某个子字符串
expect(page).to_have_title(re.compile("Playwright"))
# 创建一个定位器
get_started = page.get_by_role("link", name="Get started")
# 期望某个属性与特定值"严格相等"
expect(get_started).to_have_attribute("href", "/docs/intro")
# 点击"Get started"链接
get_started.click()
# 期望URL包含"intro"
expect(page).to_have_url(re.compile(".*intro"))
运行示例测试
默认情况下,测试将在Chromium上运行。可以通过命令行选项进行配置。测试以无头模式运行,即在运行测试时不会打开浏览器界面。测试结果和日志将显示在终端中。
运行命令:
pytest
系统要求
- Python 3.7或更高版本。
- Windows 10+,Windows Server 2016+或Windows Subsystem for Linux (WSL)。
- MacOS 12 Monterey或MacOS 13 Ventura。
- Debian 11,Ubuntu 20.04或Ubuntu 22.04。