引言

在自动化测试领域,Playwright 是一个强大的工具,它支持 Chromium、Firefox 和 WebKit 三大浏览器引擎。Playwright 提供了与 Pytest 集成的插件,使得编写端到端测试变得更加简单和高效。本文将介绍如何使用 Pytest Playwright 插件来编写和运行自动化测试。

pytest-playwright 插件简介

Playwright 的 Pytest 插件允许开发者通过 Pytest 命令行接口(CLI)来启动和控制 Playwright 的浏览器实例。这使得测试过程更加灵活,并且可以轻松地集成到现有的 Pytest 测试框架中。

安装和配置

可以通过以下命令安装:

pip install pytest-playwright

安装内置浏览器

playwright install 

使用 Pytest CLI 运行测试

使用 Pytest CLI 运行测试非常简单。只需在命令行中输入以下命令:

pytest --browser webkit --headed

这条命令会启动 WebKit 浏览器,并以有头模式(headed mode)运行测试。

自动化 CLI 参数配置

为了简化测试命令,可以在 pytest.ini 文件中自动添加常用的 CLI 参数:

# pytest.ini 文件内容
[pytest]
# 使用 Firefox 浏览器并开启 UI
addopts = --headed --browser firefox

CLI 参数详解

CLI 参数允许你定制测试的运行方式。以下是一些常用的参数:

  • --headed: 以有头模式运行测试(默认为无头模式 headless)。
  • --browser: 指定运行测试的浏览器,可以是 chromiumfirefoxwebkit。可以多次指定以测试不同的浏览器(默认为 chromium)。
  • --browser-channel: 指定要使用的浏览器通道。
  • --slowmo: 减慢 Playwright 操作的速度,单位为毫秒。这在调试时非常有用(默认为 0)。
  • --device: 指定要模拟的设备。
  • --output: 测试产生的工件(如截图、视频等)的目录(默认为 test-results)。
  • --tracing: 是否为每个测试记录跟踪信息。选项有 onoffretain-on-failure(默认为 off)。
  • --video: 是否为每个测试录制视频。选项有 onoffretain-on-failure(默认为 off)。
  • --screenshot: 是否在每个测试后自动捕获屏幕截图。选项有 onoffonly-on-failure(默认为 off)。
  • --full-page-screenshot: 是否在失败时捕获全页面截图。默认情况下,只捕获视口截图。需要启用 --screenshot 参数(默认为 off)。

代码示例

下面是一个简单的测试示例,使用 Pytest Playwright 插件来测试一个网页的标题:

# test_example.py
import pytest
from playwright.sync_api import Page, expect

@pytest.mark.parametrize("browser_type", ["chromium", "firefox", "webkit"])
def test_page_title(browser_type, browser):
    page = browser.new_page()
    page.goto("http://example.com")
    expect(page.title()).to_be("Example Domain")

在这个示例中,我们使用 pytest.mark.parametrize 装饰器来为不同的浏览器类型运行相同的测试。测试检查 “http://example.com” 的页面标题是否为 “Example Domain”。

以下是 CLI 参数及其使用示例:

–headed

运行测试时显示浏览器 UI。

pytest --headed

–browser

指定测试使用的浏览器类型。

pytest --browser chromium
pytest --browser firefox
pytest --browser webkit

–browser-channel

指定浏览器的版本通道。

pytest --browser-channel xxx

–slowmo

减慢 Playwright 操作的速度,方便观察测试过程。

pytest --slowmo 500

–device

模拟特定设备。

pytest --device "iPhone 6"

–output

指定测试产生的工件(如截图、视频等)的目录。

pytest --output works

–tracing

为每个测试记录跟踪信息。

pytest --tracing on
pytest --tracing retain-on-failure

–video

为每个测试录制视频。

pytest --video on
pytest --video retain-on-failure

–screenshot

在每个测试后自动捕获屏幕截图。

pytest --screenshot on
pytest --screenshot only-on-failure

–full-page-screenshot

在失败时捕获全页面截图。

pytest --screenshot on --full-page-screenshot on

结语

pytest-playwright 插件提供了丰富的 CLI 参数,可以帮助你定制测试环境,提高测试的可读性和可维护性。希望本文能够帮助你在自动化测试的道路上更进一步。

本站无任何商业行为
个人在线分享 » pytest-playwright 插件的使用
E-->