likes
comments
collection
share

pytest-playwright基础教程(一)-安装与简单使用

作者站长头像
站长
· 阅读数 11

pytest-playwright基础教程(一)-安装与简单使用

本文结构

1.如何安装Playwright

2.怎么运行测试用例

3.夹具的简单介绍

简单介绍

本教程主要是翻译的官网教程

附上官方文档链接:Installation | Playwright Python

如何安装Playwright

在pycharm终端输入

pip install pytest-playwright

等待安装即可

pytest-playwright基础教程(一)-安装与简单使用


安装完成后,在终端输入

playwright install

安装playwright自带的浏览器驱动

怎么运行测试用例

创建一个名称为 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/")

    # 查找是否存在标题 为"Playwright".
    expect(page).to_have_title(re.compile("Playwright"))

    # 创建一个定位器实例
    get_started = page.get_by_role("link", name="Get started")

    # 严格查找一个值"/docs/intro".
    expect(get_started).to_have_attribute("href", "/docs/intro")

    # 点击 get_started 按钮.
    get_started.click()

    # 判断该链接中是否包含"intro".
    expect(page).to_have_url(re.compile(".*intro"))

在终端输入

pytest

运行测试用例

pytest-playwright基础教程(一)-安装与简单使用

默认情况下,会使用chromium内核运行测试用例,默认为无头模式,即不显示页面.最终结果呈现在终端中

其中 expect()函数的作用是:等待直到满足预期条件


使用pytest的测试夹具

import pytest
from playwright.sync_api import Page


@pytest.fixture(scope="function", autouse=True)
def before_each_after_each(page: Page):
    print("beforeEach")
    # Go to the starting url before each test.
    page.goto("https://playwright.dev/")
    yield
    print("afterEach")

def test_main_navigation(page: Page):
    # Assertions use the expect API.
    expect(page).to_have_url("https://playwright.dev/")

其中 @pytest.fixture(scope="function",autouse=True) 的作用就是让每个测试用例,都能使用这个装饰器装饰的函数,实现代码的复用

参数介绍:

scope = "function" 的作用表示这个夹具的使用时机是每个测试函数执行时

autouse = True 表示这个夹具自动寻找符合条件的测试用例,自动执行,不需要再调用此函数

其中 yield之前的代码在测试用例之前执行,yield之后的代码在测试用例之后执行

执行效果如下

pytest-playwright基础教程(一)-安装与简单使用

总结

本文介绍了如何开始使用playwright+pytest进行简单测试,还介绍了pytest中夹具的使用方法,希望能对大家有所帮助 (●'◡'●)