What is the difference between mock.patch.object(… and mock.patch(

Question:

I am trying to understand the difference between these two approaches of mocking a method. Could someone please help distinguish them? For this example, I use the passlib library.

from passlib.context import CryptContext
from unittest import mock

with mock.patch.object(CryptContext, 'verify', return_value=True) as foo1:
    mycc = CryptContext(schemes='bcrypt_sha256')
    mypass = mycc.encrypt('test')
    assert mycc.verify('tesssst', mypass)

with mock.patch('passlib.context.CryptContext.verify', return_value=True) as foo2:
    mycc = CryptContext(schemes='bcrypt_sha256')
    mypass = mycc.encrypt('test')
    assert mycc.verify('tesssst', mypass)
Asked By: Dowwie

||

Answers:

You already discovered the difference; mock.patch() takes a string which will be resolved to an object when applying the patch, mock.patch.object() takes a direct reference.

This means that mock.patch() doesn’t require that you import the object before patching, while mock.patch.object() does require that you import before patching.

The latter is then easier to use if you already have a reference to the object.

Answered By: Martijn Pieters
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.