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... )
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With