Pytest之断⾔
在⾃动化测试过程中,需要判断预期结果和实际结果是否⼀致,这时需要使⽤到断⾔。
什么是断⾔呢?简单来说就是实际结果和期望结果去对⽐。
断⾔⽤法
在pytest中,使⽤asrt进⾏断⾔,格式为:asrt 表达式。
如果表达式返回结果为True,则断⾔成功,否则断⾔失败。
常⽤断⾔
unittest的三种断⾔:
asrtIn(expect,result)断⾔包含(被包含的写前⾯);2012高考优秀作文
asrtEqual(expect,result)断⾔相等;
asrtTure(条件)断⾔是否为真。返回Ture或Fal;
Pytest⾥的断⾔实际上就是Python中的asrt断⾔⽅法,常⽤断⾔⽅法如下:
asrt xx :判断 xx 为真;
asrt not xx :判断 xx 不为真;potentiality
asrt a in b :判断 b 包含 a;
asrt a == b :判断 a 等于 b;
asrt a != b :判断 a 不等于 b;
import pytest
def test_demo1():
a = 1
asrt a
def test_demo2():
a = 0
asrt not a
def test_demo3():
s = 'hello'
asrt 'h' in s
def test_demo4():
a = 3
asrt a == 3
def test_demo5():
a = 4
asrt a != 3
if __name__ == '__main__':
pytest.main()
运⾏结果如下:
白木耳是什么意思Testing started at 18:22 ...
C:\Urs\96984\Desktop\code\pytest\venv\ "C:\ruanjian\pycharm2019.3\PyCharm 2019.3.1\plugins\python\helpers\pycharm\_jb_pytest_runner.py" --path C:/Urs/96984/Desktop/code/pytest/demo/demo_pytest.py Launching pytest with arguments C:/Urs/96984/Desktop/code/learn_pytest/demo/demo_pytest.py in C:\Urs\96984\Desktop\code\learn_pytest\demo
============================= test ssion starts =============================
platform win32 -- Python 3.6.8, pytest-5.4.3, py-1.9.0, pluggy-0.13.1 -- C:\Urs\96984\Desktop\code\learn_pytest\venv\
cachedir: .pytest_cache
metadata: {'Python': '3.6.8', 'Platform': 'Windows-10-10.0.18362-SP0', 'Packages': {'pytest': '5.4.3', 'py': '1.9.0', 'pluggy': '0.13.1'}, 'Plugins': {'html': '2.1.1', 'metadata': '1.10.0'}, 'JAVA_HOME': 'C:\\Program Files\\Java\\jdk1.8.0_77'} rootdir: C:\Urs\96984\Desktop\code\learn_pytest\demo
plugins: html-2.1.1, metadata-1.10.0
collecting ... collected 5 items
demo_pytest.py::test_demo1 PASSED [ 20%]
demo_pytest.py::test_demo2 PASSED [ 40%]indivi
demo_pytest.py::test_demo3 PASSED [ 60%]
demo_pytest.py::test_demo4 PASSED [ 80%]
demo_pytest.py::test_demo5 PASSED [100%]
============================== 5 pasd in 0.06s ==============================
Process finished with exit code 0
异常断⾔
在测试过程中,有时需要对特定异常进⾏断⾔,可以使⽤ pytest.rais 作为上下⽂管理器,当抛出异常时可以获取到对应的异常实例。
import pytest
def test_zero_division():
nob1 / 0
if __name__ == '__main__':
pytest.main()
运⾏结果:
================================== FAILURES ===================================
_____________________________ test_zero_division ______________________________
def test_zero_division():
> 1 / 0
E ZeroDivisionError: division by zero
所以我们需要捕获并断⾔异常。
断⾔场景:断⾔抛出的异常是否符合预期。
预期结果:ZeroDivisionError: division by zero,其中ZeroDivisionError为错误类型,division by zero为具体错误值。断⾔⽅式: 断⾔异常的type和value值。
断⾔代码如下:
import pytest
def test_zero_division_long():
with pytest.rais(ZeroDivisionError) as excinfo:
1 / 0
# 断⾔异常类型 type
pe == ZeroDivisionError
# 断⾔异常 value 值
asrt "division by zero" in str(excinfo.value)
if __name__ == '__main__':
beg的用法pytest.main()
星巴克咖啡粉代码详细说明:
① pytest.rais 捕获异常,源码如下:
def rais( # noqa: F811
expected_exception: Union["Type[_E]", Tuple["Type[_E]", ...]],
*args: Any,
**kwargs: Any
) -> Union["RaisContext[_E]", _pytest._code.ExceptionInfo[_E]]:
__tracebackhide__ = True
for exc in filterfal(
inspect.isclass, always_iterable(expected_exception, BASE_TYPE) # type: ignore[arg-type] # noqa: F821
):
msg = "exceptions must be derived from BaException, not %s"
rai TypeError(msg % type(exc))
message = "DID NOT RAISE {}".format(expected_exception)
if not args:
match = kwargs.pop("match", None)
if kwargs:
msg = "Unexpected keyword arguments pasd to pytest.rais: "
ampoulemsg += ", ".join(sorted(kwargs))
msg += "\nU context-manager form instead?"
rai TypeError(msg)
return RaisContext(expected_exception, message, match)
el:
func = args[0]
if not callable(func):
rai TypeError(
大连电脑培训
"{!r} object (type: {}) must be callable".format(func, type(func))
)
try:
func(*args[1:], **kwargs)
except expected_exception as e:
# We just caught the exception - there is a traceback.
asrt e.__traceback__ is not None
return _pytest._code.ExceptionInfo.from_exc_info(
(type(e), e, e.__traceback__)
)
fail(message)
rais.Exception = fail.Exception # type: ignore
② excinfo作为异常信息实例,拥有type 、value等属性,源码如下:
@property
def type(lf) -> "Type[_E]":
"""the exception class"""
asrt (
lf._excinfo is not None
), ".type can only be ud after the context manager exits"
return lf._excinfo[0]
@property
def value(lf) -> _E:
"""the exception value"""
asrt (
lf._excinfo is not None
), ".value can only be ud after the context manager exits"
return lf._excinfo[1]
③ excinfo.value的值是元组,所以要转成字符串。
被就业