gpt4 book ai didi

python - 计算 Python 2.4 中的警告

转载 作者:太空狗 更新时间:2023-10-30 00:47:00 26 4
gpt4 key购买 nike

我有一些测试需要计算函数引发的警告数量。在 Python 2.6 中这很简单,使用

with warnings.catch_warnings(record=True) as warn:
...
self.assertEquals(len(warn), 2)

不幸的是,with 在 Python 2.4 中不可用,那么我还能使用什么?我不能简单地检查是否有一个警告(使用带有 action='error'try/catch 的警告过滤器),因为警告的数量很大。

最佳答案

我打算建议与 Ignacio 相同的解决方法,一个更完整的测试代码示例:

import warnings

def setup_warning_catcher():
""" Wrap warnings.showwarning with code that records warnings. """


caught_warnings = []
original_showwarning = warnings.showwarning

def custom_showwarning(*args, **kwargs):
caught_warnings.append(args[0])
return original_showwarning(*args, **kwargs)

warnings.showwarning = custom_showwarning
return caught_warnings


caught_warnings_list = setup_warning_catcher()

# trigger warning here

assert len(caught_warnings_list) == 1

关于python - 计算 Python 2.4 中的警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2324820/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com