如何在pytest中断言ValueError

时间:2016-06-16 22:47:32

标签: python unit-testing 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')

我如何测试格式错误的时间戳?为此写出最好的单元测试是什么?

1 个答案:

答案 0 :(得分:2)

运行预期会在with块中引发异常的代码,如:

with pytest.raises(ValueError):
    # code

有关详细信息和选项,请阅读https://pytest.org/latest/assert.html