浅谈自动化测试框架开发pytest插件

 本章我们介绍如何开发pytest插件,在上一篇文章中我们介绍了4个python单元测试框架。大概分两类,一类是必须有类继承的,例如 QTAF 和 unittest, 另一类是可以没有类继承,例如nose/nose2 和 pytest。对于没有可以没有类继承的框架,开发难度会稍大一些。

pytest扩展能力

如果我们需要给pytest增加额外的扩展能力,那么有三种方式。

1. 钩子函数

利用conftest.py 这个特殊的问题,可以创建钩子函数。

  • 目录结构:

pytest_sample/
├── conftest.py
└── test_sample.py

conftest.py文件中实现如下功能。

import pytest

@pytest.fixture
def hello():
    return "hello 虫师"

定义一个函数hello(),并使用pytest.fixture装饰器对其进行装饰。fixture的概念我们前面已经做介绍。这里fixture 默认的级别为function,可以理解为被装饰的函数会在每个功能前被执行。

然后,在test_sample.py 测试文件中调动钩子函数。

# 调用钩子函数hello
def test_case(hello):
    print("hello:", hello)
    assert hello == "hello 虫师"

在测试用例中钩子函数hello()作为测试用例的参数hello 被调用了。断言 hello函数返回的结果是否为“hello 虫师”

  • 执行用例:

> pytest -vs test_sample.py
================================= test session starts ===========================
collected 1 item

test_sample.py::test_case hello: hello 虫师
PASSED

================================== 1 passed in 2.61s ==
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值