2010-10-11 05:45:45 +08:00
|
|
|
|
|
|
|
monkeypatching/mocking modules and environments
|
|
|
|
================================================================
|
|
|
|
|
2010-11-13 18:10:45 +08:00
|
|
|
.. currentmodule:: _pytest.monkeypatch
|
2010-10-11 05:45:45 +08:00
|
|
|
|
|
|
|
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`_ one some introduction material
|
|
|
|
and motivation.
|
|
|
|
|
|
|
|
.. _`monkeypatch blog post`: http://tetamap.wordpress.com/2009/03/03/monkeypatching-in-unit-tests-done-right/
|
|
|
|
|
|
|
|
|
|
|
|
Simple example: patching ``os.path.expanduser``
|
|
|
|
---------------------------------------------------
|
|
|
|
|
|
|
|
If you e.g. 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.expanduser("~admin"), '.ssh')
|
|
|
|
|
|
|
|
def test_mytest(monkeypatch):
|
2010-10-11 16:07:14 +08:00
|
|
|
def mockreturn(path):
|
|
|
|
return '/abc'
|
|
|
|
monkeypatch.setattr(os.path, 'expanduser', mockreturn)
|
2010-10-11 05:45:45 +08:00
|
|
|
x = getssh()
|
2010-10-11 16:07:14 +08:00
|
|
|
assert x == '/abc'
|
2010-10-11 05:45:45 +08:00
|
|
|
|
|
|
|
After the test function finishes the ``os.path.expanduser`` modification
|
|
|
|
will be undone.
|
|
|
|
|
2010-10-11 16:07:14 +08:00
|
|
|
.. background check:
|
|
|
|
$ py.test
|
2010-10-12 16:59:04 +08:00
|
|
|
=========================== test session starts ============================
|
2010-11-18 05:12:16 +08:00
|
|
|
platform linux2 -- Python 2.6.5 -- pytest-2.0.0.dev30
|
|
|
|
test path 1: /tmp/doc-exec-75
|
2010-10-11 16:07:14 +08:00
|
|
|
|
2010-10-12 16:59:04 +08:00
|
|
|
============================= in 0.00 seconds =============================
|
2010-10-11 05:45:45 +08:00
|
|
|
|
|
|
|
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.
|
|
|
|
|