How to make fun of throwing an exception in python?
I have a code like this:
def extract(data):
if len(data) == 3:
a = 3
else:
component = data.split("-")
if len(component) == 3:
a,b,c = component
else:
raise globals.myException("data1", "Incorrect format", data)
return a,b,c
It's simplistic. I want to mock the globals.myException exception class. I'm doing it:
def test_extract_data_throws_exception(self):
with patch('globals.myException') as mock:
mock.__init__("data1", "Incorrect format", "")
with self.assertRaises(myException):
self.assertEqual(extract(""), (""))
And I always get the error: "TypeError: Exceptions must be old style classes or derived from BaseException, not MagicMock"
EDIT . As @Aaron Digulla points out, fixing the monkeys is the right solution. I am posting a solution to help others.
def test_extract_data_throws_exception(self):
#monkey patching
class ReplaceClass(myException):
def __init__(self, module, message, detail = u''):
pass
globals.myException = ReplaceClass
with self.assertRaises(myException:
self.assertEqual(extract(""), (""))
source to share
The reason is raise
checking the type of the argument. It must be a string (aka "old style exceptions") or derived fromBaseException
Since the layout also does not exist, raise
refuses to use it.
In this particular case, you need to either make an exception or use a monkey patch (= overwrite the symbol globals.myException
in your test and restore it afterwards).
source to share