pytest框架(2)fixture、conftest、hook、pytest.ini、allure

本文详细介绍了pytest框架的使用,包括fixture的定义和应用,conftest.py文件的作用,pytest插件的hook函数及其执行顺序,pytest.ini配置文件的设置,以及allure报告的安装、特性和使用方法。通过示例展示了如何使用allure进行详细的测试报告记录和管理。

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

Fixture

pytest fixture 官网:
https://docs.pytest.org/en/stable/fixture.html#fixture

Fixture是在测试函数运行前后,由pytest执行的外壳函数,代码可以定制,满足多变的测试需求,
功能包括:

  • 定义传入测试中的数据集
  • 配置测试前系统的初始状态
  • 为批量测试提供数据源等

pytest fixture 使用
方法1:直接通过函数名,作为参数传递到方法中,有返回值

import pytest

@pytest.fixture
def login():
    print("login....")
    return "login success"
    
def test_add_cart2(login):
    print(login)
    print("添加购物车")

方法2:使用 @pytest.mark.usefixtures(‘login’),测试用例前加上装饰器,没有返回值

import pytest
@pytest.fixture
def login():
    print("login....")
    return "login success"
    
@pytest.mark.usefixtures("login")
def test_add_cart():
    print("添加购物车")

pytest fixture参数

  • autouse 自动应用。默认为False,设置为True自动应用。
  • scope指定作用域(session>module>class>function)
  • setup-show 回溯 fixture 的执行过程
import pytest

@pytest.fixture(autouse=True)
def login():
    print("login....")
    return "login success"

@pytest.fixture(scope="class")
def goto_main():
    print("goto mian page...")

@pytest.fixture(scope="function")
def login_out():
    print("login out....")

@pytest.mark.usefixtures("goto_main")
class TestFixture:
    def test_01(self):
        print("test_01")

    def test_02(self):
        print("test_02")

    def test_03(self,login_out):
        print("test_03")

运行结果
在这里插入图片描述

test_fixture.py --setup-show

在这里插入图片描述

conftest.py

  • conftest.py文件名固定
  • conftest.py 文件就近生效
存放fixture

conftest.py

#conftest.py
import pytest
@pytest.fixture(scope="function")
def setup_and_teardown():
    print("计算开始".center(30,"*"))
    yield "计算中..."
    print("计算结束".center(30,"*"))

test_add.py

#test_add.py
import pytest
def add(a,b):
    return a + b

class TestAdd:
    @pytest.mark.parametrize('a,b,expect',[[0.1,0.2,0.3],]
### 如何在 pytest-playwright 中集成 Allure 生成测试报告 #### 安装依赖库 为了实现这一目标,需要安装 `pytest`、`playwright` 和 `allure-pytest` 这些必要的 Python 库。可以通过 pip 来完成这些操作。 ```bash pip install pytest playwright allure-pytest ``` #### 修改配置文件 对于 `pytest-playwright.py` 文件来说,在其中加入如下代码片段用于引入 `allure` 包: ```python import allure ``` 这段代码确保了可以在编写测试案例的过程中调用 `allure` 的功能[^2]。 #### 编写测试用例 当准备好了环境之后就可以开始编写带有 `@allure.step()` 或者其他装饰器标记的测试函数了。下面是一个简单的例子展示了怎样利用 Playwright 执行浏览器自动化任务的同时记录下每一步骤的信息给 Allure 报告使用。 ```python import pytest from playwright.sync_api import sync_playwright import allure @pytest.fixture(scope="module") def browser(): with sync_playwright() as p: browser = p.chromium.launch(headless=False) yield browser browser.close() @allure.feature('User Login') class TestLogin: @allure.story('Successful login') def test_successful_login(self, browser): page = browser.new_page() with allure.step("Open the website"): page.goto("https://example.com/login") with allure.step("Enter username and password"): page.fill("#username", "admin") page.fill("#password", "secret") with allure.step("Submit form"): page.click("button[type='submit']") with allure.step("Verify successful login"): assert "Welcome" in page.text_content("h1") ``` 上述代码定义了一个名为 `TestLogin` 类及其内部的方法 `test_successful_login`, 使用了多个 `with allure.step()` 块来描述具体的操作流程,并且通过断言验证登录成功后的页面内容是否符合预期[^1]。 #### 设置命令行参数 为了让 Pytest 能够识别并处理 Allure 相关的数据,执行测试的时候应当附加特定选项。这里给出完整的 CLI 参数列表以及它们的作用解释: | 参数 | 描述 | | --- | --- | | `-v` | 提供更加详尽的日志输出,显示更多关于每个测试状态的具体细节 | | `-s` | 不捕获标准输入/输出流,使得任何来自被测程序的标准输出都能直接呈现在终端上 | | `--alluredir=./temps` | 设定一个临时目录用来存储由本次运行产生的中间数据文件夹路径为当前项目的根目录下的 temps 子文件夹内 | | `--clean-alluredir` | 在每次启动前清理掉之前存在的同名目录里的残留物 | 因此实际使用的命令应该是这样的形式: ```bash pytest -vs --alluredir=./temps --clean-alluredir tests/ ``` 这条指令会触发一次全面扫描整个 `tests/` 下面所有的 `.py` 文件寻找符合条件的单元测试项;与此同时还会初始化一个新的空闲空间专门存放即将要创建出来的 XML 格式的结构化日志文档集合体。 #### 自动生成 HTML 版本的可视化报表 最后一步就是把刚刚收集起来的一系列原始资料转换成易于阅读理解的形式——即HTML格式的交互式图表界面。这通常是在所有测试结束后自动发生的动作之一。为此目的服务而编写的钩子函数位于 `conftest.py` 文件之中: ```python import os import pytest def pytest_sessionfinish(session, exitstatus): """This hook is called after whole test run finished.""" os.system("allure generate ./temps -o ./report --clean") ``` 每当一轮完整的测试周期结束之际就会激活这个回调机制进而调用系统级 shell 指令去构建最终产物放置于相对应的位置等待用户查阅分析[^3]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值