示例代码如下:
# -*- coding: utf-8 -*-
# @Time : 2020/10/25 17:17
# @Author : longrong.lang
# @FileName: test_pass.py
# @Software: PyCharm
# @Cnblogs :https://www.cnblogs.com/longronglang
'''
测试通过的例子
'''
import pytest
@pytest.fixture()
# 定义一个测试数据
def data():
return 1
def test_pass(data):
assert 1 == data
if __name__ == '__main__':
pytest.main(["-q", "test_pass.py"])
示例代码如下:
# -*- coding: utf-8 -*-
# @Time : 2020/10/25 17:26
# @Author : longrong.lang
# @FileName: test_failed.py
# @Software: PyCharm
# @Cnblogs :https://www.cnblogs.com/longronglang
'''
断言失败的栗子
'''
import pytest
@pytest.fixture()
def data():
return 'python'
def test_failed(data):
assert 'test' in data
if __name__ == '__main__':
pytest.main(["-q", "test_failed.py"])
示例代码如下:
# -*- coding: utf-8 -*-
# @Time : 2020/10/25 17:26
# @Author : longrong.lang
# @FileName: test_failedException.py
# @Software: PyCharm
# @Cnblogs :https://www.cnblogs.com/longronglang
'''
断言失败的栗子
'''
import pytest
@pytest.fixture()
def data():
return 'python'
def test_failed(data):
# 这块随便抛出一个异常了
raise IOError
assert 'py' in data
if __name__ == '__main__':
pytest.main(["-q", "test_failedException.py"])
示例代码如下:
# -*- coding: utf-8 -*-
# @Time : 2020/10/25 17:34
# @Author : longrong.lang
# @FileName: test_error.py
# @Software: PyCharm
# @Cnblogs :https://www.cnblogs.com/longronglang
'''
代码编写上的错误栗子
'''
import pytest
@pytest.fixture()
def data():
str = 'python'
assert 'test' in str
return str
def test_error(data):
assert data == 'python'
if __name__ == '__main__':
pytest.main(["-q", "test_error.py"])
fixture里面断言失败,导致fixture标记的data会报错,使得data没有返回值;而test_error调用了错误的fixture,所以error表示代码写的有问题了
示例代码如下:
# -*- coding: utf-8 -*-
# @Time : 2020/10/25 17:34
# @Author : longrong.lang
# @FileName: test_errorNoParam.py
# @Software: PyCharm
# @Cnblogs :https://www.cnblogs.com/longronglang
'''
代码编写上的错误栗子
'''
import pytest
def data():
str = 'python'
return str
def test_error(data):
assert data == 'python'
if __name__ == '__main__':
pytest.main(["-q", "test_errorNoParam.py"])
data参数并不存在,找不到自然就error了
这个和testng的异常测试差不多了,就是断言预期的异常,可以测试是否需要代码抛出异常或不抛出。示例代码如下:
# -*- coding: utf-8 -*-
# @Time : 2020/10/25 17:51
# @Author : longrong.lang
# @FileName: test_xfail.py
# @Software: PyCharm
# @Cnblogs :https://www.cnblogs.com/longronglang
'''
预期失败栗子
'''
import pytest
# 断言装饰器
@pytest.mark.xfail(raises=ZeroDivisionError)
def test_xfail():
var = 1 / 0
print(var)
代码有异常,且和raised的异常类匹配,所以是xfail(算测试通过的一种,表示符合期望捕捉到的异常),并不算failed
如果和raised的异常类不匹配,则是failed