11-pytest-assert断言
Posted 爱学习de测试小白
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了11-pytest-assert断言相关的知识,希望对你有一定的参考价值。
目录
前言
- 在做自动化测试中,怎么把实际结果和预期结果作比较呢,有个专业的术语叫做断言,符合预期的用例状态是pass,不符合预期用例状态是 failed
断言passed
# -*- coding: utf-8 -*-
# @Time : 2021/10/14
# @Author : 大海
# @File : test_20.py
import pytest
def four():
return 4
def test_function():
# 调用four方法返回4,与期望结果相同,结果为passed
assert four() == 4
if __name__ == '__main__':
pytest.main(["-s", "test_20.py"])
断言failed
# -*- coding: utf-8 -*-
# @Time : 2021/10/14
# @Author : 大海
# @File : test_21.py
import pytest
def four():
return 4
def test_function():
# 调用four方法返回4,与期望结果不同,结果为failed
assert four() == 5
if __name__ == '__main__':
pytest.main(["-s", "test_21.py"])
断言error
# -*- coding: utf-8 -*-
# @Time : 2021/10/14
# @Author : 大海
# @File : test_22.py
import pytest
@pytest.fixture()
def user():
print("这是登录操作!")
user = '小白'
assert user == "小白兔" # 1.在fixture中断言失败就是error
return user
def test_1(user):
assert user == "小白"
# 2.代码写的有问题也会error,此处未定义名为login的fixture,
def test_2(login):
assert login == '小白'
if __name__ == "__main__":
pytest.main(["-s", "test_22.py"])
异常断言
# -*- coding: utf-8 -*-
# @Time : 2021/10/14
# @Author : 大海
# @File : test_23.py
import pytest
def test_zero_division():
"""断言除0异常"""
with pytest.raises(ZeroDivisionError) as e_info:
1 / 0
# 断言异常类型type
# e_info 是一个异常信息实例,它是围绕实际引发的异常的包装器。主要属性是.type、 .value 和 .traceback
print('value:', e_info.value)
print('type:', e_info.type)
print('traceback:', e_info.traceback)
assert e_info.type == ZeroDivisionError
# 断言异常value值
assert "division by zero" in str(e_info.value)
if __name__ == '__main__':
pytest.main(["-s", "test_23.py"])
常用断言
- assert xx 判断xx为真
- assert not xx 判断xx不为真
- assert a in b 判断b包含a
- assert a not in b 判断b不包含a
- assert a == b 判断a等于b
- assert a != b 判断a不等于b
# -*- coding: utf-8 -*-
# @Time : 2021/10/14
# @Author : 大海
# @File : test_24.py
import pytest
def is_true(age):
if age == 18:
return True
else:
return False
def test_01():
a = 5
b = -1
assert is_true(a) # 断言为真
assert not is_true(b) # 断言为假
def test_02():
# 断言包含
a = "hello"
b = "hello world"
assert a in b
def test_03():
# 断言不包含
a = '小白'
b = "大海"
assert a not in b
def test_04():
# 断言相等
a = "小白"
b = "小白"
assert a == b
def test_05():
# 断言不等
a = 5
b = 6
assert a != b
if __name__ == "__main__":
pytest.main(["-s", "test_24.py"])
以上是关于11-pytest-assert断言的主要内容,如果未能解决你的问题,请参考以下文章