@@ -260,5 +260,37 @@ mock is a library for testing in Python.
260260It allows you to replace parts of your system under test with mock objects and
261261make assertions about how they have been used.
262262
263+ For example, you can monkey patch a method
264+
265+ ::
266+
267+ from mock import MagicMock
268+ thing = ProductionClass()
269+ thing.method = MagicMock(return_value=3)
270+ thing.method(3, 4, 5, key='value')
271+
272+ thing.method.assert_called_with(3, 4, 5, key='value')
273+
274+ To mock classes or objects in a module under test, use the ``patch `` decorator.
275+ In the example below, an external search system is replaced with a mock that
276+ always returns the same result (but only for the duration of the test).
277+
278+ ::
279+
280+ def mock_search(self):
281+ class MockSearchQuerySet(SearchQuerySet):
282+ def __iter__(self):
283+ return iter(["foo", "bar", "baz"])
284+ return MockSearchQuerySet()
285+
286+ # SearchForm here refers to the imported class reference in myapp,
287+ # not where the SearchForm class itself is imported from
288+ @mock.patch('myapp.SearchForm.search', mock_search)
289+ def test_new_watchlist_activities(self):
290+ # get_search_results runs a search and iterates over the result
291+ self.assertEqual(len(myapp.get_search_results(q="fish")), 3)
292+
293+ Mock has many other ways you can configure it and control its behaviour.
294+
263295 `mock <http://www.voidspace.org.uk/python/mock/ >`_
264296
0 commit comments