如何在 Python 2.7 - 3.5 测试期间忽略 DeprecationWarning?

How to ignore DeprecationWarning during testing in Pythons 2.7 - 3.5?

在 3.5 中 DeprecationWarning 明确设置为在测试期间显示。

我的软件包适用于 2.7 - 3.5,并使用 2.7 - 3.4 中存在但在 3.5 中已弃用的功能。使用替换方法会很痛苦,因为它在 3.5 之前不存在,而且多年来(最早 2020 年)都不会出现。

如何让 DeprecationWarning 在 3.5 测试期间静音?

我试过设置 PYTHONWARNINGwarnings.filterwarning、在 __init__ 中用 warnings.filterwarnings 创建自己的 TestCase,但都无济于事。

setUpClass 是在 2.7 和 3.2 中添加的,在 3.1 和 2.6- 中应该被忽略。所以最好的选择是创建自己的 unittest.TestCase 子类并将 warnings.filterwarnings 代码添加到 setUpClass 函数*。

*不要忘记在 setUpClass 上使用 classmethod 装饰器。