Home > Enterprise >  How to patch a module method that is called within a class?
How to patch a module method that is called within a class?

Time:04-02

I have the following structure:

# create.py
import sshHandler
class Create:
    def __init__(self):
        self.value = sshHandler.some_method()

# sshHandler.py
def some_method():
    return True

If I kow try to patch sshHandler.some_method it will not work as expected

from unittest import TestCase
from unittest.mock import patch
import create
class TestCreate(TestCase):
    @patch("sshHandler.some_method")
    def test_create(self, mock_ssh):
        mock_ssh.return_value = False
        c = create.Create()
        # c.value = True but should be false

The result I am looking for is that some_method would be patched in create as well (and return false). If I just call some_method in the context of test_create it works as expected. How do I fix the patch so that it is also active in the Create class when accessing sshHandler?

I saw this question Why python mock patch doesn't work?, but couldn't solve my problem with the information given there.

CodePudding user response:

You've patched the wrong module. Instead patch the sshHandler.some_method patch create.sshHandler.some_method. You must patch the object of module you're handling.

  • Related