Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customize AssertionError in Python

Tags:

python

assert

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()
like image 652
Helga Avatar asked Apr 08 '26 21:04

Helga


2 Answers

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
like image 195
Noctis Skytower Avatar answered Apr 10 '26 11:04

Noctis Skytower


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)
like image 26
Morgan Thrapp Avatar answered Apr 10 '26 10:04

Morgan Thrapp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!