Skip to content

Instantly share code, notes, and snippets.

@tarkatronic
Created April 8, 2015 21:17
Show Gist options
  • Save tarkatronic/b6d3f6036c13cd54d1a8 to your computer and use it in GitHub Desktop.
Save tarkatronic/b6d3f6036c13cd54d1a8 to your computer and use it in GitHub Desktop.
Mock Django database calls
"""
This is for a case where I was accessing the database connection/cursors directly,
and had need to mock up a result from a database call. The real trick here is
returning the cursor MagicMock object as a side effect of the initial patch.
"""
from unittest import mock
cursor = mock.MagicMock(
description=(('foo',), ('bar',)),
**{'fetchall.return_value': [('baz', 'frob')]}
)
with mock.patch('django.db.backends.utils.CursorWrapper', mock.MagicMock(side_effect=lambda x, y: cursor)):
# Insert test code here.
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment