简体   繁体   English

在Python中自定义AssertionError

[英]Customize AssertionError in Python

I'm trying to add some text for all assertion errors in my code. 我正在尝试为我的代码中的所有断言错误添加一些文本。

This is my code: 这是我的代码:

class AssertionError(Exception):
    def __init__(self, msg):
        Exception.__init__(self, msg)
        self.message = msg + "+ SOME TEXT"

assert 1 == 2, "FAIL"

Result is 结果是

__main__.AssertionError: FAIL

I expected to see result: "FAIL + SOME TEXT" 我期待看到结果:“FAIL + SOME TEXT”


Problem is with unittest also. 问题也在于单元测试。 I want add some text for all failed tests (Without updating all text message). 我想为所有失败的测试添加一些文本(不更新所有文本消息)。

import unittest

class TestCase(unittest.TestCase):
    def test1(self):
        self.assertTrue(False, "FAIL!")

    def test2(self):
        self.assertLessEqual(10, 2, "FAIL!")

if __name__ == "__main__":
    unittest.main()

This is similar to Morgan's answer but uses a slightly different way to accomplish the same result: 这与Morgan的答案类似,但使用稍微不同的方法来实现相同的结果:

>>> class AssertionError(AssertionError):
    def __init__(self, msg):
        super().__init__(msg + ' SOME TEXT')

>>> assert 1 == 2, 'FAIL'
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    assert 1 == 2, 'FAIL'
AssertionError: FAIL SOME TEXT

The issue is that you're not doing anything with self.message = msg + "+ SOME TEXT" . 问题是你没有用self.message = msg + "+ SOME TEXT"做任何事情。 You have to pass the custom message you want to Exception.__init__ . 您必须将您想要的自定义消息传递给Exception.__init__

This will work for you: 这对你有用:

class AssertionError(Exception):
    def __init__(self, msg):
        self.message = msg + " SOME TEXT"
        super().__init__(self, self.message)
assert 1 == 2, "FAIL"

If you want to view the message in the future, you can use a try/except and catch the custom message like this: 如果您希望以后查看该消息,可以使用try / except并捕获自定义消息,如下所示:

try:
    assert 1 == 2, "FAIL"
except AssertionError as e:
    print(e.message)

This variant keeps the exception exactly as it was raised and modifies its string representation only: 此变体保留与引发时完全相同的异常,并仅修改其字符串表示形式:

class AssertionError(AssertionError):
    def __str__(self):
        return super().__str__() + "SOME TEXT"

(credit: subclassing taken from Noctis' answer) (信用:从Noctis的回答中获取的子类)

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

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