0

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.

Natan
  • 728
  • 1
  • 7
  • 23
  • 1
    Isn't this `sshHandler` a class instead a method? – Mauro Baraldi Apr 01 '22 at 14:38
  • 1
    It is a python file that has some methods in it, but not a class. But I wrote it incorrectly above. You correctly spotted the mistake. I have corrected it. – Natan Apr 01 '22 at 14:49
  • Cannot reproduce. `self.assertFalse(c.value)` succeeds, as long as you fix `c = create.Create()`. – chepner Apr 01 '22 at 15:02
  • MauroBaraldi has given the correct answer. Therefore I am unsure why you can't reproduce it, @chepner I corrected the mistake you noticed above – Natan Apr 01 '22 at 15:11
  • 1
    If `create` had used `from sshHandler import some_method`, then it would be necessary to use `patch('create.some_method')` instead of `patch(sshHandler.some_method)`. As is, both `sshHandler` and `create.sshHandler` refer to the same thing, so it doesn't matter which name you use to patch `some_method`. – chepner Apr 01 '22 at 15:28
  • Thank you very much for this comment. Indeed the import had an old relic that I wasn't aware of anymore. The file sshHandler was in the folder handler and I imported it like `from handler import sshHandler` which I later changed because I figured out how to mark files as source in pycharm. Thanks to your explanation, I fixed the misleading import and now it works like you are describing without `create.` – Natan Apr 01 '22 at 16:14

1 Answers1

1

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.

Mauro Baraldi
  • 6,346
  • 2
  • 32
  • 43