mercredi 10 mars 2021

Magic Mock being returned instead of mocked value [PYTHON - UNITTEST]

Please take a look at the following modules I have, along with a simple test.

Im trying to mock the search_connection method in DbApi to return a value of 6. This value would then flow all the way back up to the control method. However when I print the output of the control method I get the following instead of 6

<MagicMock name='connections().search_one_connection'>   
from unittest import TestCase
from tests.unit.controller import control

class SampleTest(TestCase):
    def test_sample_method(self):
        connections_mock_patch = mock.patch("tests.unit.controller.connections")
        connections_mock = connections_mock_patch.start()
        connections_mock.return_value.db.search_connection.return_value = 6
        # control() returns a MagicMock object. control() should return 6
        assert control() == 6

controller.py

from tests.unit.a import connections

def control():
    return connections().search_connection()

a.py

from tests.integration.test_api import TestApi

def connections():
    return TestApi()

test_api.py

from tests.unit.db_api import DbApi

class TestApi:
    def __init__(self):
        self.db = DbApi()

    def search_connection(self):
        return self.db.search_connection()

db_api.py

class DbApi:
    def search_connection(self):
        return 5

Aucun commentaire:

Enregistrer un commentaire