Consider the following:
Class:
class Something(object):
def should_not_be_called(self):
pass
def should_be_called(self):
pass
def do_stuff(self):
self.should_be_called()
try:
self.should_not_be_called()
except Exception:
pass
Unit test:
class TestSomething(unittest.TestCase):
def test(self):
mocker = mox.Mox()
something = Something()
mocker.StubOutWithMock(something, 'should_be_called')
mocker.StubOutWithMock(something, 'should_not_be_called')
something.should_be_called()
mocker.ReplayAll()
something.do_stuff()
mocker.VerifyAll()
This test will pass (when it should clearly fail) as the try..except in do_stuff()
will except the UnexpectedMethodCallError
while the test runs...
Is there a way to get around this?
Edit: Another example that exemplifies why this is a problem a bit better:
class AnotherThing(object):
def more_stuff()(self, num):
if i == 2:
raise ValueError()
def do_stuff(self):
for i in [1, 2, 3, 'boo']:
try:
self.more_stuff(i)
except Exception:
logging.warn("an exception might have been thrown but code should continue")
class TestAnotherThing(unittest.TestCase):
def test(self):
mocker = mox.Mox()
another_thing = Something()
mocker.StubOutWithMock(something, 'fails_on_2')
mocker.StubOutWithMock(something, 'called_when_no_error')
another_thing.more_stuff(1)
# actual function calls more_stuff 2 more times, but test will still pass
another_thing.more_stuff('boo')
mocker.ReplayAll()
another_thing.do_stuff()
mocker.VerifyAll()