1

Here is my project structure

|-- project
    |-- util.py
    |-- main.py
    |-- tests
        |-- test_main.py

In the main.py file I reference the function in util.py

from util import rename

def use_rename():
    after_rename = rename("name")
    return after_rename

And this is how I implement the rename function in util.py

def rename(name: str) -> str:
    return name

Finally I test it in the test_main.py file

import sys
import os
from unittest.mock import patch

sys.path.append(os.path.join(os.path.dirname(__file__), ".."))

from main import use_rename

@patch("util.rename")
def test_use_rename(mock_rename):
    mock_rename.return_value = "name2"
    assert use_rename() == "name"

As you can see I try to mock the return result of the rename function and assume the test should fail, but it always succeeds. Is there anything wrong with my code?

1 Answer 1

0

There is only one error in your code: you mock the function rename in the module util where it is defined, but you have to mock the object util imported in the main.py module by the instruction:

from util import rename

So you need to do only a change in test_main.py:

import sys
import os
from unittest.mock import patch

sys.path.append(os.path.join(os.path.dirname(__file__), ".."))

from main import use_rename

#@patch("util.rename")    # <--- comment this decorator
@patch("main.rename")     # <--- add this decorator
def test_use_rename(mock_rename):
    mock_rename.return_value = "name2"
    assert use_rename() == "name"

With this change the output of the execution is:

...
    assert use_rename() == "name"
AssertionError
1
  • @hh54188 A feedback would be appreciated.
    – User051209
    Commented Jul 10 at 9:07

Not the answer you're looking for? Browse other questions tagged or ask your own question.