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

PythonUnit TestingMocking

Python Problem Overview


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)

Python Solutions


Solution 1 - Python

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDowwieView Question on Stackoverflow
Solution 1 - PythonMartijn PietersView Answer on Stackoverflow