【20200828】【工作中也要充电呀】单元测试框架 pytest 的使用

一. pytest是什么?

pytest 是 python 的一种单元测试框架,与 python 自带的 unittest 测试框架类似,但是比 unittest 框架使用起来更加方便,效率更高。

二. pytest怎么安装安装?

安装:pip install -U pytest

验证是否安装成功 / 查看 pytest 版本 :py.test --version

三. pytest怎么用?

1. 只有一个测试样例

一个简单的例子:

import pytest

def func(x):
    return x+1

def test_func():     # 文件要以 "test_" 开头,函数要以 "test_" 开头,否则不会对它进行测试!
    assert func(3) == 5   # assert"断言"

在 PyCharm 终端输入:py.test

结果如下图,可以看出 pytest 测试了一项,即:test_pytest.py 文件下的 func 函数。

2. 有多个测试样例 

简单的小例子:

import pytest
class TestClass:
    def test_one(self):
        x = "this"
        assert "h" in x


    def test_two(self):
        x = "hello"
        assert hasattr(x, "check")

在 PyCharm 终端输入:py.test

结果如下图,可以看出 pytest 测试了三项,即:test_pytest.py 文件下的 func 函数、test_class.py 文件下的 test_one 和 test_two 函数。

四. 几条 pytest 测试样例编写原则 

1. 测试【文件】,文件名要以 “test_” 开头(以 “_test” 结尾也可以);

2. 测试【类】,类名要以 “Test_” 开头,并且不能带有 “__init__” 方法;

3. 测试【函数】,函数名要以 “test_” 开头;

4. 断言使用 “assert”。

五. 生成测试报告

生成 HTML 格式的报告:py.test --resultlog=path,如下图:

生成 XML 格式的报告:py.test --junitxml=path,如下图:

(参考:【Pytest】python单元测试框架pytest简介) 

(参考:Python之pytest从基础到实战(二十六)


知识点

1. hasattr(object, name):检查 object 对象中是否有 name 属性。

例如:

class Coordinate:
    x = 10
    y = -5
    z = 0

point = Coordinate()
print(hasattr(point, 'x'))
print(hasattr(point, 'y'))
print(hasattr(point, 'z'))
print(hasattr(point, 'no'))

运行结果:

 

(参考:Python hasattr()

(参考:Python hasattr() 函数

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Satisfying

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

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

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

打赏作者

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

抵扣说明:

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

余额充值