簡體   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