Dowwie
Dowwie

Reputation: 2043

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

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)

Upvotes: 123

Views: 46549

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124100

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.

Upvotes: 175

Related Questions