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

Discussão em 'Python' iniciado por Stack, Maio 14, 2025.

  1. Stack

    Stack Membro Participativo

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

    Continue reading...

Compartilhe esta Página