7

Using Python 2.6.6

So I just learned that the following:

myLock.acquire()
doStuff()
myLock.release()

can be replaced with:

with myLock:
  doStuff()

My quandry is that with the former code I could unittest that the lock was being used to protect the doing-of-stuff by mocking out the Lock. But with the latter my unittest now (expectedly) fails, because acquire() and release() aren't being called. So for the latter case, how do I verify that the lock is used to protect the doing-of-stuff?

I prefer the second method because it is not only more concise, but there is no chance that I'll write code that forgets to unlock a resource. (Not that I've ever done that before... )

1 Answer 1

7

The with statement internally calls the __enter__ and __exit__ magic methods at the beginning and end (respectively). You can mock out these methods either by using a MagicMock or by explicitly setting mock.__enter__ = Mock();mock.__exit__ = Mock().

Setting magic methods this way only works for mocks; to override a magic method on a non-mock object, you have to set it on the type.

Not the answer you're looking for? Browse other questions tagged or ask your own question.