简体   繁体   中英

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?

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.

eg @patch('someDir.other_mod._call_to_s3')

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM