├── .gitignore ├── .travis.yml ├── LICENSE ├── README.rst ├── mock_django ├── __init__.py ├── http.py ├── managers.py ├── models.py ├── query.py ├── shared.py └── signals.py ├── runtests.py ├── setup.py ├── tests ├── __init__.py ├── mock_django │ ├── __init__.py │ ├── http │ │ ├── __init__.py │ │ └── tests.py │ ├── managers │ │ ├── __init__.py │ │ └── tests.py │ ├── models │ │ ├── __init__.py │ │ └── tests.py │ ├── query │ │ ├── __init__.py │ │ └── tests.py │ └── signals │ │ ├── __init__.py │ │ └── tests.py └── requirements.txt └── tox.ini /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | *.egg 3 | *.egg-info/ 4 | *~ 5 | /dist 6 | /build 7 | .tox 8 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | python: 2.7 3 | env: 4 | 5 | - TOX_ENV=flake8 6 | 7 | - TOX_ENV=py34-django1.9 8 | - TOX_ENV=py34-django1.8 9 | - TOX_ENV=py34-django1.7 10 | - TOX_ENV=py34-django1.6 11 | - TOX_ENV=py34-django1.5 12 | 13 | - TOX_ENV=py33-django1.8 14 | - TOX_ENV=py33-django1.7 15 | - TOX_ENV=py33-django1.6 16 | - TOX_ENV=py33-django1.5 17 | 18 | - TOX_ENV=py32-django1.8 19 | - TOX_ENV=py32-django1.7 20 | - TOX_ENV=py32-django1.6 21 | - TOX_ENV=py32-django1.5 22 | 23 | - TOX_ENV=py27-django1.9 24 | - TOX_ENV=py27-django1.8 25 | - TOX_ENV=py27-django1.7 26 | - TOX_ENV=py27-django1.6 27 | - TOX_ENV=py27-django1.5 28 | - TOX_ENV=py27-django1.4 29 | 30 | - TOX_ENV=py26-django1.6 31 | - TOX_ENV=py26-django1.5 32 | - TOX_ENV=py26-django1.4 33 | 34 | - TOX_ENV=pypy-django1.9 35 | - TOX_ENV=pypy-django1.8 36 | - TOX_ENV=pypy-django1.7 37 | - TOX_ENV=pypy-django1.6 38 | - TOX_ENV=pypy-django1.5 39 | - TOX_ENV=pypy-django1.4 40 | 41 | - TOX_ENV=pypy3-django1.8 42 | - TOX_ENV=pypy3-django1.7 43 | - TOX_ENV=pypy3-django1.6 44 | - TOX_ENV=pypy3-django1.5 45 | 46 | install: 47 | - pip install tox 48 | script: 49 | - tox -e $TOX_ENV 50 | sudo: false 51 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2012 DISQUS 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | mock-django 2 | ~~~~~~~~~~~ 3 | 4 | A simple library for mocking certain Django behavior, such as the ORM. 5 | 6 | Using mock-django objects 7 | ------------------------- 8 | Inside your virtualenv: 9 | 10 | .. code:: python 11 | 12 | >>> from django.conf import settings 13 | >>> settings.configure() # required to convince Django it's properly configured 14 | >>> from mock_django.query import QuerySetMock 15 | >>> class Post(object): pass 16 | ... 17 | >>> qs = QuerySetMock(Post, 1, 2, 3) 18 | >>> list(qs.all()) 19 | [1, 2, 3] 20 | >>> qs.count() 21 | 3 22 | >>> list(qs.all().filter()) 23 | [1, 2, 3] 24 | 25 | See tests for more examples. 26 | 27 | 28 | Testing 29 | ------- 30 | 31 | .. image:: https://secure.travis-ci.org/dcramer/mock-django.png 32 | :alt: Build Status 33 | :target: http://travis-ci.org/dcramer/mock-django 34 | 35 | ``tox`` 36 | -------------------------------------------------------------------------------- /mock_django/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | mock_django 3 | ~~~~~~~~~~~ 4 | 5 | :copyright: (c) 2012 DISQUS. 6 | :license: Apache License 2.0, see LICENSE for more details. 7 | """ 8 | 9 | from .http import * 10 | from .managers import * 11 | from .models import * 12 | from .signals import * 13 | -------------------------------------------------------------------------------- /mock_django/http.py: -------------------------------------------------------------------------------- 1 | """ 2 | mock_django.http 3 | ~~~~~~~~~~~~~~~~ 4 | 5 | :copyright: (c) 2012 DISQUS. 6 | :license: Apache License 2.0, see LICENSE for more details. 7 | """ 8 | 9 | from django.contrib.auth.models import AnonymousUser 10 | from django.http import HttpRequest 11 | try: 12 | # Python 2 13 | from urllib import urlencode 14 | except ImportError: 15 | # Python 3 16 | from urllib.parse import urlencode 17 | 18 | __all__ = ('MockHttpRequest',) 19 | 20 | 21 | class WsgiHttpRequest(HttpRequest): 22 | def __init__(self, *args, **kwargs): 23 | super(WsgiHttpRequest, self).__init__(*args, **kwargs) 24 | self.user = AnonymousUser() 25 | self.session = {} 26 | self.META = {} 27 | self.GET = {} 28 | self.POST = {} 29 | 30 | def _get_request(self): 31 | from django.utils.datastructures import MergeDict 32 | if not hasattr(self, '_request'): 33 | self._request = MergeDict(self.POST, self.GET) 34 | return self._request 35 | REQUEST = property(_get_request) 36 | 37 | def _get_raw_post_data(self): 38 | if not hasattr(self, '_raw_post_data'): 39 | self._raw_post_data = urlencode(self.POST) 40 | return self._raw_post_data 41 | 42 | def _set_raw_post_data(self, data): 43 | self._raw_post_data = data 44 | self.POST = {} 45 | raw_post_data = property(_get_raw_post_data, _set_raw_post_data) 46 | 47 | 48 | def MockHttpRequest(path='/', method='GET', GET=None, POST=None, META=None, user=None): 49 | if GET is None: 50 | GET = {} 51 | if POST is None: 52 | POST = {} 53 | else: 54 | method = 'POST' 55 | if META is None: 56 | META = { 57 | 'REMOTE_ADDR': '127.0.0.1', 58 | 'SERVER_PORT': '8000', 59 | 'HTTP_REFERER': '', 60 | 'SERVER_NAME': 'testserver', 61 | } 62 | if user is None: 63 | user = AnonymousUser() 64 | 65 | request = WsgiHttpRequest() 66 | request.path = request.path_info = path 67 | request.method = method 68 | request.META = META 69 | request.GET = GET 70 | request.POST = POST 71 | request.user = user 72 | return request 73 | -------------------------------------------------------------------------------- /mock_django/managers.py: -------------------------------------------------------------------------------- 1 | """ 2 | mock_django.managers 3 | ~~~~~~~~~~~~~~~~~~~~ 4 | 5 | :copyright: (c) 2012 DISQUS. 6 | :license: Apache License 2.0, see LICENSE for more details. 7 | """ 8 | 9 | import mock 10 | from .query import QuerySetMock 11 | from .shared import SharedMock 12 | 13 | 14 | __all__ = ('ManagerMock',) 15 | 16 | 17 | def ManagerMock(manager, *return_value): 18 | """ 19 | Set the results to two items: 20 | 21 | >>> objects = ManagerMock(Post.objects, 'queryset', 'result') 22 | >>> assert objects.filter() == objects.all() 23 | 24 | Force an exception: 25 | 26 | >>> objects = ManagerMock(Post.objects, Exception()) 27 | 28 | See QuerySetMock for more about how this works. 29 | """ 30 | 31 | def make_get_query_set(self, model): 32 | def _get(*a, **k): 33 | return QuerySetMock(model, *return_value) 34 | return _get 35 | 36 | actual_model = getattr(manager, 'model', None) 37 | if actual_model: 38 | model = mock.MagicMock(spec=actual_model()) 39 | else: 40 | model = mock.MagicMock() 41 | 42 | m = SharedMock() 43 | m.model = model 44 | m.get_query_set = make_get_query_set(m, actual_model) 45 | m.get = m.get_query_set().get 46 | m.count = m.get_query_set().count 47 | m.exists = m.get_query_set().exists 48 | m.__iter__ = m.get_query_set().__iter__ 49 | m.__getitem__ = m.get_query_set().__getitem__ 50 | return m 51 | -------------------------------------------------------------------------------- /mock_django/models.py: -------------------------------------------------------------------------------- 1 | """ 2 | mock_django.models 3 | ~~~~~~~~~~~~~~~~~~ 4 | 5 | :copyright: (c) 2012 DISQUS. 6 | :license: Apache License 2.0, see LICENSE for more details. 7 | """ 8 | 9 | import mock 10 | 11 | __all__ = ('ModelMock',) 12 | 13 | 14 | # TODO: make foreignkey_id == foreignkey.id 15 | class _ModelMock(mock.MagicMock): 16 | def __init__(self, *args, **kwargs): 17 | super(_ModelMock, self).__init__(*args, **kwargs) 18 | 19 | # Django ORM needed state for write status 20 | self._state = mock.Mock() 21 | self._state.db = None 22 | 23 | def _get_child_mock(self, **kwargs): 24 | name = kwargs.get('name', '') 25 | if name == 'pk': 26 | return self.id 27 | return super(_ModelMock, self)._get_child_mock(**kwargs) 28 | 29 | 30 | def ModelMock(model): 31 | """ 32 | >>> Post = ModelMock(Post) 33 | >>> assert post.pk == post.id 34 | """ 35 | return _ModelMock(spec=model()) 36 | -------------------------------------------------------------------------------- /mock_django/query.py: -------------------------------------------------------------------------------- 1 | """ 2 | mock_django.query 3 | ~~~~~~~~~~~~~~~~~ 4 | 5 | :copyright: (c) 2012 DISQUS. 6 | :license: Apache License 2.0, see LICENSE for more details. 7 | """ 8 | import copy 9 | 10 | import mock 11 | from .shared import SharedMock 12 | 13 | __all__ = ('QuerySetMock',) 14 | 15 | QUERYSET_RETURNING_METHODS = ['filter', 'exclude', 'order_by', 'reverse', 16 | 'distinct', 'none', 'all', 'select_related', 17 | 'prefetch_related', 'defer', 'only', 'using', 18 | 'select_for_update'] 19 | 20 | 21 | def QuerySetMock(model, *return_value): 22 | """ 23 | Get a SharedMock that returns self for most attributes and a new copy of 24 | itself for any method that ordinarily generates QuerySets. 25 | 26 | Set the results to two items: 27 | 28 | >>> class Post(object): pass 29 | >>> objects = QuerySetMock(Post, 'return', 'values') 30 | >>> assert list(objects.filter()) == list(objects.all()) 31 | 32 | Force an exception: 33 | 34 | >>> objects = QuerySetMock(Post, Exception()) 35 | 36 | Chain calls: 37 | >>> objects.all().filter(filter_arg='dummy') 38 | """ 39 | 40 | def make_get(self, model): 41 | def _get(*a, **k): 42 | results = list(self) 43 | if len(results) > 1: 44 | raise model.MultipleObjectsReturned 45 | try: 46 | return results[0] 47 | except IndexError: 48 | raise model.DoesNotExist 49 | return _get 50 | 51 | def make_qs_returning_method(self): 52 | def _qs_returning_method(*a, **k): 53 | return copy.deepcopy(self) 54 | return _qs_returning_method 55 | 56 | def make_getitem(self): 57 | def _getitem(k): 58 | if isinstance(k, slice): 59 | self.__start = k.start 60 | self.__stop = k.stop 61 | else: 62 | return list(self)[k] 63 | return self 64 | return _getitem 65 | 66 | def make_iterator(self): 67 | def _iterator(*a, **k): 68 | if len(return_value) == 1 and isinstance(return_value[0], Exception): 69 | raise return_value[0] 70 | 71 | start = getattr(self, '__start', None) 72 | stop = getattr(self, '__stop', None) 73 | for x in return_value[start:stop]: 74 | yield x 75 | return _iterator 76 | 77 | actual_model = model 78 | if actual_model: 79 | model = mock.MagicMock(spec=actual_model()) 80 | else: 81 | model = mock.MagicMock() 82 | 83 | m = SharedMock(reserved=['count', 'exists'] + QUERYSET_RETURNING_METHODS) 84 | m.__start = None 85 | m.__stop = None 86 | m.__iter__.side_effect = lambda: iter(m.iterator()) 87 | m.__getitem__.side_effect = make_getitem(m) 88 | if hasattr(m, "__nonzero__"): 89 | # Python 2 90 | m.__nonzero__.side_effect = lambda: bool(return_value) 91 | m.exists.side_effect = m.__nonzero__ 92 | else: 93 | # Python 3 94 | m.__bool__.side_effect = lambda: bool(return_value) 95 | m.exists.side_effect = m.__bool__ 96 | m.__len__.side_effect = lambda: len(return_value) 97 | m.count.side_effect = m.__len__ 98 | 99 | m.model = model 100 | m.get = make_get(m, actual_model) 101 | 102 | for method_name in QUERYSET_RETURNING_METHODS: 103 | setattr(m, method_name, make_qs_returning_method(m)) 104 | 105 | # Note since this is a SharedMock, *all* auto-generated child 106 | # attributes will have the same side_effect ... might not make 107 | # sense for some like count(). 108 | m.iterator.side_effect = make_iterator(m) 109 | return m 110 | -------------------------------------------------------------------------------- /mock_django/shared.py: -------------------------------------------------------------------------------- 1 | import mock 2 | 3 | 4 | class SharedMock(mock.MagicMock): 5 | 6 | """ 7 | A MagicMock whose children are all itself. 8 | 9 | >>> m = SharedMock() 10 | >>> m is m.foo is m.bar is m.foo.bar.baz.qux 11 | True 12 | >>> m.foo.side_effect = ['hello from foo'] 13 | >>> m.bar() 14 | 'hello from foo' 15 | 16 | 'Magic' methods are not shared. 17 | >>> m.__getitem__ is m.__len__ 18 | False 19 | 20 | Neither are attributes you assign. 21 | >>> m.explicitly_assigned_attribute = 1 22 | >>> m.explicitly_assigned_attribute is m.foo 23 | False 24 | 25 | """ 26 | 27 | def __init__(self, *args, **kwargs): 28 | reserved = kwargs.pop('reserved', []) 29 | 30 | # XXX: we cannot bind to self until after the mock is initialized 31 | super(SharedMock, self).__init__(*args, **kwargs) 32 | 33 | parent = mock.MagicMock() 34 | parent.child = self 35 | self.__parent = parent 36 | self.__reserved = reserved 37 | 38 | def _get_child_mock(self, **kwargs): 39 | name = kwargs.get('name', '') 40 | if (name[:2] == name[-2:] == '__') or name in self.__reserved: 41 | return super(SharedMock, self)._get_child_mock(**kwargs) 42 | return self 43 | 44 | def __getattr__(self, name): 45 | result = super(SharedMock, self).__getattr__(name) 46 | if result is self: 47 | result._mock_name = result._mock_new_name = name 48 | return result 49 | 50 | def assert_chain_calls(self, *calls): 51 | """ 52 | Asserts that a chained method was called (parents in the chain do not 53 | matter, nor are they tracked). Use with `mock.call`. 54 | 55 | >>> obj.filter(foo='bar').select_related('baz') 56 | >>> obj.assert_chain_calls(mock.call.filter(foo='bar')) 57 | >>> obj.assert_chain_calls(mock.call.select_related('baz')) 58 | >>> obj.assert_chain_calls(mock.call.reverse()) 59 | *** AssertionError: [call.reverse()] not all found in call list, ... 60 | 61 | """ 62 | 63 | all_calls = self.__parent.mock_calls[:] 64 | 65 | not_found = [] 66 | for kall in calls: 67 | try: 68 | all_calls.remove(kall) 69 | except ValueError: 70 | not_found.append(kall) 71 | if not_found: 72 | if self.__parent.mock_calls: 73 | message = '%r not all found in call list, %d other(s) were:\n%r' % (not_found, len(self.__parent.mock_calls), self.__parent.mock_calls) 74 | else: 75 | message = 'no calls were found' 76 | 77 | raise AssertionError(message) 78 | -------------------------------------------------------------------------------- /mock_django/signals.py: -------------------------------------------------------------------------------- 1 | """ 2 | mock_django.signals 3 | ~~~~~~~~~~~~~~~~ 4 | 5 | :copyright: (c) 2012 DISQUS. 6 | :license: Apache License 2.0, see LICENSE for more details. 7 | """ 8 | import contextlib 9 | import mock 10 | 11 | 12 | @contextlib.contextmanager 13 | def mock_signal_receiver(signal, wraps=None, **kwargs): 14 | """ 15 | Temporarily attaches a receiver to the provided ``signal`` within the scope 16 | of the context manager. 17 | 18 | The mocked receiver is returned as the ``as`` target of the ``with`` 19 | statement. 20 | 21 | To have the mocked receiver wrap a callable, pass the callable as the 22 | ``wraps`` keyword argument. All other keyword arguments provided are passed 23 | through to the signal's ``connect`` method. 24 | 25 | >>> with mock_signal_receiver(post_save, sender=Model) as receiver: 26 | >>> Model.objects.create() 27 | >>> assert receiver.call_count = 1 28 | """ 29 | if wraps is None: 30 | def wraps(*args, **kwrags): 31 | return None 32 | 33 | receiver = mock.Mock(wraps=wraps) 34 | signal.connect(receiver, **kwargs) 35 | yield receiver 36 | signal.disconnect(receiver) 37 | -------------------------------------------------------------------------------- /runtests.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import django 4 | from django.conf import settings 5 | # collector import is required otherwise setuptools errors 6 | from nose.core import run, collector 7 | 8 | 9 | # Trick Django into thinking that we've configured a project, so importing 10 | # anything that tries to access attributes of `django.conf.settings` will just 11 | # return the default values, instead of crashing out. 12 | if not settings.configured: 13 | settings.configure( 14 | INSTALLED_APPS=[ 15 | "django.contrib.contenttypes", 16 | "django.contrib.auth", 17 | ], 18 | ) 19 | 20 | try: 21 | django.setup() 22 | except AttributeError: 23 | # Django 1.7 or lower 24 | pass 25 | 26 | 27 | if __name__ == '__main__': 28 | run() 29 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | 3 | # Hack to prevent stupid "TypeError: 'NoneType' object is not callable" error 4 | # in multiprocessing/util.py _exit_function when running `python 5 | # setup.py test` (see 6 | # http://www.eby-sarna.com/pipermail/peak/2010-May/003357.html) 7 | try: 8 | import multiprocessing 9 | except ImportError: 10 | pass 11 | 12 | setup( 13 | name='mock-django', 14 | version='0.6.10', 15 | description='', 16 | license='Apache License 2.0', 17 | author='David Cramer', 18 | author_email='dcramer@gmail.com', 19 | url='http://github.com/dcramer/mock-django', 20 | packages=find_packages(exclude=['tests', 'tests.*']), 21 | install_requires=[ 22 | 'Django>=1.4', 23 | 'mock', 24 | ], 25 | tests_require=[ 26 | 'unittest2', 27 | 'nose', 28 | ], 29 | test_suite='runtests.collector', 30 | zip_safe=False, 31 | include_package_data=True, 32 | ) 33 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dcramer/mock-django/1168d3255e0d67fbf74a9c71feaccbdafef59d21/tests/__init__.py -------------------------------------------------------------------------------- /tests/mock_django/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dcramer/mock-django/1168d3255e0d67fbf74a9c71feaccbdafef59d21/tests/mock_django/__init__.py -------------------------------------------------------------------------------- /tests/mock_django/http/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dcramer/mock-django/1168d3255e0d67fbf74a9c71feaccbdafef59d21/tests/mock_django/http/__init__.py -------------------------------------------------------------------------------- /tests/mock_django/http/tests.py: -------------------------------------------------------------------------------- 1 | try: 2 | # Python 2 3 | from unittest2 import TestCase, skipIf 4 | except ImportError: 5 | # Python 3 6 | from unittest import TestCase, skipIf 7 | 8 | try: 9 | # Python 2 10 | from urllib import urlencode 11 | except ImportError: 12 | # Python 3 13 | from urllib.parse import urlencode 14 | 15 | import django 16 | from django.contrib.auth.models import AnonymousUser 17 | 18 | from mock import Mock 19 | 20 | from mock_django.http import MockHttpRequest 21 | from mock_django.http import WsgiHttpRequest 22 | 23 | 24 | class WsgiHttpRequestTest(TestCase): 25 | def test_instance(self): 26 | wsgi_r = WsgiHttpRequest() 27 | 28 | self.assertTrue(isinstance(wsgi_r.user, AnonymousUser)) 29 | self.assertEqual({}, wsgi_r.session) 30 | self.assertEqual({}, wsgi_r.META) 31 | self.assertEqual({}, wsgi_r.GET) 32 | self.assertEqual({}, wsgi_r.POST) 33 | 34 | @skipIf(django.VERSION >= (1, 9), "MergeDict and REQUEST removed in Django 1.9") 35 | def test__get_request(self): 36 | from django.utils.datastructures import MergeDict 37 | wsgi_r = WsgiHttpRequest() 38 | expected_items = MergeDict({}, {}).items() 39 | 40 | wsgi_r.GET = {} 41 | wsgi_r.POST = {} 42 | 43 | self.assertListEqual(sorted(expected_items), 44 | sorted(wsgi_r._get_request().items())) 45 | 46 | def test_REQUEST_property(self): 47 | self.assertTrue(isinstance(WsgiHttpRequest.REQUEST, property)) 48 | 49 | def test__get_raw_post_data(self): 50 | wsgi_r = WsgiHttpRequest() 51 | 52 | wsgi_r._get_raw_post_data() 53 | 54 | self.assertEqual(urlencode({}), wsgi_r._raw_post_data) 55 | 56 | def test__set_raw_post_data(self): 57 | wsgi_r = WsgiHttpRequest() 58 | 59 | wsgi_r._set_raw_post_data('') 60 | 61 | self.assertEqual({}, wsgi_r.POST) 62 | self.assertEqual(urlencode({}), wsgi_r._raw_post_data) 63 | 64 | def test_raw_post_data_property(self): 65 | self.assertTrue(isinstance(WsgiHttpRequest.raw_post_data, property)) 66 | 67 | 68 | class MockHttpRequestTest(TestCase): 69 | def test_call(self): 70 | result = MockHttpRequest() 71 | meta = { 72 | 'REMOTE_ADDR': '127.0.0.1', 73 | 'SERVER_PORT': '8000', 74 | 'HTTP_REFERER': '', 75 | 'SERVER_NAME': 'testserver', 76 | } 77 | 78 | self.assertTrue(isinstance(result, WsgiHttpRequest)) 79 | self.assertEqual('/', result.path) 80 | self.assertEqual('GET', result.method) 81 | self.assertEqual(meta, result.META) 82 | self.assertEqual({}, result.GET) 83 | self.assertEqual({}, result.POST) 84 | self.assertTrue(isinstance(result.user, AnonymousUser)) 85 | 86 | def test_call(self): 87 | class MockUser: 88 | pass 89 | 90 | result = MockHttpRequest(user=MockUser()) 91 | 92 | self.assertTrue(isinstance(result.user, MockUser)) 93 | -------------------------------------------------------------------------------- /tests/mock_django/managers/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dcramer/mock-django/1168d3255e0d67fbf74a9c71feaccbdafef59d21/tests/mock_django/managers/__init__.py -------------------------------------------------------------------------------- /tests/mock_django/managers/tests.py: -------------------------------------------------------------------------------- 1 | import mock 2 | from mock_django.managers import ManagerMock 3 | try: 4 | # Python 2 5 | from unittest2 import TestCase 6 | except ImportError: 7 | # Python 3 8 | from unittest import TestCase 9 | 10 | 11 | class Model(object): 12 | class DoesNotExist(Exception): 13 | pass 14 | 15 | class MultipleObjectsReturned(Exception): 16 | pass 17 | 18 | 19 | def make_manager(): 20 | manager = mock.MagicMock(spec=( 21 | 'all', 'filter', 'order_by', 22 | )) 23 | manager.model = Model 24 | return manager 25 | 26 | 27 | class ManagerMockTestCase(TestCase): 28 | def test_iter(self): 29 | manager = make_manager() 30 | inst = ManagerMock(manager, 'foo') 31 | self.assertEquals(list(inst.all()), ['foo']) 32 | 33 | def test_iter_exception(self): 34 | manager = make_manager() 35 | inst = ManagerMock(manager, Exception()) 36 | self.assertRaises(Exception, list, inst.all()) 37 | 38 | def test_getitem(self): 39 | manager = make_manager() 40 | inst = ManagerMock(manager, 'foo') 41 | self.assertEquals(inst.all()[0], 'foo') 42 | 43 | def test_returns_self(self): 44 | manager = make_manager() 45 | inst = ManagerMock(manager, 'foo') 46 | self.assertEquals(inst.all(), inst) 47 | 48 | def test_get_on_singular_list(self): 49 | manager = make_manager() 50 | inst = ManagerMock(manager, 'foo') 51 | 52 | self.assertEquals(inst.get(), 'foo') 53 | 54 | def test_get_on_multiple_objects(self): 55 | manager = make_manager() 56 | inst = ManagerMock(manager, 'foo', 'bar') 57 | inst.model.MultipleObjectsReturned = Exception 58 | 59 | self.assertRaises(inst.model.MultipleObjectsReturned, inst.get) 60 | 61 | def test_get_raises_doesnotexist(self): 62 | manager = make_manager() 63 | inst = ManagerMock(manager) 64 | inst.model.DoesNotExist = Exception 65 | 66 | self.assertRaises(inst.model.DoesNotExist, inst.get) 67 | 68 | def test_call_tracking(self): 69 | # only works in >= mock 0.8 70 | manager = make_manager() 71 | inst = ManagerMock(manager, 'foo') 72 | 73 | inst.filter(foo='bar').select_related('baz') 74 | 75 | calls = inst.mock_calls 76 | 77 | self.assertGreater(len(calls), 1) 78 | inst.assert_chain_calls(mock.call.filter(foo='bar')) 79 | inst.assert_chain_calls(mock.call.select_related('baz')) 80 | 81 | def test_getitem_get(self): 82 | manager = make_manager() 83 | inst = ManagerMock(manager, 'foo') 84 | self.assertEquals(inst[0:1].get(), 'foo') 85 | 86 | def test_get_raises_doesnotexist_with_queryset(self): 87 | manager = make_manager() 88 | inst = ManagerMock(manager) 89 | queryset = inst.using('default.slave')[0:1] 90 | self.assertRaises(manager.model.DoesNotExist, queryset.get) 91 | -------------------------------------------------------------------------------- /tests/mock_django/models/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dcramer/mock-django/1168d3255e0d67fbf74a9c71feaccbdafef59d21/tests/mock_django/models/__init__.py -------------------------------------------------------------------------------- /tests/mock_django/models/tests.py: -------------------------------------------------------------------------------- 1 | from mock import MagicMock 2 | from mock_django.models import ModelMock 3 | try: 4 | # Python 2 5 | from unittest2 import TestCase 6 | except ImportError: 7 | # Python 3 8 | from unittest import TestCase 9 | 10 | 11 | class Model(object): 12 | id = '1' 13 | pk = '2' 14 | 15 | def foo(self): 16 | pass 17 | 18 | def bar(self): 19 | return 'bar' 20 | 21 | 22 | class ModelMockTestCase(TestCase): 23 | def test_pk_alias(self): 24 | mock = ModelMock(Model) 25 | self.assertEquals(mock.id, mock.pk) 26 | 27 | def test_only_model_attrs_exist(self): 28 | """ 29 | ModelMocks have only the members that the Model has. 30 | """ 31 | mock = ModelMock(Model) 32 | self.assertRaises(AttributeError, lambda x: x.baz, mock) 33 | 34 | def test_model_attrs_are_mocks(self): 35 | """ 36 | ModelMock members are Mocks, not the actual model members. 37 | """ 38 | mock = ModelMock(Model) 39 | self.assertNotEquals(mock.bar(), 'bar') 40 | self.assertIsInstance(mock, MagicMock) 41 | 42 | def test_attrs_are_not_identical(self): 43 | """ 44 | Each member of a ModelMock is unique. 45 | """ 46 | mock = ModelMock(Model) 47 | self.assertIsNot(mock.foo, mock.bar) 48 | self.assertIsNot(mock.foo, mock.id) 49 | -------------------------------------------------------------------------------- /tests/mock_django/query/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dcramer/mock-django/1168d3255e0d67fbf74a9c71feaccbdafef59d21/tests/mock_django/query/__init__.py -------------------------------------------------------------------------------- /tests/mock_django/query/tests.py: -------------------------------------------------------------------------------- 1 | from mock_django.query import QuerySetMock 2 | try: 3 | # Python 2 4 | from unittest2 import TestCase 5 | except ImportError: 6 | # Python 3 7 | from unittest import TestCase 8 | 9 | 10 | class TestException(Exception): 11 | pass 12 | 13 | 14 | class TestModel(object): 15 | def foo(self): 16 | pass 17 | 18 | def bar(self): 19 | return 'bar' 20 | 21 | 22 | class QuerySetTestCase(TestCase): 23 | def test_vals_returned(self): 24 | qs = QuerySetMock(None, 1, 2, 3) 25 | self.assertEquals(list(qs), [1, 2, 3]) 26 | 27 | def test_qs_generator_inequality(self): 28 | """ 29 | Each QuerySet-returning method's return value is unique. 30 | """ 31 | qs = QuerySetMock(None, 1, 2, 3) 32 | self.assertNotEquals(qs.all(), qs.filter()) 33 | self.assertNotEquals(qs.filter(), qs.order_by()) 34 | 35 | def test_qs_yield_equality(self): 36 | """ 37 | The generators may not be the same, but they do produce the same output. 38 | """ 39 | qs = QuerySetMock(None, 1, 2, 3) 40 | self.assertEquals(list(qs.all()), list(qs.filter())) 41 | 42 | def test_qs_method_takes_arg(self): 43 | """ 44 | QS-returning methods are impotent, but they do take args. 45 | """ 46 | qs = QuerySetMock(None, 1, 2, 3) 47 | self.assertEquals(list(qs.order_by('something')), [1, 2, 3]) 48 | 49 | def test_raises_exception_when_evaluated(self): 50 | """ 51 | Exception raises when you actually use a QS-returning method. 52 | """ 53 | qs = QuerySetMock(None, TestException()) 54 | self.assertRaises(TestException, list, qs.all()) 55 | 56 | def test_raises_exception_when_accessed(self): 57 | """ 58 | Exceptions can raise on getitem, too. 59 | """ 60 | qs = QuerySetMock(None, TestException()) 61 | self.assertRaises(TestException, lambda x: x[0], qs) 62 | 63 | def test_chaining_calls_works(self): 64 | """ 65 | Chained calls to QS-returning methods should return new QuerySetMocks. 66 | """ 67 | qs = QuerySetMock(None, 1, 2, 3) 68 | qs.all().filter(filter_arg='dummy') 69 | qs.filter(filter_arg='dummy').order_by('-date') 70 | 71 | def test_chained_calls_return_new_querysetmocks(self): 72 | qs = QuerySetMock(None, 1, 2, 3) 73 | qs_all = qs.all() 74 | qs_filter = qs.filter() 75 | qs_all_filter = qs.filter().all() 76 | 77 | self.assertIsNot(qs_all, qs_filter) 78 | self.assertIsNot(qs_filter, qs_all_filter) 79 | 80 | # Test reserved methods 81 | def test_count_is_scalar(self): 82 | qs = QuerySetMock(None, 1, 2, 3) 83 | self.assertEquals(qs.count(), 3) 84 | 85 | def test_exists_is_boolean(self): 86 | qs = QuerySetMock(None) 87 | self.assertFalse(qs.exists()) 88 | 89 | qs = QuerySetMock(None, 1, 2, 3) 90 | self.assertTrue(qs.exists()) 91 | 92 | def test_objects_returned_do_not_change_type(self): 93 | """ 94 | Not sure this is the behavior we want, but it's the behavior we have. 95 | """ 96 | qs = QuerySetMock(TestModel, 1, 2, 3) 97 | self.assertNotIsInstance(qs[0], TestModel) 98 | -------------------------------------------------------------------------------- /tests/mock_django/signals/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dcramer/mock-django/1168d3255e0d67fbf74a9c71feaccbdafef59d21/tests/mock_django/signals/__init__.py -------------------------------------------------------------------------------- /tests/mock_django/signals/tests.py: -------------------------------------------------------------------------------- 1 | from django.dispatch import Signal 2 | from mock_django.signals import mock_signal_receiver 3 | try: 4 | # Python 2 5 | from unittest2 import TestCase 6 | except ImportError: 7 | # Python 3 8 | from unittest import TestCase 9 | 10 | 11 | class MockSignalTestCase(TestCase): 12 | def test_mock_receiver(self): 13 | signal = Signal() 14 | with mock_signal_receiver(signal) as receiver: 15 | signal.send(sender=None) 16 | self.assertEqual(receiver.call_count, 1) 17 | 18 | sentinel = {} 19 | 20 | def side_effect(*args, **kwargs): 21 | return sentinel 22 | 23 | with mock_signal_receiver(signal, wraps=side_effect) as receiver: 24 | responses = signal.send(sender=None) 25 | self.assertEqual(receiver.call_count, 1) 26 | 27 | # Signals respond with a list of tuple pairs [(receiver, response), ...] 28 | self.assertIs(responses[0][1], sentinel) 29 | -------------------------------------------------------------------------------- /tests/requirements.txt: -------------------------------------------------------------------------------- 1 | nose 2 | unittest2 3 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | # Tox (http://tox.testrun.org/) is a tool for running tests 2 | # in multiple virtualenvs. This configuration file will run the 3 | # test suite on all supported python versions. To use it, "pip install tox" 4 | # and then run "tox" from this directory. 5 | 6 | [tox] 7 | envlist = 8 | py34-django{1.9,1.8,1.7,1.6,1.5}, 9 | py27-django{1.9,1.8,1.7,1.6,1.5,1.4}, 10 | py26-django{1.6,1.5,1.4}, 11 | flake8 12 | 13 | [testenv] 14 | commands = {envpython} runtests.py 15 | basepython = 16 | py35: python3.5 17 | py34: python3.4 18 | py33: python3.4 19 | py32: python3.4 20 | py27: python2.7 21 | py26: python2.6 22 | pypy: pypy 23 | pypy3: pypy3 24 | deps = 25 | django1.4: Django==1.4 26 | django1.5: Django==1.5 27 | django1.6: Django==1.6 28 | django1.7: Django==1.7 29 | django1.8: Django==1.8 30 | django1.9: Django==1.9a1 31 | -r{toxinidir}/tests/requirements.txt 32 | 33 | [testenv:flake8] 34 | basepython=python 35 | deps=flake8 36 | commands= 37 | flake8 mock_django 38 | 39 | [flake8] 40 | ignore = E501,E225,F403 41 | --------------------------------------------------------------------------------