Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why mock.patch doesn't work while trying to mock a function

The structure of the project is

enter image description here

main.py

from src.tools.tool_a import fun


def main_fun():
    fun()

tools_a.py

def fun():
    raise Exception('')

test_fun.py

from unittest.mock import patch
from src.main import main_fun


@patch('src.tools.tool_a.fun')
def test_main_fun(fun):
    main_fun()

If I run pytest tests/test_fun.py I get an exception from method fun(). I already mocked it so do not understand what is the correct way of mocking it.

like image 656
user1298426 Avatar asked Jul 11 '26 19:07

user1298426


1 Answers

@jonrsharpe gave the correct answer in the comments, but so the solution is easier to find I'll post it here:

You patch where things are used, not where they're defined: docs.python.org/3/library/unittest.mock.html#where-to-patch

Therefore, the code should be:

from unittest.mock import patch
from src.main import main_fun


@patch('src.main.fun')
def test_main_fun(fun):
    main_fun()
like image 161
Shani Shalgi Avatar answered Jul 14 '26 09:07

Shani Shalgi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!