[英]Performing an assertion in a test written with pytest that should not have occurred
下面是执行每个断言的完整测试代码。 出于一个原因,这对我来说是不直观的。 如果变量 k 的值为 None 则 function t 抛出异常,因此不应执行调用 t 之后的代码,并且应由上下文管理器捕获异常。 但是,这不会发生,我不知道为什么。 并不是说它困扰我,它以这种方式执行甚至很棒,但我想知道为什么。
from contextlib import nullcontext as does_not_raise
import pytest
def t(k):
if k:
return k
else:
raise ValueError("Value")
@pytest.mark.parametrize("k, cntxt", [(None, pytest.raises(ValueError)), ("Value", does_not_raise())])
def test_t(k, cntxt):
with cntxt as ex:
kk = t(k)
if k:
assert kk == k
assert ex is None
else:
assert kk is None
assert str(ex.value) == "Value"
如果变量 k 的值为 None 则 function t 抛出异常,因此不应执行调用 t 之后的代码,并且应由上下文管理器捕获异常。
除非我误解了你,否则我相信这正是正在发生的事情。 在k
为None
的情况下,不会执行这些行:
assert kk is None
assert str(ex.value) == "Value"
为确保是这种情况,您可以将测试 function 更改为:
@pytest.mark.parametrize("k, cntxt", [(None, pytest.raises(ValueError)), ("Value", does_not_raise())])
def test_t(k, cntxt):
with cntxt as ex:
kk = t(k)
if k is None:
assert False
它不会失败。
您可能希望像这样将断言移出上下文管理器
@pytest.mark.parametrize("k, cntxt", [(None, pytest.raises(ValueError)), ("Value", does_not_raise())])
def test_t(k, cntxt):
with cntxt as ex:
kk = t(k)
if k:
print("one")
assert kk == k
assert ex is None
else:
print("two")
# Can't do this as kk was never assigned to anything
# assert kk is None
assert str(ex.value) == "Value"
$ pytest -s myfile.py
...
two
.
one
.
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.