使用Playwright+Pytest+Yaml+Allure搭建UI自动化测试用例框架

本文详细介绍了如何使用Playwright搭建UI自动化测试框架,并展示了如何通过分层设计提高代码可维护性和测试覆盖率,包括安装步骤、Allure配置和各层次功能如点击、截图等的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本人在学习搭建playwright的UI自动化框架时,发现网上讲解的搭建过程不详细且极容易报错。便写下该篇文章,便于记录及后续本人与读者使用。

安装软件包

pip install pyaml
pip install playwright
python -m playwright install chromium
pip install allure-pytest
pip install pytest
pip install pytest-playwright

下载allure并配置环境

官网下载地址:https://repo.maven.apache.org/maven2/io/qameta/allure/allure-commandline/

开源地址

Gitee:Playwright+Pytest+Allure测试UI自动化框架

注:欢迎大家进入Gitee进行lssues与优化代码,完善自动化框架。

目录

common(公共方法层)
testcase(用例层)
data(数据层)
log(日志层)
reports(报告层)
在这里插入图片描述

common公共方法层

该层用于存放用例常调用的函数
action.py(复杂动作封装)

# 点击输入内容
def click_fill(page, local, fills):
	page.locator(local).click()
	page.locator(local).fill(fills)

attach.py(结果处理动作封装)

import allure
from playwright.sync_api import Page

'''
 readAttach:
 入参(page, 路径[./log/screenshot/], 文件名[test_playwright])
'''

# 结果截图与Allure提取
def readAttach(page: Page, paths, fileName):
	page.screenshot(path=paths + fileName + ".png")
	with open(paths + fileName + ".png", "rb") as file:
		allure.attach(file.read(), name=fileName, attachment_type=allure.attachment_type.PNG)

read_file.py(yaml文件读取)

import yaml

from setting import DIR_NAME


def read_yaml(file_path):
    with open(DIR_NAME + file_path, "r", encoding="utf-8") as f:
        return yaml.load(f, Loader=yaml.FullLoader)


if __name__ == "__main__":
    print(read_yaml("/data/base.yaml"))
    print(read_yaml("/data/base.yaml")["test_pytest"]["goto"])

testcase用例层

该层存放自动化用例并用于执行
conftest.py(fixtures)

import allure
from pytest import Item

def pytest_runtest_call(item: Item):
	if item.parent._obj.__doc__:
		allure.dynamic.feature(item.parent._obj.__doc__)

	if item.function.__doc__:
		allure.dynamic.title(item.function.__doc__)

test_基础数据.py

import allure
import pytest

from common.action import click_fill
from common.attach import readAttach
from common.read_file import read_yaml
from playwright.sync_api import Page


@allure.epic("基础数据")
@allure.title("搜索pytest")
def test_pytest(page: Page):
    # 读取yaml文件
    dbinfo = read_yaml("/data/base.yaml")
    # 打开地址
    page.goto(dbinfo["test_pytest"]["goto"])
    # 搜索框输入内容
    click_fill(page, "#kw", dbinfo["test_pytest"]["fills"])
    # 点击'百度一下'
    page.get_by_role("button", name="百度一下").click()
    # 截图结果并保存到log与allure
    readAttach(page, dbinfo["test_pytest"]["path"], dbinfo["test_pytest"]["fileName"])


@allure.epic("基础数据")
@allure.title("搜索allure")
def test_allure(page: Page):
    dbinfo = read_yaml("/data/base.yaml")
    page.goto(dbinfo["test_allure"]["goto"])
    click_fill(page, "#kw", dbinfo["test_allure"]["fills"])
    page.get_by_role("button", name="百度一下").click()
    readAttach(page, dbinfo["test_allure"]["path"], dbinfo["test_allure"]["fileName"])

test_采购.py

import allure
from common.attach import readAttach
from playwright.sync_api import Page


@allure.epic("采购模块")
@allure.title("搜索playwright")
def test_playwright(page: Page):
    page.goto("https://www.baidu.com/")
    page.locator("#kw").click()
    page.locator("#kw").fill("playwright")
    page.get_by_role("button", name="百度一下").click()
    readAttach(page, "./log/screenshot/", "test_playwright")

