Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python's mock throwing AttributeError: 'module' object has no attribute 'patch'

I am trying to create some tests for a Python program. I am using Python version 2.7.12 so I had to install mock using sudo pip install mock.

According to the documentation and several other sites, I should be able to use the following code to use patch:

import mock     # Also could use from mock import patch
import unittest

class TestCases(unittest.TestCase):
    @mock.patch('MyClass.ImportedClass')   # If using from mock import patch should just be @patch
    def test_patches(self, mock_ImportedClass):
        # Test code...

However, the above code throws the following error:

AttributeError: 'module' object has no attribute 'patch'

After some experimenting in the terminal, it seems quite a few things don't work. For example

>>> import mock

>>> mock.MagicMock
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'MagicMock'

>>> mock.patch
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'patch'

>>> mock.Mock
<class mock.Mock at 0x7fdff56b0600>

Interestingly, I can access something called patch using mock.Mock(), but I don't know if this works in the same way and cannot find anything about it in the documentation.

My experience with Python is fairly limited so I'm not sure what might be wrong. I'm fairly certain the right package was installed. Any help on how I can get this working?

like image 902
c1moore Avatar asked Aug 17 '16 16:08

c1moore


Video Answer


1 Answers

Just for the sake of completeness, I wanted to add the answer, but the credit goes to @user2357112.

If you run into this issue check to make sure you don't have another file named mock.py (or whatever file you're trying to import) either in the same directory or in the search path for python. To confirm you've loaded the correct file, you can check mock.__file_, which is an attribute added automatically by python to your imported files. If you're using the terminal, you can just do something like:

>>> import mock

>>> mock.__file__
'/usr/lib/python2.7/...'

If the file path doesn't match what you expect, you should remove the file being imported from your search path or modify your search path so that the file you want is found first. If neither of those are an option, you need to change the name of the file you're importing (if it's one you define and not a library like mock).

like image 161
c1moore Avatar answered Oct 28 '22 00:10

c1moore