title: How to mock.patch MySQLdb.cursors?
body: <pre><code>class CanonDatabase:
      def __init__(self, clean_up_db=False):
          self.db = "tmg_canon_april_tokens"
          self.conn = create_connection(self.db)
          self.cur = self.conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)
  </code></pre>
  
  <p>I am trying to mock.patch MySQLdb in order to pass the constructor.</p>
  
  <pre><code>@mock.patch.object(MySQLdb, '__init__')
  class TestDatabase(unittest.TestCase):
      def setUp(self):
          super(TestDatabase, self).setUp()
          patch = mock.patch('atone_canon.Database.create_connection')
          mock_baz = patch.start()
          mock_baz.cursor.return_value = mock.MagicMock()
  
      def tearDown(self):
          super(TestDatabase, self).tearDown()
          mock.patch.stopall()
  
      def test_clean_table(self, mysql_mock):
          db = CanonDatabase()
          self.assertEqual(True, False)
  </code></pre>
  
  <p>However this fails with the following error message:</p>
  
  <blockquote>
  <pre><code>File "atone_canon/Database.py", line 20, in __init__ self.cur = self.conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)
  </code></pre>
    
    <p>AttributeError: 'module' object has no attribute 'cursors'</p>
  </blockquote>
  
  <p><strong>I found a way:</strong></p>
  
  <p>If I insert this import in my unit test, without (!) even using it:</p>
  
  <pre><code>from MySQLdb.cursors import DictCursor
  </code></pre>
  
  <p>Then I no longer get the error, and I won't even have to mock.patch the MySQLdb wrapper:</p>
  
  <pre><code># @mock.patch.object(MySQLdb, '__init__')
  class TestDatabase(unittest.TestCase):
     ...
  </code></pre>
  
  <p>Not too happy with the solution. Generally I have difficulties with mocking classes that live outside my project (e.g. live in the virtualenv). I leave this open, so hopefully someone can show me how to mock these kind of classes.</p>