How to disable Python lock using c instruction?

Using Python 2.6.6

So, I just found out that the following:

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

can be replaced by:

 with myLock: doStuff() 

My quandry is that with the previous code, I could rule out that the lock was used to protect the work by mocking the Lock. But with the latter, my unittest now (presumably) fails because gets () and release () are not called. So, for the latter case, how can I verify that the lock is used to protect the work?

I prefer the second method because it is not only more concise, but there is no chance that I will write code that forgets to unlock the resource. (Not that I ever did this before ...)

+5
source share
1 answer

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

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

+6
source

All Articles