0

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.

1 Answer 1

1

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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.