了解pytest的conftest.py文件

1.conftest.py 是 pytest 框架中的一个特殊配置文件,用于定义全局的测试配置和辅助功能。它主要用来实现以下功能:

Fixture:定义共享的fixture,供测试用例使用。
钩子函数:实现pytest的钩子函数,以便在测试运行的不同阶段执行特定代码。
插件:可以在 conftest.py 中定义插件,使其自动应用于所有测试。

Fixture
Fixtures 是 pytest 中用于在测试执行前准备测试环境的函数。它们可以在 conftest.py 中定义,以便在整个测试目录中共享。而在测试用例文件中定义的 fixture 仅对该文件中的测试用例可见和可用,它们不会被其他文件中的测试用例使用。

#conftest.py
import pytest
@pytest.fixture()
def paas_token():
    user_token = paas_login()
    return user_token

在测试用例中使用这个fixture:

# test_db.py
def test_query(paas_token):
    assert name == "Amy"

钩子函数
pytest 提供了很多钩子函数,可以在 conftest.py 中实现这些函数,以在测试的不同阶段执行特定操作。
如pytest_terminal_summary,用于在测试执行完成后生成终端摘要报告。这个钩子函数允许你自定义测试报告的输出内容,使你可以添加额外的信息或统计数据到 pytest 生成的终端报告中。

# conftest.py
def pytest_terminal_summary(terminalreporter, exitstatus, config):
    """
    在测试完成后生成终端摘要报告。
    
    :param terminalreporter: 终端报告生成器
    :param exitstatus: 测试执行的退出状态
    :param config: pytest配置对象
    """
    stats = terminalreporter.stats
    total = terminalreporter._numcollected
    passed = len(stats.get('passed', []))
    failed = len(stats.get('failed', []))
    error = len(stats.get('error', []))
    skipped = len(stats.get('skipped', []))
    xfailed = len(stats.get('xfailed', []))

    desc = f"""
        本次执行情况如下:
        总用例数为:{total}
        通过用例数:{passed}
        失败用例数: {failed}
        错误用例数:{error}
        预期失败的用例:{xfailed}
        跳过用例数:{skipped} 
        测试报告地址:[http://{host}:60000/index.html](http://{host}:60000/index.html)
        """
    send_msg(desc)#发送给企业微信

发送到企业微信的结果截图:
在这里插入图片描述
插件
conftest.py 可以用来定义和注册插件,使其在测试中自动应用。例如,可以编写一个插件来记录所有测试的执行时间。

# conftest.py

import pytest
import time

def pytest_runtest_setup(item):
    item.start_time = time.time()

def pytest_runtest_teardown(item, nextitem):
    duration = time.time() - item.start_time
    print(f"测试 {item.name} 花费时间: {duration:.2f} 秒")

文件结构
在这里插入图片描述
在这种结构中,conftest.py 中定义的fixture和钩子函数可以被tc目录中的所有测试用例自动使用。

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值