简体   繁体   中英

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"


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:

>>> 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" . You have to pass the custom message you want to 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:
    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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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