Data数据层

该层用于存储业务层数据变量,方便后续维护与调整。如:数据不适用能更快速找到位置更改

注:一个用例配一个yaml
base.yaml

test_pytest:
  goto: https://www.baidu.com/
  fills: pytest
  path: ./log/screenshot/
  fileName: test_pytest
test_allure:
  goto: https://www.baidu.com/
  fills: allure
  path: ./log/screenshot/
  fileName: test_allure

pytest.ini

[pytest]
# 全集测试
addopts = -vs --alluredir=./reports/tmp --clean-alluredir
# 冒烟测试
;addopts = -sv -m smoke --alluredir ./reports/apiReport --clean-alluredir
testpaths = ./testcase
python_files = test_*.py
python_classes = Test*
python_functions = test_*
markers =
    smoke

run.py

import os

import pytest

if __name__ == "__main__":
    pytest.main()
    os.system("allure generate ./reports/tmp -o ./reports/UIReport --clean")
    # 本地启动打开Allure报告HTML
    os.system("allure serve ./reports/tmp")

setting.py

import os

DIR_NAME = os.path.dirname(os.path.abspath(__file__))
print(DIR_NAME)

日志层、报告层(运行后自动生成)

附分层意义的解答:

分层的目的用于代码可维护性,可行性,可持续性,简洁性。下面我列举几个例子,大家就会知道分层的意义。

例:四个层级合并在一个用例写,当登录环境地址切换 你需每个用例都调整,分层只需调整Login.py

四个层级合并在一个用例写,当变量数据全部需要调整时,你得找到每个步骤修改数据,分层只需调整test02.yaml

07f8f234-d6ac-4dfd-a512-e9a19c03dc43

### 使用 Python PlaywrightPytest 进行自动化测试 #### 安装必要的库 为了构建基于 PythonUI 自动化测试框架,需安装多个依赖项。这些工具包括用于编写和运行测试的 `pytest` 及其扩展模块 `pytest-playwright`,以及浏览器自动化的核心组件 `playwright`。 ```bash pip install pytest playwright pytest-playwright ``` 对于 Chromium 浏览器的支持,则通过命令来完成相应驱动程序的下载: ```bash python -m playwright install chromium ``` 此操作会确保本地环境中具备执行自动化脚本所需的全部资源[^1]。 #### 编写第一个测试案 创建简单的登录功能验证示可以更好地理解整个流程。下面是一个基本结构,在这里定义了一个名为 `test_login.py` 文件中的函数用来模拟用户输入用户名密码并提交表单的过程。 ```python import pytest def test_successful_login(page): page.goto("http://example.com/login") # 替换成实际网址 page.fill("#username", "admin") page.fill("#password", "secret") page.click("button[type='submit']") assert page.url == "http://example.com/dashboard" ``` 上述代码片段展示了如何利用 Page 对象提供的方法与网页交互,并最终断言页面跳转到了预期的目标地址以确认登录成功[^2]。 #### 配置报告生成 为了让测试结果更加直观易读,推荐集成 Allure 报告生成功能。这不仅有助于团队成员之间分享测试进展,也方便定位失败原因。首先得安装 allure-pytest 插件: ```bash pip install allure-pytest ``` 接着可以在命令行中指定参数让 pytest 输出 allure 格式的日志文件夹路径: ```bash pytest --alluredir=./results tests/ ``` 最后借助于独立发布的 Allure 命令行工具或者 Jenkins 等 CI 平台上的插件来进行可视化展示[^3]。 #### 实际应用场景下的注意事项 当面对更复杂的业务逻辑时,建议采用 YAML 或 JSON 文件存储测试数据,使维护变得更加轻松;同时考虑引入 fixture 来管理前后置条件,提高代码复用率。另外,针对不同环境可能存在的差异(比如开发、预发布),应当灵活调整配置选项以适应变化的需求[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

KrityCat

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值