2010-10-11 05:45:45 +08:00
|
|
|
""" monkeypatching and mocking functionality. """
|
2009-07-21 00:54:08 +08:00
|
|
|
|
2013-10-04 00:25:03 +08:00
|
|
|
import os, sys
|
2013-10-21 20:01:02 +08:00
|
|
|
from py.builtin import _basestring
|
2009-03-17 17:18:38 +08:00
|
|
|
|
2009-05-19 05:26:16 +08:00
|
|
|
def pytest_funcarg__monkeypatch(request):
|
2010-07-27 03:15:15 +08:00
|
|
|
"""The returned ``monkeypatch`` funcarg provides these
|
2009-07-21 00:54:08 +08:00
|
|
|
helper methods to modify objects, dictionaries or os.environ::
|
|
|
|
|
2010-07-27 03:15:15 +08:00
|
|
|
monkeypatch.setattr(obj, name, value, raising=True)
|
2009-08-22 18:45:58 +08:00
|
|
|
monkeypatch.delattr(obj, name, raising=True)
|
2010-07-27 03:15:15 +08:00
|
|
|
monkeypatch.setitem(mapping, name, value)
|
2009-08-22 18:45:58 +08:00
|
|
|
monkeypatch.delitem(obj, name, raising=True)
|
2010-07-27 03:15:15 +08:00
|
|
|
monkeypatch.setenv(name, value, prepend=False)
|
2009-08-22 18:45:58 +08:00
|
|
|
monkeypatch.delenv(name, value, raising=True)
|
2009-09-06 05:21:58 +08:00
|
|
|
monkeypatch.syspath_prepend(path)
|
2012-01-06 22:25:57 +08:00
|
|
|
monkeypatch.chdir(path)
|
2009-08-22 18:45:58 +08:00
|
|
|
|
2011-03-04 06:40:38 +08:00
|
|
|
All modifications will be undone after the requesting
|
|
|
|
test function has finished. The ``raising``
|
2010-07-27 03:15:15 +08:00
|
|
|
parameter determines if a KeyError or AttributeError
|
|
|
|
will be raised if the set/deletion operation has no target.
|
2009-07-21 00:54:08 +08:00
|
|
|
"""
|
2010-10-11 05:45:45 +08:00
|
|
|
mpatch = monkeypatch()
|
|
|
|
request.addfinalizer(mpatch.undo)
|
|
|
|
return mpatch
|
2009-02-27 18:18:27 +08:00
|
|
|
|
2013-09-27 18:33:06 +08:00
|
|
|
|
|
|
|
|
2015-05-20 04:59:49 +08:00
|
|
|
def derive_importpath(import_path, raising):
|
2013-10-04 00:25:03 +08:00
|
|
|
import pytest
|
2013-10-22 17:26:29 +08:00
|
|
|
if not isinstance(import_path, _basestring) or "." not in import_path:
|
2013-09-27 18:33:06 +08:00
|
|
|
raise TypeError("must be absolute import path string, not %r" %
|
|
|
|
(import_path,))
|
|
|
|
rest = []
|
|
|
|
target = import_path
|
|
|
|
while target:
|
|
|
|
try:
|
|
|
|
obj = __import__(target, None, None, "__doc__")
|
|
|
|
except ImportError:
|
|
|
|
if "." not in target:
|
|
|
|
__tracebackhide__ = True
|
|
|
|
pytest.fail("could not import any sub part: %s" %
|
|
|
|
import_path)
|
|
|
|
target, name = target.rsplit(".", 1)
|
|
|
|
rest.append(name)
|
|
|
|
else:
|
|
|
|
assert rest
|
|
|
|
try:
|
|
|
|
while len(rest) > 1:
|
|
|
|
attr = rest.pop()
|
|
|
|
obj = getattr(obj, attr)
|
|
|
|
attr = rest[0]
|
2015-05-20 04:59:49 +08:00
|
|
|
if raising:
|
|
|
|
getattr(obj, attr)
|
2013-09-27 18:33:06 +08:00
|
|
|
except AttributeError:
|
|
|
|
__tracebackhide__ = True
|
|
|
|
pytest.fail("object %r has no attribute %r" % (obj, attr))
|
|
|
|
return attr, obj
|
|
|
|
|
|
|
|
|
|
|
|
|
2014-05-10 19:49:24 +08:00
|
|
|
class Notset:
|
|
|
|
def __repr__(self):
|
|
|
|
return "<notset>"
|
|
|
|
|
|
|
|
notset = Notset()
|
2009-02-27 18:18:27 +08:00
|
|
|
|
2010-10-11 05:45:45 +08:00
|
|
|
class monkeypatch:
|
2015-01-09 09:15:22 +08:00
|
|
|
""" Object keeping a record of setattr/item/env/syspath changes. """
|
2009-02-27 18:18:27 +08:00
|
|
|
def __init__(self):
|
|
|
|
self._setattr = []
|
|
|
|
self._setitem = []
|
2012-01-04 19:43:19 +08:00
|
|
|
self._cwd = None
|
2009-02-27 18:18:27 +08:00
|
|
|
|
2013-09-27 18:33:06 +08:00
|
|
|
def setattr(self, target, name, value=notset, raising=True):
|
2015-01-09 09:15:22 +08:00
|
|
|
""" Set attribute value on target, memorizing the old value.
|
2013-09-27 18:33:06 +08:00
|
|
|
By default raise AttributeError if the attribute did not exist.
|
2013-08-07 21:35:27 +08:00
|
|
|
|
2013-09-27 18:33:06 +08:00
|
|
|
For convenience you can specify a string as ``target`` which
|
|
|
|
will be interpreted as a dotted import path, with the last part
|
|
|
|
being the attribute name. Example:
|
|
|
|
``monkeypatch.setattr("os.getcwd", lambda x: "/")``
|
|
|
|
would set the ``getcwd`` function of the ``os`` module.
|
|
|
|
|
|
|
|
The ``raising`` value determines if the setattr should fail
|
|
|
|
if the attribute is not already present (defaults to True
|
|
|
|
which means it will raise).
|
2013-08-07 21:35:27 +08:00
|
|
|
"""
|
2013-09-27 18:33:06 +08:00
|
|
|
__tracebackhide__ = True
|
2013-10-04 00:25:03 +08:00
|
|
|
import inspect
|
2013-09-27 18:33:06 +08:00
|
|
|
|
|
|
|
if value is notset:
|
2013-10-21 20:01:02 +08:00
|
|
|
if not isinstance(target, _basestring):
|
2013-09-27 18:33:06 +08:00
|
|
|
raise TypeError("use setattr(target, name, value) or "
|
|
|
|
"setattr(target, value) with target being a dotted "
|
|
|
|
"import string")
|
|
|
|
value = name
|
2015-05-20 04:59:49 +08:00
|
|
|
name, target = derive_importpath(target, raising)
|
2013-09-27 18:33:06 +08:00
|
|
|
|
|
|
|
oldval = getattr(target, name, notset)
|
2009-09-07 23:53:50 +08:00
|
|
|
if raising and oldval is notset:
|
2013-09-27 18:33:06 +08:00
|
|
|
raise AttributeError("%r has no attribute %r" %(target, name))
|
2012-09-26 00:15:13 +08:00
|
|
|
|
|
|
|
# avoid class descriptors like staticmethod/classmethod
|
2013-09-27 18:33:06 +08:00
|
|
|
if inspect.isclass(target):
|
|
|
|
oldval = target.__dict__.get(name, notset)
|
|
|
|
self._setattr.insert(0, (target, name, oldval))
|
|
|
|
setattr(target, name, value)
|
|
|
|
|
|
|
|
def delattr(self, target, name=notset, raising=True):
|
2015-01-09 09:15:22 +08:00
|
|
|
""" Delete attribute ``name`` from ``target``, by default raise
|
2013-09-27 18:33:06 +08:00
|
|
|
AttributeError it the attribute did not previously exist.
|
|
|
|
|
|
|
|
If no ``name`` is specified and ``target`` is a string
|
|
|
|
it will be interpreted as a dotted import path with the
|
|
|
|
last part being the attribute name.
|
|
|
|
|
2015-01-09 09:15:22 +08:00
|
|
|
If ``raising`` is set to False, no exception will be raised if the
|
|
|
|
attribute is missing.
|
2013-09-27 18:33:06 +08:00
|
|
|
"""
|
|
|
|
__tracebackhide__ = True
|
|
|
|
if name is notset:
|
2013-10-22 17:26:29 +08:00
|
|
|
if not isinstance(target, _basestring):
|
2013-09-27 18:33:06 +08:00
|
|
|
raise TypeError("use delattr(target, name) or "
|
|
|
|
"delattr(target) with target being a dotted "
|
|
|
|
"import string")
|
2015-05-20 04:59:49 +08:00
|
|
|
name, target = derive_importpath(target, raising)
|
2013-09-27 18:33:06 +08:00
|
|
|
|
|
|
|
if not hasattr(target, name):
|
2009-08-22 18:45:58 +08:00
|
|
|
if raising:
|
2010-07-27 03:15:15 +08:00
|
|
|
raise AttributeError(name)
|
2009-08-22 18:45:58 +08:00
|
|
|
else:
|
2013-09-27 18:33:06 +08:00
|
|
|
self._setattr.insert(0, (target, name,
|
|
|
|
getattr(target, name, notset)))
|
|
|
|
delattr(target, name)
|
2009-08-22 18:45:58 +08:00
|
|
|
|
|
|
|
def setitem(self, dic, name, value):
|
2015-01-09 09:15:22 +08:00
|
|
|
""" Set dictionary entry ``name`` to value. """
|
2009-08-22 18:45:58 +08:00
|
|
|
self._setitem.insert(0, (dic, name, dic.get(name, notset)))
|
|
|
|
dic[name] = value
|
|
|
|
|
|
|
|
def delitem(self, dic, name, raising=True):
|
2015-01-09 09:15:22 +08:00
|
|
|
""" Delete ``name`` from dict. Raise KeyError if it doesn't exist.
|
|
|
|
|
|
|
|
If ``raising`` is set to False, no exception will be raised if the
|
|
|
|
key is missing.
|
|
|
|
"""
|
2009-08-22 18:45:58 +08:00
|
|
|
if name not in dic:
|
|
|
|
if raising:
|
2010-07-27 03:15:15 +08:00
|
|
|
raise KeyError(name)
|
|
|
|
else:
|
2009-08-22 18:45:58 +08:00
|
|
|
self._setitem.insert(0, (dic, name, dic.get(name, notset)))
|
|
|
|
del dic[name]
|
2009-02-27 18:18:27 +08:00
|
|
|
|
2009-08-14 02:10:12 +08:00
|
|
|
def setenv(self, name, value, prepend=None):
|
2015-01-09 09:15:22 +08:00
|
|
|
""" Set environment variable ``name`` to ``value``. If ``prepend``
|
2010-11-06 18:38:53 +08:00
|
|
|
is a character, read the current environment variable value
|
2010-10-11 05:45:45 +08:00
|
|
|
and prepend the ``value`` adjoined with the ``prepend`` character."""
|
2009-08-14 02:10:12 +08:00
|
|
|
value = str(value)
|
|
|
|
if prepend and name in os.environ:
|
|
|
|
value = value + prepend + os.environ[name]
|
|
|
|
self.setitem(os.environ, name, value)
|
2009-03-17 17:18:38 +08:00
|
|
|
|
2009-08-22 18:45:58 +08:00
|
|
|
def delenv(self, name, raising=True):
|
2015-01-09 09:15:22 +08:00
|
|
|
""" Delete ``name`` from the environment. Raise KeyError it does not
|
|
|
|
exist.
|
|
|
|
|
|
|
|
If ``raising`` is set to False, no exception will be raised if the
|
|
|
|
environment variable is missing.
|
|
|
|
"""
|
2009-08-22 18:45:58 +08:00
|
|
|
self.delitem(os.environ, name, raising=raising)
|
|
|
|
|
2009-09-06 05:21:58 +08:00
|
|
|
def syspath_prepend(self, path):
|
2015-01-09 09:15:22 +08:00
|
|
|
""" Prepend ``path`` to ``sys.path`` list of import locations. """
|
2009-09-06 05:21:58 +08:00
|
|
|
if not hasattr(self, '_savesyspath'):
|
|
|
|
self._savesyspath = sys.path[:]
|
|
|
|
sys.path.insert(0, str(path))
|
|
|
|
|
2012-01-04 19:43:19 +08:00
|
|
|
def chdir(self, path):
|
2015-05-01 12:13:06 +08:00
|
|
|
""" Change the current working directory to the specified path.
|
|
|
|
Path can be a string or a py.path.local object.
|
2012-01-06 22:25:57 +08:00
|
|
|
"""
|
2012-01-04 19:43:19 +08:00
|
|
|
if self._cwd is None:
|
|
|
|
self._cwd = os.getcwd()
|
|
|
|
if hasattr(path, "chdir"):
|
|
|
|
path.chdir()
|
|
|
|
else:
|
|
|
|
os.chdir(path)
|
|
|
|
|
2009-09-05 22:54:52 +08:00
|
|
|
def undo(self):
|
2015-01-09 09:15:22 +08:00
|
|
|
""" Undo previous changes. This call consumes the
|
|
|
|
undo stack. Calling it a second time has no effect unless
|
2015-08-30 10:53:57 +08:00
|
|
|
you do more monkeypatching after the undo call.
|
|
|
|
|
2015-09-14 03:49:01 +08:00
|
|
|
There is generally no need to call `undo()`, since it is
|
2015-08-30 10:53:57 +08:00
|
|
|
called automatically during tear-down.
|
|
|
|
|
|
|
|
Note that the same `monkeypatch` fixture is used across a
|
2015-08-30 13:00:00 +08:00
|
|
|
single test function invocation. If `monkeypatch` is used both by
|
2015-09-14 03:49:01 +08:00
|
|
|
the test function itself and one of the test fixtures,
|
2015-08-30 10:53:57 +08:00
|
|
|
calling `undo()` will undo all of the changes made in
|
|
|
|
both functions.
|
|
|
|
"""
|
2009-02-27 18:18:27 +08:00
|
|
|
for obj, name, value in self._setattr:
|
|
|
|
if value is not notset:
|
|
|
|
setattr(obj, name, value)
|
2009-03-04 01:42:32 +08:00
|
|
|
else:
|
|
|
|
delattr(obj, name)
|
2009-09-05 22:54:52 +08:00
|
|
|
self._setattr[:] = []
|
2009-02-27 18:18:27 +08:00
|
|
|
for dictionary, name, value in self._setitem:
|
|
|
|
if value is notset:
|
2011-12-28 23:49:13 +08:00
|
|
|
try:
|
|
|
|
del dictionary[name]
|
|
|
|
except KeyError:
|
|
|
|
pass # was already deleted, so we have the desired state
|
2009-02-27 18:18:27 +08:00
|
|
|
else:
|
|
|
|
dictionary[name] = value
|
2009-09-05 22:54:52 +08:00
|
|
|
self._setitem[:] = []
|
2009-09-06 05:21:58 +08:00
|
|
|
if hasattr(self, '_savesyspath'):
|
|
|
|
sys.path[:] = self._savesyspath
|
2012-01-04 19:42:23 +08:00
|
|
|
del self._savesyspath
|
2012-01-04 19:43:19 +08:00
|
|
|
|
|
|
|
if self._cwd is not None:
|
|
|
|
os.chdir(self._cwd)
|
|
|
|
self._cwd = None
|