达永编程网

程序员技术分享与交流平台

Playwright与PyTest结合指南_pytest pageobject

Playwright与PyTest的结合,为Web自动化测试带来了强大的动力。它让你既能利用Playwright现代、跨浏览器的自动化能力,又能借助PyTest成熟测试框架的结构化、可扩展性来高效管理和组织测试用例。我会带你了解如何将这两者结合使用。

为了让你快速上手,我先用一个流程图来概括Playwright与PyTest结合使用的核心步骤和关键配置:


下面我们来详细看看各个环节。

安装与环境搭建

首先,你需要安装pytest和pytest-playwright插件,并安装Playwright所需的浏览器驱动。

# 1. 安装pytest和pytest-playwright插件
pip install pytest pytest-playwright

# 2. 安装Playwright浏览器驱动(安装较慢,耐心等待)
playwright install

编写你的第一个测试用例

创建一个测试文件(如test_example.py),PyTest会自动发现以test_开头的文件或函数。

import pytest
from playwright.sync_api import Page

# 使用page fixture,它由pytest-playwright提供
def test_visit_baidu(page: Page): # 将page fixture作为参数注入
    page.goto("https://www.baidu.com")
    page.fill('//*[@id="kw"]', "Playwright") # 使用XPath定位搜索框并输入
    page.click('#su') # 使用CSS选择器定位并点击“百度一下”按钮
    assert "Playwright" in page.title() # 断言页面标题包含特定文本
    print(page.title) # 打印当前页面标题

配置与执行测试

PyTest-P laywright提供了丰富的命令行参数(CLI)来灵活控制测试行为:

参数 (--)

说明

示例

--headed

有头模式(显示浏览器UI)下运行测试(默认:无头模式)

pytest --headed

--browser

指定浏览器(chromium, firefox, webkit)。可多次指定

pytest --browser chromium --browser firefox

--slowmo

减慢操作速度(毫秒),便于观察

pytest --slowmo 1000

--video

录制视频(on, off, retain-on-failure)

pytest --video on

--screenshot

截屏(on, off, only-on-failure)

pytest --screenshot on

--tracing

记录追踪信息(on, off, retain-on-failure),用于调试

pytest --tracing on

--numprocesses

使用pytest-xdist进行并行测试

pytest --numprocesses auto

你可以通过pytest.ini文件预设这些参数,避免每次手动输入:

# pytest.ini
[pytest]
addopts = --headed --browser chromium --slowmo 100 --video on --screenshot on

Fixtures的深度使用

Fixtures是PyTest的核心功能,用于设置和清理测试环境。pytest-playwright提供了开箱即用的fixtures。

1. 使用内置Fixtures 最常用的是page fixture,它为你提供了一个全新的浏览器页面。

def test_my_app(page: Page):
    page.goto("https://example.com")
    # ... 你的测试逻辑

2. Fixture的作用域 (Scope) Fixtures可以有不同的作用域,控制其创建和销毁的频率。

@pytest.fixture(scope='module') # 该fixture在整个模块中只执行一次
def browser():
    with sync_playwright() as p:
        browser = p.chromium.launch()
        yield browser # 提供浏览器实例给测试用例
        browser.close() # 所有测试完成后关闭浏览器

def test_example_1(browser): # 在不同的测试中复用同一个浏览器实例
    page = browser.new_page()
    # ...

3. 覆盖Fixtures的默认选项 你可以自定义浏览器或上下文的启动参数。

# conftest.py
import pytest

@pytest.fixture(scope="session")
def browser_context_args(browser_context_args):
    return {**browser_context_args, "ignore_https_errors": True} # 忽略HTTPS错误

# 或在测试用例中直接标记以覆盖特定上下文的选项
@pytest.mark.browser_context_args(timezone_id="Europe/Berlin", locale="de-DE")
def test_with_custom_timezone(page):
    # 这个测试将在欧洲/柏林时区运行

高级技巧与最佳实践

  1. 并行测试:使用pytest-xdist插件可以显著缩短大型测试集的运行时间。
  2. pip install pytest-xdist pytest --numprocesses auto # 根据CPU核心数自动创建worker进程

跳过测试:可以使用PyTest的skip标记根据条件跳过测试。

import pytest

@pytest.mark.skip("skip this test for now") # 无条件跳过
def test_skip_example():
    pass

@pytest.mark.skip_browser("firefox") # 自定义标记(需实现),跳过特定浏览器
def test_skip_firefox(page):
    pass

录制生成代码:Playwright的Codegen功能可以录制你的操作并生成PyTest代码。

playwright codegen --target python-pytest -o test_recording.py https://baidu.com

页面对象模式 (Page Object Model):对于复杂项目,强烈建议使用页面对象模式来分离页面元素定位和操作逻辑,提高代码的可维护性和可读性。

# 示例:一个简单的页面对象
class BaiduPage:
    def __init__(self, page: Page):
        self.page = page
        self.search_input = page.locator("#kw")
        self.search_button = page.locator("#su")

    def search(self, keyword):
        self.search_input.fill(keyword)
        self.search_button.click()

# 在测试中使用
def test_using_pom(page: Page):
    baidu_page = BaiduPage(page)
    baidu_page.search("Playwright")
    # ... 断言

移动端模拟与多浏览器测试:Playwright可以模拟移动设备,并利用PyTest的参数化功能进行多浏览器测试。

import pytest
from playwright.sync_api import sync_playwright

# 多浏览器参数化测试
@pytest.mark.parametrize("browser_type", ["chromium", "firefox", "webkit"])
def test_cross_browser(browser_type):
    with sync_playwright() as p:
        browser = getattr(p, browser_type).launch()
        # ... 测试逻辑
        browser.close()

# 移动端模拟
def test_mobile_emulation(playwright): # 使用playwright fixture
    iphone_12 = playwright.devices['iPhone 12 Pro']
    browser = playwright.webkit.launch()
    context = browser.new_context(**iphone_12)
    page = context.new_page()
    page.goto("https://m.example.com")
    # ... 移动端测试逻辑
    browser.close()

常见问题与排查

  • Fixtures未注入:确保测试函数的参数名与fixture名称完全一致(例如page)。
  • 异步与同步API:上述示例均使用同步API。Playwright也支持异步(async/await),如需使用异步,请确保使用async def定义测试函数,并使用from playwright.async_api import Page。
  • 元素定位问题:充分利用Playwright强大的定位器(locator),如page.locator('css=button').click(),并配合page.wait_for_selector()等等待方法避免竞态条件。
  • 查看详细输出:运行测试时添加-v或-s参数(如pytest -v -s)可以获取更详细的输出和打印语句。

Playwright与PyTest的结合,为你提供了一个功能全面、易于编写且易于维护的现代Web自动化测试方案。从简单的脚本到复杂的企业级测试套件,这个组合都能应对自如。

希望这份指南能帮助你快速上手。实践出真知,多写多试,你就会越来越熟练。

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言