Reputation: 113
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()
Upvotes: 3
Views: 2379
Reputation: 17237
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)
Upvotes: 1
Reputation: 9986
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)
Upvotes: 1
Reputation: 21991
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
Upvotes: 3