How to mock using patch relative paths?

I used Dan Passaro’s solution till I came across this one using patch.object – which looks even better to me:

from unittest.mock import patch,
from .. import monkey
[...]
@patch.object(monkey, 'ook', Mock(return_value=None))
def test_run_ook (self, mock_ook):
    self.assertIsNone(monkey.ook())
    mock_ook.run.assert_called_once_with('')

Advantages:

  • No need for the boilerplate code that is __name__ + '.object_to_be_mocked'
  • All dependencies of the test case are clearly stated at the beginning of the file as import statements.
  • In cases where the dotted name of the object you’re trying to mock out is longer (say “amazon.jungle.monkey.ook”) and you therefore write @patch.object(amazon.jungle.monkey, 'ook', …), your IDE’s static code analysis can make sure that at least amazon.jungle.monkey is a valid variable since you didn’t write the whole thing as a string 'amazon.jungle.monkey.ook'.

Disadvantages:

  • You cannot do from ..monkey import ook but need to do from .. import monkey and access ook through monkey, i.e. monkey.ook. In cases where I need to write this often I will add ook = monkey.ook to the beginning of my tests for convenience. (Or even to the import statements in case I never need to mock out this particular property of monkey.)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)