How do you mock a return value from PyMySQL for testing in Python?
<p>I'm trying to set up some tests for a script that will pull data from a MySQL database. I found an example <a href="https://github.com/chimpler/catdb/blob/master/tests/test_mysql.py" rel="nofollow">here</a> that looks like what I want to do, but it just gives me an object instead of results:</p>

<p><code>&lt;MagicMock name='pymysql.connect().cursor[38 chars]152'&gt;</code></p>

<p>Here is the function I am using (<code>simple.py</code>):</p>

<pre><code>import pymysql

def get_user_data():
    connection = pymysql.connect(host='localhost', user='user', password='password',
                                 db='db', charset='utf8mb4',
                                 cursorclass=pymysql.cursors.DictCursor)

    try:
        with connection.cursor() as cursor:
            sql = "SELECT `id`, `password` FROM `users`"
            cursor.execute(sql)
            results = cursor.fetchall()
    finally:
        connection.close()

    return results
</code></pre>

<p>And the test:</p>

<pre><code>from unittest import TestCase, mock
import simple

class TestSimple(TestCase):

    @mock.patch('simple.pymysql', autospec=True)
    def test_get-data(self, mock_pymysql):
        mock_cursor = mock.MagicMock()
        test_data = [{'password': 'secret', 'id': 1}]
        mock_cursor.fetchall.return_value = test_data
        mock_pymysql.connect.return_value.__enter__.return_value = mock_cursor

        self.assertEqual(test_data, simple.get_user_data())
</code></pre>

<p>The results:</p>

<pre><code>AssertionError: [{'id': 1, 'password': 'secret'}] != &lt;MagicMock name='pymysql.connect().cursor[38 chars]840'&gt;
</code></pre>

<p>I'm using Python 3.51</p>

<p>It looks like your mock is missing a reference to cursor</p>

<p><code>mock_pymysql.connect.return_value.cursor.return_value.__enter__.return_value = mock_cursor</code></p>

<p>I've always found mocking call syntax to be awkward but the MagicMock displays what's wrong in a roundabout way. It's saying it has no return value registered for <code>pymysql.connect.return_value.cursor</code></p>

<p><code>&lt;MagicMock name='pymysql.connect().cursor[38 chars]840'&gt;</code></p>

python unit-testing