Skip to content
This repository
tag: 0.6.3
Fetching contributors…

Cannot retrieve contributors at this time

file 48 lines (35 sloc) 1.142 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
"""
mock_django.managers
~~~~~~~~~~~~~~~~~~~~

:copyright: (c) 2012 DISQUS.
:license: Apache License 2.0, see LICENSE for more details.
"""

import mock
from .query import QuerySetMock
from .shared import SharedMock


__all__ = ('ManagerMock',)


def ManagerMock(manager, *return_value):
    """
Set the results to two items:

>>> objects = ManagerMock(Post.objects, 'queryset', 'result')
>>> assert objects.filter() == objects.all()

Force an exception:

>>> objects = ManagerMock(Post.objects, Exception())

See QuerySetMock for more about how this works.
"""

    def make_get_query_set(self, model):
        def _get(*a, **k):
            return QuerySetMock(model, *return_value)
        return _get

    actual_model = getattr(manager, 'model', None)
    if actual_model:
        model = mock.MagicMock(spec=actual_model())
    else:
        model = mock.MagicMock()

    m = SharedMock()
    m.model = model
    m.get_query_set = make_get_query_set(m, actual_model)
    m.get = m.get_query_set().get
    m.__iter__ = m.get_query_set().__iter__
    m.__getitem__ = m.get_query_set().__getitem__
    return m
Something went wrong with that request. Please try again.