安装 pytest
打开命令行
pip install -U pytest
查看是否安装成功
pytest --version
目前版本是 pytest 6.2.3
官方文档 pytest
创建第一个测试
使用 sublime 编写一个源文件
def func(x):
return x + 1
def test_answer():
assert func(3) == 5
assert 语句验证测试期望。
运行的话
打开命令行,窗口切换到源文件所在目录,我这里的源文件保存在
C:\Users\Administrator\Desktop\test\20210406
通过 cd 进入该目录
C:\Users\Administrator> cd C:\Users\Administrator\Desktop\test\20210406
C:\Users\Administrator\Desktop\test\20210406>
命令行运行的话,可以有几种方式
直接输入 pytest
或者 py.test
或者 python –m pytest
这里以 pytest 命令为例,完成后,pytest将显示失败报告,因为func(3)未返回5。
如果不想用命令行的话,尝试一下把我们的源文件修改一下
import pytest
def test_a():
print ("-------------->test_a")
assert 1 #断言成功
def test_b():
print ("-------------->test_b")
assert 0 #断言失败
if __name__ == '__main__':
pytest.main('-s test_abc.py'.split()) #调用 pytest 的 main 函数执行测试
当然亦可以,因为我们的 pytest.main 中需要一个字符串类型的参数,所以可以用 split 自动分割成字符串或自行设置
import pytest
def test_a():
print ("-------------->test_a")
assert 1 #断言成功
def test_b():
print ("-------------->test_b")
assert 0 #断言失败
if __name__ == '__main__':
pytest.main(['-s', 'test_abc.py']) #调用 pytest 的 main 函数执行测试
运行多个测试
pytest 会运行当前目录下所有符合条件的 py 文件
我们也可以将多个测试放在一个组里面
# 该源文件为:test_class.py
class TestClass:
"""docstring for TestClass"""
def test_one(self):
x = "this"
assert "h" in x
def test_two(self):
x = "hello"
assert hasattr(x, "check")
命令行中输入
pytest -q test_class.py
-q 表示使其以极简模式展示出来
那么 test_one 会成功,test_two 会失败,补充说明 hasattr() 函数的用法
命令行中结果为:
C:\Users\Administrator\Desktop\test\20210406\test_calss>pytest -q test_class.py
.F [100%]
============================================== FAILURES ===============================================
_________________________________________TestClass.test_two__________________________________________
self = <test_class.TestClass object at 0x000001CA994107F0>
def test_two(self):
x = "hello"
> assert hasattr(x, "check")
E AssertionError: assert False
E + where False = hasattr('hello', 'check') test_class.py:9: AssertionError
======================================= short test summary info =======================================
FAILED test_class.py::TestClass::test_two - AssertionError: assert False
1 failed, 1 passed in 0.06s
上述代码中,第二行,其中 .
表示成功 passed ,F
表示失败 failed
- hasattr(object, name)
判断一个对象里面是否有name属性或者name方法。
返回BOOL值,有name特性返回True, 否则返回False。
举例说明:
class test():
name='xiaoming'
def run(self):
return 'Hello World!'
t=test()
print hasattr(t,"name")#输出True
print hasattr(t,"run")#输出True
补充说明
-v
可以显示测试的详细信息
pytest -h
查看 pytest 的所有选项