maya
maya

Reputation: 81

Mocking a function in a function

I am trying to mock a couple of function calls in a function so I can test their behaviour.

I have tried a couple of different approaches, shown in the code, but it should_be_mocked function never gets mocked. I use python3, PyCharm, the test framework is set to pytest

test.py

from unittest import mock, TestCase
from unittest.mock import patch

from path import should_be_mocked
from other_path import flow


def test_flow(monkeypatch):
    def ret_val():
        return should_be_mocked("hi")

    monkeypatch.setattr('path', "should_be_mocked", ret_val())

    assert flow() == "hi"


def test_flow2(monkeypatch):
    monkeypatch.setattr('path.should_be_mocked', lambda x: "hi")
    assert flow() == "hi"


@patch('path.should_be_mocked')
def test_flow3(mocker):
    mocker.return_value = "hello returned"
    flow()
    mocker.test.assert_called_with("hello")


class TestStuff(TestCase):
    @patch('path.should_be_mocked')
    def test_flow4(self, mocker):
        mocker.return_value = "hello returned"
        flow()
        mocker.test.assert_called_with("hello")

path

def should_be_mocked(hello):
    return hello

other_path

def flow():
    # business logic here
    return should_be_mocked("hello")

All the tests fail and return the value from the real function. Where did I go wrong?

Added info.

Trying to change the path to other_path results in

E       AttributeError: 'other_path' has no attribute 'should_be_mocked'

Upvotes: 2

Views: 295

Answers (1)

maya
maya

Reputation: 81

I am answering my own question here. Thanks to @hoefling I found out that the path was misstaken. But I could not get the first testcase running. The other ones worked after reworking them like this.

def test_flow2(monkeypatch):
    monkeypatch.setattr('other_path', lambda x: "hi")
    assert flow() == "hi"


@patch('other_path.should_be_mocked')
def test_flow3(mocker):
    flow()
    mocker.assert_called_with("hello")


class TestStuff(TestCase):
    @patch('other_path.should_be_mocked')
    def test_flow4(self, mocker):
        flow()
        mocker.assert_called_with("hello")

The first did not work, the second worked after changing the path. The 3rd and 4th needed the .test removed from the assert statement

Upvotes: 2

Related Questions