Thin-wrapper around the mock package for easier use with py.test
Project description
This plugin installs a mock fixture which is a thin-wrapper around the patching API provided by the excellent mock package, but with the benefit of not having to worry about undoing patches at the end of a test:
def test_unix_fs(mock):
mock.patch('os.remove')
UnixFS.rm('file')
os.remove.assert_called_once_with('file')
Usage
The mock fixture has the same API as mock.patch, supporting the same arguments:
def test_foo(mock):
# all valid calls
mock.patch('os.remove')
mock.patch.object(os, 'listdir', autospec=True)
mocked = mock.patch('os.path.isfile')
The supported methods are:
mock.patch: see http://www.voidspace.org.uk/python/mock/patch.html#patch.
mock.patch.object: see http://www.voidspace.org.uk/python/mock/patch.html#patch-object.
mock.patch.multiple: see http://www.voidspace.org.uk/python/mock/patch.html#patch-multiple.
mock.stopall(): stops all active patches at this point.
Why bother with a plugin?
There are a number of different patch usages in the standard mock API, but IMHO they don’t scale very well when you have a more than one or two patches to apply.
It may lead to an excessive nesting of with statements, breaking the flow of the test:
import mock
def test_unix_fs():
with mock.patch('os.remove'):
UnixFS.rm('file')
os.remote.assert_called_once_with('file')
with mock.patch('os.listdir'):
assert UnixFS.ls('dir') == expected
# ...
with mock.patch('shutil.copy'):
UnixFS.cp('src', 'dst')
# ...
One can use patch as a decorator to improve the flow of the test, but now the test functions must receive the mock objects:
@mock.patch('os.remove')
@mock.patch('os.listdir')
@mock.patch('shutil.copy')
def test_unix_fs(mocked_copy, mocked_listdir, mocked_copy):
UnixFS.rm('file')
os.remote.assert_called_once_with('file')
assert UnixFS.ls('dir') == expected
# ...
UnixFS.cp('src', 'dst')
# ...
Even when you prefer to access the mocks using the original references. Besides don’t mixing nicely with other fixtures (although it works), you can’t easily undo the mocking if you follow this approach.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for pytest_mock-0.1.0-py2.py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 127bde0696a30137154f7cc0d343ea743eb10327dbf3a667c2381ad56f78d0cf |
|
MD5 | ceee55e81d2d7fe37c8a3bc34aa517bb |
|
BLAKE2b-256 | 419239d235497e34d5600c0404e843f1ee8f5ddafcf204d299078d0379563db5 |