简体   繁体   English

等待Python警告并引发异常

[英]Wait for Python warnings and raise Exception

I have a Python test that possibly generates many warnings. 我有一个Python测试,可能会生成许多警告。 When the test finishes, I want it to raise an exception if there were any warnings. 测试完成后,如果有任何警告,我希望它引发异常。

It is important to run the test to the end and then raise, because I am using a remote build bot and want to see all warnings at once. 将测试进行到最后再进行测试很重要,因为我使用的是远程构建机器人,并且希望一次查看所有警告。

How do I do that? 我怎么做?

I asked that yesterday but found the answer later, alone. 我昨天问过,但后来一个人找到了答案。 The technique is interesting and I want to share it. 该技术很有趣,我想分享一下。

When a module creates warnings with the warnings module, it stores these warnings in a special variable that holds the seen warnings. 当模块使用警告模块创建警告时,它将这些警告存储在一个特殊变量中,该变量保存看到的警告。 So in my case, the parser module issues warnings. 因此,就我而言,解析器模块会发出警告。 I simply let it do its usual job, and at the end of the test comes: 我只是让它完成其通常的工作,然后在测试结束时出现:

if hasattr(parser, "__warningregistry__"):
    raise RuntimeError("There are errors, see above.")

This way, I don't have to modify my parser in any way, but at the end of the run, I get an exception, and I have all warnings available. 这样,我不必以任何方式修改解析器,但是在运行结束时,我遇到了异常,并且所有警告均可用。 Then I can fix all cases and start another run of the build bot. 然后,我可以修复所有情况并开始运行另一次构建机器人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM