一、pytest入门?
pytest框架使编写小型测试变得容易,但可以扩展以支持应用程序和库的复杂功能测试。
特点:
- 失败的assert语句的详细信息
- 自动发现测试模块和方法
二、使用步骤
1.引入库
代码如下(示例):
'''
只执行pytest,会查找当前目录及子目录下test_*.py和*_test.py文件
如果想只执行某个文件,可以pytest start.py
加上-q就是显示简单的结果pytest -q start.py
'''
def func(x):
return x+1
def test_answer():
assert func(3) == 5
class TestClass:
def test_one(self):
x = "this"
assert 'h' in x
def test_two(self):
x = 'hello'
assert hasattr(x,"check")
##2.断言引发的异常判断
import pytest
def f():
raise SystemExit(1)
def test_mytest():
with pytest.raises(SystemExit):
f()
以“安静”报告模式执行测试功能:
pytest -q test_sysexit.py,
输出为:
. [100%]
1 passed in 0.01s
2.pytest执行标准
python测试发现的约定:
- 如果没有指定参数,集合从testpaths或者当前目录执行。或者,命令行参数可以用于目录、文件名或节点ID的任意组合。
- 递归到目录中,除非匹配norecursedirs
- 目录中搜索tets_.py或者_test.py文件 ,由其导入test package name
- 从文件中收集测试项
- test在类外加前缀的测试函数或者方法,test内置前缀测试函数或方法Test带前缀的测试类(不包含__init__方法)
一个类中的多个测试分组
def func(x):
return x+1
def test_answer():
assert func(3) == 5
class 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
输出结果:
D:\pytest\exe\test\learn>pytest -q test_class.py
F.F [100%]
==========================================