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.patch.dict: see http://www.voidspace.org.uk/python/mock/patch.html#patch-dict.
mock.stopall(): stops all active patches at this point.
Requirements
Python 2.6+, Python 3.2+
pytest
mock (for Python < 3.3)
Install
Install using pip:
$ pip install pytest-mock
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.remove.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:
@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.remove.assert_called_once_with('file')
assert UnixFS.ls('dir') == expected
# ...
UnixFS.cp('src', 'dst')
# ...
But this poses a few disadvantages:
test functions must receive the mock objects as parameter, even if you don’t plan to access them directly; also, order depends on the order of the decorated patch functions;
receiving the mocks as parameters doesn’t mix nicely with pytest’s approach of naming fixtures as parameters, or pytest.mark.parametrize;
you can’t easily undo the mocking during the test execution;
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.2.0-py2.py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 3e62c954197cc0394fade51fb585b4798fa4f73259c27d2106f40d2bf648f9a0 |
|
MD5 | 49d5a8005e028e7616e8e2b91a1f0a8f |
|
BLAKE2b-256 | b82d53273a710634bdb8fc917c37425850c65940ec90fd003cf286285e3b9e0a |