繁体   English   中英

在Python中自定义AssertionError

[英]Customize AssertionError in Python

我正在尝试为我的代码中的所有断言错误添加一些文本。

这是我的代码:

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

assert 1 == 2, "FAIL"

结果是

__main__.AssertionError: FAIL

我期待看到结果:“FAIL + SOME TEXT”


问题也在于单元测试。 我想为所有失败的测试添加一些文本(不更新所有文本消息)。

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()

这与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

问题是你没有用self.message = msg + "+ SOME TEXT"做任何事情。 您必须将您想要的自定义消息传递给Exception.__init__

这对你有用:

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

如果您希望以后查看该消息,可以使用try / except并捕获自定义消息,如下所示:

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

此变体保留与引发时完全相同的异常,并仅修改其字符串表示形式:

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

(信用:从Noctis的回答中获取的子类)

暂无
暂无

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

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