playwright结合pytest使用案例
playwright简介
不愧是宇宙最强,它也是目前为止对ui自动化领域里最好的一个库,在selenium之上,还有对应的异步机制,其他见百度不便在此详叙。
本篇经典案例是对我司的veer产品做ui自动化的案例,可供参考 不谢~
安装与启动
# 安装 playwright-python 依赖库 pip install playwright # 安装浏览器驱动 python -m playwright install # 录制脚本 python -m playwright codegen
其实我们用的只是录制脚本里的定位语句,其他的需要自己改写。如下:
page层
class IndexPage: # 页面元素 url = "https://preview-www.veer.com/" popup = "i" search_box = "[placeholder=\"搜索照片、插画和矢量图,多个词用空格隔开\"]" value = "hello world" submit = "[class='search_bar_submit']" real_flag = "[class='count_label']" fail_flag = "共 0 个结果"
page层最小粒度控制,便于管理元素。
testcase层
具有以下特性(自行体会):
结合非GUI模式以方便CI/CD
结合PO模式以方便单独管理元素
结合pytest.mark.paramtrize实现参数化
结合pytest.fixture实现预处理
结合了日志记录 + 结果断言
import time from playwright.sync_api import Page from po.index_page import IndexPage as pg import pytest from common.log import logger @pytest.fixture(scope="function") def preview(page): page.goto(pg.url) page.click(pg.popup) yield page page.close() @pytest.mark.parametrize("word", ["hello world", "星空"]) def test_search(preview: Page, word): page = preview page.fill(pg.search_box, word) page.click(pg.submit) time.sleep(1) with page.expect_navigation(): flag = page.text_content(pg.real_flag) logger().info(flag) assert flag != pg.fail_flag