
Monkeypatching/mocking modules and environments
================================================================

.. currentmodule:: _pytest.monkeypatch

Sometimes tests need to invoke functionality which depends
on global settings or which invokes code which cannot be easily
tested such as network access.  The ``monkeypatch`` function argument
helps you to safely set/delete an attribute, dictionary item or
environment variable or to modify ``sys.path`` for importing.
See the `monkeypatch blog post`_ for some introduction material
and a discussion of its motivation.

.. _`monkeypatch blog post`: http://tetamap.wordpress.com/2009/03/03/monkeypatching-in-unit-tests-done-right/


Simple example: patching ``os.path.expanduser``
---------------------------------------------------

If, for instance, you want to pretend that ``os.expanduser`` returns a certain
directory, you can use the :py:meth:`monkeypatch.setattr` method to
patch this function before calling into a function which uses it::

    import os.path
    def getssh(): # pseudo application code
        return os.path.join(os.path.expanduser("~admin"), '.ssh')

    def test_mytest(monkeypatch):
        def mockreturn(path):
            return '/abc'
        monkeypatch.setattr(os.path, 'expanduser', mockreturn)
        x = getssh()
        assert x == '/abc/.ssh'

After the test function finishes the ``os.path.expanduser`` modification
will be undone.

.. background check:
   $ py.test
   =========================== test session starts ============================
   platform darwin -- Python 2.7.1 -- pytest-2.1.3
   collecting ... collected 0 items
   
   =============================  in 0.00 seconds =============================

Method reference of the monkeypatch function argument
-----------------------------------------------------

.. autoclass:: monkeypatch
    :members: setattr, delattr, setitem, delitem, setenv, delenv, syspath_prepend, undo

``monkeypatch.setattr/delattr/delitem/delenv()`` all
by default raise an Exception if the target does not exist.
Pass ``raising=False`` if you want to skip this check.

