返回

技术入门:pytest-playwright 基础教程(一)——安装与简单使用

后端

1. Playwright 的安装

Playwright 是一款开源跨浏览器的自动化测试工具,支持 Chromium、Firefox 和 WebKit 等主流浏览器。其强大的功能和易用性使其成为众多自动化测试工程师的首选。

1.1 前提条件

在安装 Playwright 之前,需要确保计算机上已安装了 Node.js 环境。Node.js 的版本需要在 10.15 以上。

1.2 安装 Playwright

安装 Playwright 的步骤如下:

  • 打开终端或命令提示符。
  • 输入以下命令:
npm install -g playwright
  • 等待安装完成。

1.3 验证安装

安装完成后,可以通过以下命令验证 Playwright 是否安装成功:

playwright --version

如果看到版本信息,则表示 Playwright 已成功安装。

2. 运行测试用例

2.1 创建项目

创建一个新的 Node.js 项目,用于存放测试用例。

2.2 安装依赖

在项目目录下,输入以下命令安装 pytest 和 pytest-playwright:

npm install --save-dev pytest pytest-playwright

2.3 创建测试文件

创建一个名为 test_example.py 的文件,并将以下代码粘贴进去:

import pytest
import playwright

@pytest.fixture(scope="class")
def browser(request):
    # 在类级别启动浏览器实例
    browser = playwright.chromium.launch()

    # 在类级别结束时关闭浏览器实例
    def fin():
        browser.close()

    request.cls.browser = browser

    yield browser


@pytest.mark.usefixtures("browser")
class TestExample:
    def test_example(self):
        # 获取当前页面
        page = self.browser.new_page()

        # 打开百度
        page.goto("https://www.baidu.com")

        # 截图
        page.screenshot(path="example.png")

        # 断言标题
        assert page.title() == "百度一下,你就知道"

        # 关闭页面
        page.close()

2.4 运行测试用例

在项目目录下,输入以下命令运行测试用例:

pytest

如果测试用例执行成功,将看到以下输出:

=== test session starts ===
platform darwin -- Python 3.10.4, pytest-7.1.2, py-1.11.0, pluggy-1.0.0
rootdir: /Users/username/projects/test_project
collected 1 item

test_example.py .

=== test session starts ===

3. 夹具的简单介绍

夹具(Fixture)是 pytest 中的一个重要概念,它允许在测试用例中共享代码和资源。夹具可以是函数、类或方法,通过 @pytest.fixture() 修饰器定义。

在上面的示例中,我们定义了一个名为 browser 的夹具,该夹具会在每个测试类开始时启动一个浏览器实例,并在测试类结束时关闭该实例。这样,测试用例就可以通过 self.browser 访问浏览器实例。

夹具还可以用于共享其他资源,例如数据库连接、文件句柄等。

4. 总结

本教程介绍了 pytest-playwright 的基本安装、测试用例运行和夹具的使用方法。这些知识为读者后续的学习和使用 pytest-playwright 打下了坚实的基础。在接下来的教程中,我们将继续深入探索 pytest-playwright 的更多特性和用法,敬请期待!