2009-07-21 00:54:08 +08:00
|
|
|
|
|
|
|
pytest_monkeypatch plugin
|
|
|
|
=========================
|
|
|
|
|
|
|
|
safely patch object attributes, dicts and environment variables.
|
|
|
|
|
2009-07-22 22:09:49 +08:00
|
|
|
.. contents::
|
|
|
|
:local:
|
|
|
|
|
2009-07-21 00:54:08 +08:00
|
|
|
Usage
|
|
|
|
----------------
|
|
|
|
|
|
|
|
Use the `monkeypatch funcarg`_ to safely patch the environment
|
|
|
|
variables, object attributes or dictionaries. For example, if you want
|
|
|
|
to set the environment variable ``ENV1`` and patch the
|
|
|
|
``os.path.abspath`` function to return a particular value during a test
|
|
|
|
function execution you can write it down like this:
|
|
|
|
|
|
|
|
.. sourcecode:: python
|
|
|
|
|
|
|
|
def test_mytest(monkeypatch):
|
|
|
|
monkeypatch.setenv('ENV1', 'myval')
|
|
|
|
monkeypatch.setattr(os.path, 'abspath', lambda x: '/')
|
|
|
|
... # your test code
|
|
|
|
|
|
|
|
The function argument will do the modifications and memorize the
|
|
|
|
old state. After the test function finished execution all
|
|
|
|
modifications will be reverted. See the `monkeypatch blog post`_
|
|
|
|
for an extensive discussion.
|
|
|
|
|
|
|
|
.. _`monkeypatch blog post`: http://tetamap.wordpress.com/2009/03/03/monkeypatching-in-unit-tests-done-right/
|
2009-07-22 22:09:49 +08:00
|
|
|
|
2009-07-21 00:54:08 +08:00
|
|
|
.. _`monkeypatch funcarg`:
|
|
|
|
|
|
|
|
|
|
|
|
the 'monkeypatch' test function argument
|
|
|
|
----------------------------------------
|
|
|
|
|
|
|
|
The returned ``monkeypatch`` funcarg provides three
|
|
|
|
helper methods to modify objects, dictionaries or os.environ::
|
|
|
|
|
|
|
|
monkeypatch.setattr(obj, name, value)
|
|
|
|
monkeypatch.setitem(mapping, name, value)
|
|
|
|
monkeypatch.setenv(name, value)
|
|
|
|
|
|
|
|
All such modifications will be undone when the requesting
|
|
|
|
test function finished its execution.
|
|
|
|
|
2009-07-22 22:09:49 +08:00
|
|
|
Start improving this plugin in 30 seconds
|
|
|
|
=========================================
|
2009-07-21 00:54:08 +08:00
|
|
|
|
|
|
|
|
2009-07-22 22:09:49 +08:00
|
|
|
Do you find the above documentation or the plugin itself lacking?
|
2009-07-21 00:54:08 +08:00
|
|
|
|
|
|
|
1. Download `pytest_monkeypatch.py`_ plugin source code
|
|
|
|
2. put it somewhere as ``pytest_monkeypatch.py`` into your import path
|
2009-07-22 22:09:49 +08:00
|
|
|
3. a subsequent ``py.test`` run will use your local version
|
2009-07-21 00:54:08 +08:00
|
|
|
|
|
|
|
Further information: extend_ documentation, other plugins_ or contact_.
|
|
|
|
|
2009-07-31 20:43:04 +08:00
|
|
|
.. include:: links.txt
|