一. 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简介)
知识点
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() 函数)