Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unittest Python Lock is acquired with 'with' statement?

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... )

like image 951
PfunnyGuy Avatar asked May 26 '16 13:05

PfunnyGuy


1 Answers

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.

like image 171
pppery Avatar answered Nov 02 '22 01:11

pppery