Skip to main content

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')

version downloads ci

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:

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


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pytest-mock-0.1.0.zip (11.0 kB view hashes)

Uploaded Source

Built Distribution

pytest_mock-0.1.0-py2.py3-none-any.whl (5.4 kB view hashes)

Uploaded Python 2 Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page