From b96b11fe59d6fd761f0a96a34c968f29bbff0cf9 Mon Sep 17 00:00:00 2001 From: Roger Barnes Date: Tue, 18 Sep 2012 21:04:14 +1000 Subject: [PATCH 1/2] Add mock library to testing page --- docs/writing/tests.rst | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/docs/writing/tests.rst b/docs/writing/tests.rst index 12590b6..342b133 100644 --- a/docs/writing/tests.rst +++ b/docs/writing/tests.rst @@ -1,5 +1,5 @@ Testing Your Code -===================== +================= Testing your code is very important. @@ -248,3 +248,17 @@ the need to change any other code. `unittest2 `_ +mock +---- + +mock is a library for testing in Python. + +:: + + $ pip install mock + +It allows you to replace parts of your system under test with mock objects and +make assertions about how they have been used. + + `mock `_ + From 3b902fe0906ea25816ab5171f9e8776472b0f213 Mon Sep 17 00:00:00 2001 From: Roger Barnes Date: Wed, 19 Sep 2012 16:46:54 +1000 Subject: [PATCH 2/2] Add examples to section on mock --- docs/writing/tests.rst | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/docs/writing/tests.rst b/docs/writing/tests.rst index 342b133..975adf6 100644 --- a/docs/writing/tests.rst +++ b/docs/writing/tests.rst @@ -260,5 +260,37 @@ mock is a library for testing in Python. It allows you to replace parts of your system under test with mock objects and make assertions about how they have been used. +For example, you can monkey patch a method + +:: + + from mock import MagicMock + thing = ProductionClass() + thing.method = MagicMock(return_value=3) + thing.method(3, 4, 5, key='value') + + thing.method.assert_called_with(3, 4, 5, key='value') + +To mock classes or objects in a module under test, use the ``patch`` decorator. +In the example below, an external search system is replaced with a mock that +always returns the same result (but only for the duration of the test). + +:: + + def mock_search(self): + class MockSearchQuerySet(SearchQuerySet): + def __iter__(self): + return iter(["foo", "bar", "baz"]) + return MockSearchQuerySet() + + # SearchForm here refers to the imported class reference in myapp, + # not where the SearchForm class itself is imported from + @mock.patch('myapp.SearchForm.search', mock_search) + def test_new_watchlist_activities(self): + # get_search_results runs a search and iterates over the result + self.assertEqual(len(myapp.get_search_results(q="fish")), 3) + +Mock has many other ways you can configure it and control its behaviour. + `mock `_