快速上手

环境依赖

pytest-xlsx 的使用环境为: python >=3.12和 pytest>=8.2

具体依赖如下:

python>=3.12
pytest>=8.2
openpyxl~=3.0
pyyaml~=6.0

安装插件

pip install pytest-xlsx -U

添加配置

鉴于excel文件应用广泛,为了避免误操作,本插件需要通过配置文件手动启用后才会生效。

具体来说:

  1. 在根目录创建 pytest.ini

  2. 写入下面这些内容

# pytest.ini
[pytest]

# 执行xlsx用例
xlsx_run_case = true

# 指定meta列,用来解析内容
xlsx_meta_column_name  = 关键字

使用插件

1. 创建用例

创建xlsx文件用例,并在meta列(本例中为 关键字 ) 编写解析标记

备注

注意:文件名必须是 test_ 开头,以此和非用例的xlsx进行区分

其中有两个内置标记将被插件解析,其他标记则传递给钩子函数进行解析:

  • name:必填,不可重复 ,用指定明用例名称

  • mark:选填,可重复,用来添加pytest标记

为了简化逻辑便于理解,我们约定: 总是以 name 标记作为一个用例的开始

例如:

test_demo.xlsx

关键字

name

百度首页

goto

https://www.baidu.com

2. 创建钩子

插件在执行xlsx用例时,将 namemark 之外内容,依次传递给钩子 pytest_xlsx_run_step()

所以,创建钩子,即可得到每一个具体步骤,并根据步骤内容完成相应的动作。

备注

注意:钩子应该返回True,以便后续的同名钩子不再执行

# conftest.py

from selenium import webdriver
from pytest_xlsx import XlsxItem

def pytest_xlsx_run_step(item: XlsxItem):
    driver = webdriver.Chrome()

    step = item.current_step
    action = step.get("关键字")
    args = step.get("_BlankField")  # `_BlankField` 存储所有空白字段数据

    if action == 'goto':
        driver.get(*args)

    driver.quit()
    return True

3. 执行用例

启动pytest框架即可加载和执行xlsx用例

(.venv) C:\demo\pytest-xlsx-demo>pytest
========================= test session starts =========================
platform win32 -- Python 3.12.0, pytest-8.2.2, pluggy-1.5.0
rootdir: C:\demo\pytest-xlsx-demo
configfile: pytest.ini
plugins: xlsx-2.0.0
collected 1 item

test_demo.xlsx.                                                 [100%]
========================= 1 passed in 45.81s =========================

下一步

现在你已经可以用pytest执行xlsx文件用例了,

接下来,可以继续学习在xlsx文件中使用mark、fixture、数据驱动、变量、函数等内容。

此外,也可以在xlsx文件中使用其他的pytest插件(通常是mark或fixture的方式)