如何在 pytest 中断言 ValueError
How to assert ValueError in pytest
我正在为以下函数编写 pytest 单元测试
from datetime import datetime
def validate_timestamp(timestamp):
"""Confirm that the passed in string is in the proper format %Y%m%d_%H"""
try:
ts = datetime.strptime(str(timestamp),'%Y%m%d_%H')
except:
raise ValueError("{0} must be in the format `%Y%m%d_%H".format(timestamp))
return datetime.strftime(ts,'%Y%m%d_%H')
如何测试格式错误的时间戳?为此编写的最佳单元测试是什么?
运行 预计会在 with
块中引发异常的代码,例如:
with pytest.raises(ValueError):
# code
有关详细信息和选项,请阅读 https://pytest.org/en/latest/getting-started.html#assert-that-a-certain-exception-is-raised。
从 Python 3.1 开始,您可以使用 match 参数来匹配调用堆栈中的整个字符串或子字符串。
from datetime import datetime
def validate_timestamp(timestamp):
"""Confirm that the passed in string is in the proper format %Y%m%d_%H"""
try:
ts = datetime.strptime(str(timestamp),'%Y%m%d_%H')
except:
raise ValueError("{0} must be in the format `%Y%m%d_%H".format(timestamp))
return datetime.strftime(ts,'%Y%m%d_%H')
def test_bad_timestamp_fails():
with pytest.raises(ValueError, match=r"foobar must be in the format `%Y%m%d_%H"):
validate_timestamp("foobar")
我正在为以下函数编写 pytest 单元测试
from datetime import datetime
def validate_timestamp(timestamp):
"""Confirm that the passed in string is in the proper format %Y%m%d_%H"""
try:
ts = datetime.strptime(str(timestamp),'%Y%m%d_%H')
except:
raise ValueError("{0} must be in the format `%Y%m%d_%H".format(timestamp))
return datetime.strftime(ts,'%Y%m%d_%H')
如何测试格式错误的时间戳?为此编写的最佳单元测试是什么?
运行 预计会在 with
块中引发异常的代码,例如:
with pytest.raises(ValueError):
# code
有关详细信息和选项,请阅读 https://pytest.org/en/latest/getting-started.html#assert-that-a-certain-exception-is-raised。
从 Python 3.1 开始,您可以使用 match 参数来匹配调用堆栈中的整个字符串或子字符串。
from datetime import datetime
def validate_timestamp(timestamp):
"""Confirm that the passed in string is in the proper format %Y%m%d_%H"""
try:
ts = datetime.strptime(str(timestamp),'%Y%m%d_%H')
except:
raise ValueError("{0} must be in the format `%Y%m%d_%H".format(timestamp))
return datetime.strftime(ts,'%Y%m%d_%H')
def test_bad_timestamp_fails():
with pytest.raises(ValueError, match=r"foobar must be in the format `%Y%m%d_%H"):
validate_timestamp("foobar")