Permalink
Browse files

Preliminary support for .get() and exceptions

  • Loading branch information...
1 parent 95219f3 commit e711b0b3adde7a5000f0ef375d0fc9c57d2f17b6 @dcramer committed Feb 7, 2012
Showing with 39 additions and 0 deletions.
  1. +19 −0 mock_django/managers.py
  2. +20 −0 tests/mock_django/managers/tests.py
View
@@ -62,7 +62,26 @@ def ManagerMock(manager, *return_value):
>>> assert objects.filter() == objects.all()
"""
+ def make_get(self):
+ def _get(*a, **k):
+ results = list(self)
+ if len(results) > 1:
+ raise self.model.MultipleObjectsReturned
+ try:
+ return results[0]
+ except IndexError:
+ raise self.model.DoesNotExist
+ return _get
+
+ model = getattr(manager, 'model', None)
+ if model:
+ model = mock.MagicMock(spec=manager.model())
+ else:
+ model = mock.MagicMock()
+
m = _ManagerMock()
+ m.model = model
+ m.get = make_get(m)
m.__iter__.side_effect = lambda *a, **k: iter(return_value)
m.__getitem__ = lambda s, n: list(s)[n]
return m
@@ -27,6 +27,26 @@ def test_returns_self(self):
self.assertEquals(inst.all(), inst)
+ def test_get_on_singular_list(self):
+ manager = make_manager()
+ inst = ManagerMock(manager, 'foo')
+
+ self.assertEquals(inst.get(), 'foo')
+
+ def test_get_on_multiple_objects(self):
+ manager = make_manager()
+ inst = ManagerMock(manager, 'foo', 'bar')
+ inst.model.MultipleObjectsReturned = Exception
+
+ self.assertRaises(inst.model.MultipleObjectsReturned, inst.get)
+
+ def test_get_raises_doesnotexist(self):
+ manager = make_manager()
+ inst = ManagerMock(manager)
+ inst.model.DoesNotExist = Exception
+
+ self.assertRaises(inst.model.DoesNotExist, inst.get)
+
def test_call_tracking(self):
# only works in >= mock 0.8
manager = make_manager()

0 comments on commit e711b0b

Please sign in to comment.