jpaodev
jpaodev

Reputation: 136

Python unittest mocking problems (Global variable)

After checking at least 20 stackoverflow posts, I decided I'd share my problem here, maybe somebody can help me out.

It's quite simple, I am trying to mock a Database (to connect to another DB in the test), so I use unittest.mock.patch

self.mocks = [
            "api.database.database.db",
            "api.utils.checker.Checker.check_db_reachability"
        ]
        self.mocks = [patch(mocked_func, return_value=self.db) for mocked_func in self.mocks]

After running (Console Output I printed after starting the mocks) the db import does not get mocked, however the class method I mocked the same way, got changed into a magic mock, if called.

dbtest_1     | DEBUG:test.postgres.test_crud:Changed DB:
dbtest_1     | DEBUG:test.postgres.test_crud:<databases.core.Database object at 0x7f7465e6c040>
dbtest_1     | DEBUG:test.postgres.test_crud:Changed Checker:
dbtest_1     | DEBUG:test.postgres.test_crud:<MagicMock name='check_db_reachability' id='140137474713264'>

Does somebody know what I'm doing wrong? The expected output would be, that the databases.core.Database object also gets mocked.

Upvotes: 0

Views: 285

Answers (1)

jpaodev
jpaodev

Reputation: 136

Found the answer myself - sharing it here, might help people who face the same out.

The problem was:

  1. I was importing a variable / function from another module (file), which wasn't contained in a class or something similar
  2. The problem was, I was patching the wrong location (the location where the object was defined (e.g. db = Database()) - however: You have to patch the location, where the object / variable is being imported!

Read more about the topic here: https://docs.python.org/3/library/unittest.mock.html#where-to-patch

I hope I can save you some time, I wish I found out sooner. Peace!

Upvotes: 1

Related Questions