Charitoo
Charitoo

Reputation: 1872

Determining the target for unittest.mock.patch

I am writing a some tests for a library I've been developing. It has the following structure.

lib
|---__init__.py
|---mod1.py
|---mod2.py
|---mod3.py
tests
|---__init__.py
|---test_mod1.py

In init.py of tests folder, I added the path of the library to the sys.path variable and them made all the imports. i.e. from lib import mod1, mod2, mod3. In test_mod1.py I did from . import mod1

The problem now is that I want to patch a function in mod1.py. I tried mock.patch('mod1.func1') but that didn't work then I tried mock.patch('.mod1.func1') that too is not working. How do I determine the target for the patch?

Upvotes: 5

Views: 1804

Answers (1)

Simeon Visser
Simeon Visser

Reputation: 122376

You should specify where the function that you want to mock is located.

In this case, if func1 is the following in lib.mod1:

def func1(a, b):
    return a + b

then the following should work:

@mock.patch('lib.mod1.func1', mock.Mock(return_value=3))
def test_mod1():
    result = mod1.func1(100, 200)
    assert result == 3  # not 300 because we mocked it

You could also implement it as follows:

@mock.patch('lib.mod1.func1')
def test_mod1(mocked_func1):
    mocked_func1.return_value = 3
    result = mod1.func1(100, 200)
    assert result == 3  # not 300 because we mocked it

Upvotes: 2

Related Questions