pytest的简单学习
一、介绍及下载安装
- pytest是python的一种单元测试框架,与python自带的unittest测试框架类似,但是比unittest框架使用起来更简洁,效率更高。
- 其主要使用assert断言对单元方法记性测试
- 其有个fixture类,可以减少资源占用,资源的统一调度
- 安装:
pip install -U pytest
- 测试:
py.test --version
或者pytest --version
二、基础单元测试(assert断言)
- assert断言是python标准语法里的东西
- asset后是一个返回布尔值的表达式
- 若为真,则通过;若为假,抛出异常
# example
>>>assert 1 == 1
>>>assert 2+2 == 2*2
>>>assert len('hello') < 10
>>>assert len('hello') > 10
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
>>>assert len('hello') > 10, '字符串长度小于10'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError: 字符串长度小于10
>>>assert range(4) == [0,1,2,3]
通过上面关于assert的例子,可以看出很适合单元测试。
1、测试函数的例子
def func(x):
return x+1
def test_func():
assert func(3) == 5
进入终端,在该文件所在目录下,执行pytest
。
执行结果如下:
========================= test session starts =========================
platform linux2 -- Python 2.7.13+, pytest-3.7.4, py-1.6.0, pluggy-0.7.1
rootdir: /home/light/code/study/test_pytest, inifile:
plugins: celery-4.2.1
collected 1 item
test_pytest.py F [100%]
========================= FAILURES =========================
_________________________ test_func ________________________
def test_func():
> assert func(3) == 5
E assert 4 == 5
E + where 4 = func(3)
test_pytest.py:6: AssertionError
========================= 1 failed in 0.39 seconds =========================
pytest会在当前的目录下,寻找以test开头的文件(即测试文件),找到测试文件之后,进入到测试文件中寻找test_开头的测试函数并执行。
通过上面的测试输出,我们可以看到该测试过程中,收集到了一个测试函数,测试结果是失败的(标记为F),并且在FAILURES部分输出了详细的错误信息,帮助我们分析测试原因,我们可以看到”assert func(3) == 5”这条语句出错了,错误的原因是func(3)=4。
2、测试类的例子
class TestClass:
def test_one(self):
x = "this"
assert 'h' in x
def test_two(self):
x = "hello"
assert hasattr(x, 'check')
进入终端,在该文件所在目录下,执行pytest
。
执行结果如下:
========================= test session starts =========================
platform lin