2010-10-11 05:45:45 +08:00
|
|
|
""" monkeypatching and mocking functionality. """
|
2017-03-17 09:21:30 +08:00
|
|
|
from __future__ import absolute_import, division, print_function
|
2009-07-21 00:54:08 +08:00
|
|
|
|
2017-03-16 01:00:59 +08:00
|
|
|
import os
|
|
|
|
import sys
|
2015-12-28 05:42:42 +08:00
|
|
|
import re
|
2018-04-11 01:17:51 +08:00
|
|
|
from contextlib import contextmanager
|
|
|
|
|
2017-08-03 01:33:52 +08:00
|
|
|
import six
|
2017-03-16 01:00:59 +08:00
|
|
|
from _pytest.fixtures import fixture
|
2016-07-12 09:03:53 +08:00
|
|
|
|
2015-12-28 05:42:42 +08:00
|
|
|
RE_IMPORT_ERROR_NAME = re.compile("^No module named (.*)$")
|
|
|
|
|
|
|
|
|
2017-03-16 01:00:59 +08:00
|
|
|
@fixture
|
2017-01-04 21:31:44 +08:00
|
|
|
def monkeypatch():
|
2016-07-12 09:03:53 +08:00
|
|
|
"""The returned ``monkeypatch`` fixture 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
|
2016-07-21 09:05:49 +08:00
|
|
|
test function or fixture 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
|
|
|
"""
|
2016-07-12 09:03:53 +08:00
|
|
|
mpatch = MonkeyPatch()
|
2017-01-04 21:31:44 +08:00
|
|
|
yield mpatch
|
|
|
|
mpatch.undo()
|
2009-02-27 18:18:27 +08:00
|
|
|
|
2013-09-27 18:33:06 +08:00
|
|
|
|
2016-01-24 02:12:10 +08:00
|
|
|
def resolve(name):
|
|
|
|
# simplified from zope.dottedname
|
2018-05-23 22:48:46 +08:00
|
|
|
parts = name.split(".")
|
2016-01-24 02:12:10 +08:00
|
|
|
|
|
|
|
used = parts.pop(0)
|
|
|
|
found = __import__(used)
|
|
|
|
for part in parts:
|
2018-05-23 22:48:46 +08:00
|
|
|
used += "." + part
|
2016-01-24 02:12:10 +08:00
|
|
|
try:
|
|
|
|
found = getattr(found, part)
|
|
|
|
except AttributeError:
|
2016-01-24 19:28:14 +08:00
|
|
|
pass
|
|
|
|
else:
|
|
|
|
continue
|
|
|
|
# we use explicit un-nesting of the handling block in order
|
|
|
|
# to avoid nested exceptions on python 3
|
|
|
|
try:
|
|
|
|
__import__(used)
|
|
|
|
except ImportError as ex:
|
|
|
|
# str is used for py2 vs py3
|
|
|
|
expected = str(ex).split()[-1]
|
|
|
|
if expected == used:
|
|
|
|
raise
|
|
|
|
else:
|
2018-05-23 22:48:46 +08:00
|
|
|
raise ImportError("import error in %s: %s" % (used, ex))
|
2016-01-24 19:28:14 +08:00
|
|
|
found = annotated_getattr(found, part, used)
|
2016-01-24 02:12:10 +08:00
|
|
|
return found
|
|
|
|
|
|
|
|
|
2016-01-24 02:31:17 +08:00
|
|
|
def annotated_getattr(obj, name, ann):
|
|
|
|
try:
|
|
|
|
obj = getattr(obj, name)
|
|
|
|
except AttributeError:
|
|
|
|
raise AttributeError(
|
2018-05-23 22:48:46 +08:00
|
|
|
"%r object at %s has no attribute %r" % (type(obj).__name__, ann, name)
|
2016-01-24 02:31:17 +08:00
|
|
|
)
|
|
|
|
return obj
|
|
|
|
|
|
|
|
|
2015-05-20 04:59:49 +08:00
|
|
|
def derive_importpath(import_path, raising):
|
2017-08-03 01:33:52 +08:00
|
|
|
if not isinstance(import_path, six.string_types) or "." not in import_path:
|
2018-05-23 22:48:46 +08:00
|
|
|
raise TypeError("must be absolute import path string, not %r" % (import_path,))
|
|
|
|
module, attr = import_path.rsplit(".", 1)
|
2016-01-24 02:12:10 +08:00
|
|
|
target = resolve(module)
|
|
|
|
if raising:
|
2016-01-24 02:31:17 +08:00
|
|
|
annotated_getattr(target, attr, ann=module)
|
2016-01-24 02:12:10 +08:00
|
|
|
return attr, target
|
2013-09-27 18:33:06 +08:00
|
|
|
|
|
|
|
|
2018-01-25 04:23:42 +08:00
|
|
|
class Notset(object):
|
2018-05-23 22:48:46 +08:00
|
|
|
|
2014-05-10 19:49:24 +08:00
|
|
|
def __repr__(self):
|
|
|
|
return "<notset>"
|
|
|
|
|
2016-01-24 01:08:18 +08:00
|
|
|
|
2014-05-10 19:49:24 +08:00
|
|
|
notset = Notset()
|
2009-02-27 18:18:27 +08:00
|
|
|
|
2016-01-24 01:08:18 +08:00
|
|
|
|
2018-01-25 04:23:42 +08:00
|
|
|
class MonkeyPatch(object):
|
2016-07-21 09:05:49 +08:00
|
|
|
""" Object returned by the ``monkeypatch`` fixture keeping a record of setattr/item/env/syspath changes.
|
|
|
|
"""
|
2016-01-24 01:08:18 +08:00
|
|
|
|
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
|
2015-09-14 13:42:23 +08:00
|
|
|
self._savesyspath = None
|
2009-02-27 18:18:27 +08:00
|
|
|
|
2018-04-11 01:17:51 +08:00
|
|
|
@contextmanager
|
|
|
|
def context(self):
|
2018-04-13 21:00:07 +08:00
|
|
|
"""
|
|
|
|
Context manager that returns a new :class:`MonkeyPatch` object which
|
|
|
|
undoes any patching done inside the ``with`` block upon exit:
|
|
|
|
|
|
|
|
.. code-block:: python
|
|
|
|
|
|
|
|
import functools
|
|
|
|
def test_partial(monkeypatch):
|
|
|
|
with monkeypatch.context() as m:
|
|
|
|
m.setattr(functools, "partial", 3)
|
|
|
|
|
|
|
|
Useful in situations where it is desired to undo some patches before the test ends,
|
|
|
|
such as mocking ``stdlib`` functions that might break pytest itself if mocked (for examples
|
|
|
|
of this see `#3290 <https://github.com/pytest-dev/pytest/issues/3290>`_.
|
|
|
|
"""
|
2018-04-11 01:17:51 +08:00
|
|
|
m = MonkeyPatch()
|
|
|
|
try:
|
|
|
|
yield m
|
|
|
|
finally:
|
|
|
|
m.undo()
|
|
|
|
|
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:
|
2018-03-12 22:19:26 +08:00
|
|
|
``monkeypatch.setattr("os.getcwd", lambda: "/")``
|
2013-09-27 18:33:06 +08:00
|
|
|
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:
|
2017-08-03 01:33:52 +08:00
|
|
|
if not isinstance(target, six.string_types):
|
2018-05-23 22:48:46 +08:00
|
|
|
raise TypeError(
|
|
|
|
"use setattr(target, name, value) or "
|
|
|
|
"setattr(target, value) with target being a dotted "
|
|
|
|
"import string"
|
|
|
|
)
|
2013-09-27 18:33:06 +08:00
|
|
|
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:
|
2016-01-24 01:08:18 +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)
|
2015-12-30 08:02:18 +08:00
|
|
|
self._setattr.append((target, name, oldval))
|
2013-09-27 18:33:06 +08:00
|
|
|
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:
|
2017-08-03 01:33:52 +08:00
|
|
|
if not isinstance(target, six.string_types):
|
2018-05-23 22:48:46 +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:
|
2015-12-30 08:02:18 +08:00
|
|
|
self._setattr.append((target, name, getattr(target, name, notset)))
|
2013-09-27 18:33:06 +08:00
|
|
|
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. """
|
2015-12-30 08:02:18 +08:00
|
|
|
self._setitem.append((dic, name, dic.get(name, notset)))
|
2009-08-22 18:45:58 +08:00
|
|
|
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:
|
2015-12-30 08:02:18 +08:00
|
|
|
self._setitem.append((dic, name, dic.get(name, notset)))
|
2009-08-22 18:45:58 +08:00
|
|
|
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. """
|
2015-09-14 13:42:23 +08:00
|
|
|
if self._savesyspath is None:
|
2009-09-06 05:21:58 +08:00
|
|
|
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.
|
2016-07-22 18:39:06 +08:00
|
|
|
|
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.
|
2016-07-22 18:39:06 +08:00
|
|
|
|
2015-08-30 10:53:57 +08:00
|
|
|
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.
|
|
|
|
"""
|
2015-12-30 08:02:18 +08:00
|
|
|
for obj, name, value in reversed(self._setattr):
|
2009-02-27 18:18:27 +08:00
|
|
|
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[:] = []
|
2015-12-30 08:02:18 +08:00
|
|
|
for dictionary, name, value in reversed(self._setitem):
|
2009-02-27 18:18:27 +08:00
|
|
|
if value is notset:
|
2011-12-28 23:49:13 +08:00
|
|
|
try:
|
|
|
|
del dictionary[name]
|
|
|
|
except KeyError:
|
2016-01-24 01:08:18 +08:00
|
|
|
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[:] = []
|
2015-09-14 13:42:23 +08:00
|
|
|
if self._savesyspath is not None:
|
2009-09-06 05:21:58 +08:00
|
|
|
sys.path[:] = self._savesyspath
|
2015-09-14 13:42:23 +08:00
|
|
|
self._savesyspath = None
|
2012-01-04 19:43:19 +08:00
|
|
|
|
|
|
|
if self._cwd is not None:
|
|
|
|
os.chdir(self._cwd)
|
|
|
|
self._cwd = None
|