[TIP] Mocking a cursor for use with Psycopg2
Patrick Smith
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:
print record
This code will print:
result 1
result 2
And you can still make any desired assertions about the recorded calls:
cur.execute.assert_called_once_with('SELECT * FROM test;')
Hope this helps,
Patrick Smith
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
> 337-335-0133
> Twitter: http://twitter.com/abanduk
> Site: http://bandukwala.me
>
>
> _______________________________________________
> testing-in-python mailing list
> testing-in-python at lists.idyll.org
> http://lists.idyll.org/listinfo/testing-in-python
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.idyll.org/pipermail/testing-in-python/attachments/20140314/45e18ee8/attachment.htm>
More information about the testing-in-python
mailing list