Skip to main content
 首页 » 编程设计

python之如何在 pytest 中断言 ValueError

2025年05月04日26xxx_UU

我正在为以下函数编写 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 block 中引发异常的代码,例如:

with pytest.raises(ValueError): 
    # code 

有关详细信息和选项,请阅读 https://pytest.org/en/latest/getting-started.html#assert-that-a-certain-exception-is-raised .