[TIP] Mocking a cursor for use with Psycopg2
pjs482 at gmail.com
Fri Mar 14 08:25:47 PDT 2014
If I understand correctly, what you want is a mock object that is iterable.
You can accomplish this using a MagicMock and setting the return value for
`__iter__`. For example:
from mock import MagicMock
cur = MagicMock()
cur.__iter__.return_value = ['result 1', 'result 2']
Now, in your code under test, you can use the mock object to record the
function call and also iterate over the results:
cur.execute('SELECT * FROM test;')
for record in cur:
This code will print:
And you can still make any desired assertions about the recorded calls:
cur.execute.assert_called_once_with('SELECT * FROM test;')
Hope this helps,
On Thu, Mar 13, 2014 at 12:29 PM, Alexander Bandukwala <7h3kk1d at gmail.com>wrote:
> I'm trying to mock access to my postgres database using the mock
> framework. I saw the cursor example here<http://mock.readthedocs.org/en/latest/getting-started.html?highlight=cursor#setting-return-values-and-attributes>.
> The psycopg2 cursor however does not return the data set but is iterated
> over example here <http://initd.org/psycopg/docs/cursor.html> under
> result retrieval methods. What would be the best way to mock a cursor which
> can be called with a function but also be iterated over.
> Thanks for any assistance and sorry for the inexperienced question.
> Alexander Bandukwala
> Twitter: http://twitter.com/abanduk
> Site: http://bandukwala.me
> testing-in-python mailing list
> testing-in-python at lists.idyll.org
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the testing-in-python