Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock function call inside init method Python

I'm writing a unit test to make sure my class object is created correctly, and this object relies on getting contents from s3. I want to mock out the function that calls s3 inside it completely,:

class SomeClassTest(unittest.TestCase):

    @patch('someDir.util._call_to_s3')
    def test_someclass_load(self, magic_mock):
        magic_mock.return_value = {"host": "bogus.com"}
        some_class = SomeClass()

        self.assertGreater(len(some_class), 0)

class SomeClass():

    def __init__():
        try:
            content = _call_to_s3(bucket_name, file_name)
        except:
            rest of code ...

How do I mock out the function _call_to_s3 which is defined in another library file?

like image 649
robinhood91 Avatar asked Sep 14 '25 06:09

robinhood91


1 Answers

When you monkeypatch, you're changing a name so that it points at a different value. You're not changing the value itself. The key is to patch the name that's being used by the unit you are testing.

Every time you do "from foo import bar", you're creating a new, local copy of a name. In this case, it looks like SomeClass is not in the someDir.util module. Let's say it's in someDir.other_mod

someDir.other_mod would be doing something like "from someDir.util import _call_to_s3". This creates a new name someDir.other_mod._call_to_s3. That's the name that SomeClass uses, so that's the name that you need to patch.

e.g. @patch('someDir.other_mod._call_to_s3')

There is no way to patch every name that points at a particular value.

like image 124
Aaron Bentley Avatar answered Sep 16 '25 21:09

Aaron Bentley