Skip to content

Commit 59d7128

Browse files
committed
Adding README documentation
1 parent 39a75b6 commit 59d7128

File tree

2 files changed

+80
-4
lines changed

2 files changed

+80
-4
lines changed

README.md

Lines changed: 0 additions & 4 deletions
This file was deleted.

README.rst

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
pytest-mock
2+
===========
3+
4+
Thin-wrapper around the mock package for easier use with py.test.
5+
6+
This plugin provides a fixture named `mock` that has the same patching API
7+
provided by the excellent `mock <http://pypi.python.org/pypi/mock>`_ package,
8+
but with the benefit of not having to worry about undoing patches at the end
9+
of a test::
10+
11+
12+
def test_unix_fs(mock):
13+
mock.patch('os.remove')
14+
UnixFS.rm('file')
15+
os.remove.assert_called_once_with('file')
16+
17+
18+
Usage
19+
-----
20+
21+
The `mock` fixture has the same API as
22+
`mock.patch <http://www.voidspace.org.uk/python/mock/patch.html#patch-decorators>`_,
23+
supporting the same arguments::
24+
25+
# all valid calls
26+
mock.patch('os.remove')
27+
mock.patch.object(os, 'listdir', autospec=True)
28+
mocked = mock.patch('os.remove')
29+
30+
The supported methods are:
31+
32+
- `mock.patch`: see http://www.voidspace.org.uk/python/mock/patch.html#patch.
33+
- `mock.patch.object`: see `http://www.voidspace.org.uk/python/mock/patch.html#patch-object.
34+
- `mock.patch.multiple`: see `http://www.voidspace.org.uk/python/mock/patch.html#patch-multiple.
35+
- `mock.stopall()`: stops all active patches at this point.
36+
37+
Why bother with a plugin?
38+
-------------------------
39+
40+
There are a number of different `patch` usages in the standard `mock` API,
41+
but IMHO they don't scale very well when you have a more than one or two
42+
patches to apply.
43+
44+
It may lead to an excessive nesting of `with` statements, breaking the flow
45+
of the test::
46+
47+
import mock
48+
49+
def test_unix_fs():
50+
with mock.patch('os.remove'):
51+
UnixFS.rm('file')
52+
os.remote.assert_called_once_with('file')
53+
54+
with mock.patch('os.listdir'):
55+
assert UnixFS.ls('dir') == expected
56+
# ...
57+
58+
with mock.patch('shutil.copy'):
59+
UnixFS.cp('src', 'dst')
60+
# ...
61+
62+
63+
One can use `patch` as a decorator to improve the flow of the test, but now the
64+
test functions must receive the mock objects::
65+
66+
@mock.patch('os.remove')
67+
@mock.patch('os.listdir')
68+
@mock.patch('shutil.copy')
69+
def test_unix_fs(mocked_copy, mocked_listdir, mocked_copy):
70+
UnixFS.rm('file')
71+
os.remote.assert_called_once_with('file')
72+
73+
assert UnixFS.ls('dir') == expected
74+
# ...
75+
76+
UnixFS.cp('src', 'dst')
77+
# ...
78+
79+
Even when you prefer to access the mocks using the original references. Plus
80+
now you cannot easily undo the mocking if you follow this approach.

0 commit comments

Comments
 (0)