2

I have a mock that works fine as expected.

from mock import patch

def second(arg):
    return 3


def first():
    return second('arg')


@patch('test.second')
def test_test(second_mock):
    second_mock.return_value = 47  # We decide this

    call_it = first()

    second_mock.assert_called_once()
    second_mock.assert_called_with('arg')

    assert call_it == 47

But not if i move me second() method to another file...

from mock import patch
from test_help import second


def first():
    return second('arg')


@patch('test_help.second')
def test_test(second_mock):
    second_mock.return_value = 47  # We decide this

    call_it = first()

    second_mock.assert_called_once()
    second_mock.assert_called_with('arg')

    assert call_it == 47

I get the same error: AssertionError: Expected 'second' to have been called once. Called 0 times.

What am I missing here?

I have tried a few different ways of formatting, but none seem to work. Is this even the best practice/package in this case for unit testing?

doedotdev
  • 555
  • 4
  • 17

1 Answers1

2

Don't worry, you're on right path, that is the way to mock functions.

And about your probem, remember that you patch the namespace according to function from where the mocked function is called.

So, when you in your module module_where_first_is_located make an import from test_help import second then second is recognized as module_where_first_is_located.second.

So instead of @patch('test_help.second') do @patch('module_of_first.second').

ipaleka
  • 3,745
  • 2
  • 13
  • 33
  • Thanks, this got me in the correct direction. Still ran into some silly things where I was mocking a function in another file that I wasn't directly calling in that file from the first file. So the flow was from main_file => new_file.function_one=> new_file.function_two, where the functionality of new_file.function_two was what I wanted to mock. So because in main_file I was just importing function_one, it had no context or ability to patch function_two. So changing up my imports to be import the entire new_file resolved that for now. – doedotdev Jul 08 '19 at 19:52
  • Well, contemporary editors and IDEs with their debuggers may help. When you step into function then you may inspect its variables and imports. – ipaleka Jul 08 '19 at 20:17