|
1 | 1 | Testing Your Code |
2 | | -===================== |
| 2 | +================= |
3 | 3 |
|
4 | 4 | Testing your code is very important. |
5 | 5 |
|
@@ -248,3 +248,49 @@ the need to change any other code. |
248 | 248 | `unittest2 <http://pypi.python.org/pypi/unittest2>`_ |
249 | 249 |
|
250 | 250 |
|
| 251 | +mock |
| 252 | +---- |
| 253 | + |
| 254 | +mock is a library for testing in Python. |
| 255 | + |
| 256 | +:: |
| 257 | + |
| 258 | + $ pip install mock |
| 259 | + |
| 260 | +It allows you to replace parts of your system under test with mock objects and |
| 261 | +make assertions about how they have been used. |
| 262 | + |
| 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 | + |
| 295 | + `mock <http://www.voidspace.org.uk/python/mock/>`_ |
| 296 | + |
0 commit comments