| 1 |
""" monkeypatching and mocking functionality. """ |
| 2 |
|
| 3 |
import os, sys |
| 4 |
import re |
| 5 |
|
| 6 |
from py.builtin import _basestring |
| 7 |
|
| 8 |
RE_IMPORT_ERROR_NAME = re.compile("^No module named (.*)$") |
| 9 |
|
| 10 |
|
| 11 |
def pytest_funcarg__monkeypatch(request): |
| 12 |
"""The returned ``monkeypatch`` funcarg provides these |
| 13 |
helper methods to modify objects, dictionaries or os.environ:: |
| 14 |
|
| 15 |
monkeypatch.setattr(obj, name, value, raising=True) |
| 16 |
monkeypatch.delattr(obj, name, raising=True) |
| 17 |
monkeypatch.setitem(mapping, name, value) |
| 18 |
monkeypatch.delitem(obj, name, raising=True) |
| 19 |
monkeypatch.setenv(name, value, prepend=False) |
| 20 |
monkeypatch.delenv(name, value, raising=True) |
| 21 |
monkeypatch.syspath_prepend(path) |
| 22 |
monkeypatch.chdir(path) |
| 23 |
|
| 24 |
All modifications will be undone after the requesting |
| 25 |
test function has finished. The ``raising`` |
| 26 |
parameter determines if a KeyError or AttributeError |
| 27 |
will be raised if the set/deletion operation has no target. |
| 28 |
""" |
| 29 |
mpatch = monkeypatch() |
| 30 |
request.addfinalizer(mpatch.undo) |
| 31 |
return mpatch |
| 32 |
|
| 33 |
|
| 34 |
def resolve(name): |
| 35 |
|
| 36 |
parts = name.split('.') |
| 37 |
|
| 38 |
used = parts.pop(0) |
| 39 |
found = __import__(used) |
| 40 |
for part in parts: |
| 41 |
used += '.' + part |
| 42 |
try: |
| 43 |
found = getattr(found, part) |
| 44 |
except AttributeError: |
| 45 |
pass |
| 46 |
else: |
| 47 |
continue |
| 48 |
|
| 49 |
|
| 50 |
try: |
| 51 |
__import__(used) |
| 52 |
except ImportError as ex: |
| 53 |
|
| 54 |
expected = str(ex).split()[-1] |
| 55 |
if expected == used: |
| 56 |
raise |
| 57 |
else: |
| 58 |
raise ImportError( |
| 59 |
'import error in %s: %s' % (used, ex) |
| 60 |
) |
| 61 |
found = annotated_getattr(found, part, used) |
| 62 |
return found |
| 63 |
|
| 64 |
|
| 65 |
def annotated_getattr(obj, name, ann): |
| 66 |
try: |
| 67 |
obj = getattr(obj, name) |
| 68 |
except AttributeError: |
| 69 |
raise AttributeError( |
| 70 |
'%r object at %s has no attribute %r' % ( |
| 71 |
type(obj).__name__, ann, name |
| 72 |
) |
| 73 |
) |
| 74 |
return obj |
| 75 |
|
| 76 |
|
| 77 |
def derive_importpath(import_path, raising): |
| 78 |
if not isinstance(import_path, _basestring) or "." not in import_path: |
| 79 |
raise TypeError("must be absolute import path string, not %r" % |
| 80 |
(import_path,)) |
| 81 |
module, attr = import_path.rsplit('.', 1) |
| 82 |
target = resolve(module) |
| 83 |
if raising: |
| 84 |
annotated_getattr(target, attr, ann=module) |
| 85 |
return attr, target |
| 86 |
|
| 87 |
|
| 88 |
class Notset: |
| 89 |
def __repr__(self): |
| 90 |
return "<notset>" |
| 91 |
|
| 92 |
|
| 93 |
notset = Notset() |
| 94 |
|
| 95 |
|
| 96 |
class monkeypatch: |
| 97 |
""" Object keeping a record of setattr/item/env/syspath changes. """ |
| 98 |
|
| 99 |
def __init__(self): |
| 100 |
self._setattr = [] |
| 101 |
self._setitem = [] |
| 102 |
self._cwd = None |
| 103 |
self._savesyspath = None |
| 104 |
|
| 105 |
def setattr(self, target, name, value=notset, raising=True): |
| 106 |
""" Set attribute value on target, memorizing the old value. |
| 107 |
By default raise AttributeError if the attribute did not exist. |
| 108 |
|
| 109 |
For convenience you can specify a string as ``target`` which |
| 110 |
will be interpreted as a dotted import path, with the last part |
| 111 |
being the attribute name. Example: |
| 112 |
``monkeypatch.setattr("os.getcwd", lambda x: "/")`` |
| 113 |
would set the ``getcwd`` function of the ``os`` module. |
| 114 |
|
| 115 |
The ``raising`` value determines if the setattr should fail |
| 116 |
if the attribute is not already present (defaults to True |
| 117 |
which means it will raise). |
| 118 |
""" |
| 119 |
__tracebackhide__ = True |
| 120 |
import inspect |
| 121 |
|
| 122 |
if value is notset: |
| 123 |
if not isinstance(target, _basestring): |
| 124 |
raise TypeError("use setattr(target, name, value) or " |
| 125 |
"setattr(target, value) with target being a dotted " |
| 126 |
"import string") |
| 127 |
value = name |
| 128 |
name, target = derive_importpath(target, raising) |
| 129 |
|
| 130 |
oldval = getattr(target, name, notset) |
| 131 |
if raising and oldval is notset: |
| 132 |
raise AttributeError("%r has no attribute %r" % (target, name)) |
| 133 |
|
| 134 |
|
| 135 |
if inspect.isclass(target): |
| 136 |
oldval = target.__dict__.get(name, notset) |
| 137 |
self._setattr.append((target, name, oldval)) |
| 138 |
setattr(target, name, value) |
| 139 |
|
| 140 |
def delattr(self, target, name=notset, raising=True): |
| 141 |
""" Delete attribute ``name`` from ``target``, by default raise |
| 142 |
AttributeError it the attribute did not previously exist. |
| 143 |
|
| 144 |
If no ``name`` is specified and ``target`` is a string |
| 145 |
it will be interpreted as a dotted import path with the |
| 146 |
last part being the attribute name. |
| 147 |
|
| 148 |
If ``raising`` is set to False, no exception will be raised if the |
| 149 |
attribute is missing. |
| 150 |
""" |
| 151 |
__tracebackhide__ = True |
| 152 |
if name is notset: |
| 153 |
if not isinstance(target, _basestring): |
| 154 |
raise TypeError("use delattr(target, name) or " |
| 155 |
"delattr(target) with target being a dotted " |
| 156 |
"import string") |
| 157 |
name, target = derive_importpath(target, raising) |
| 158 |
|
| 159 |
if not hasattr(target, name): |
| 160 |
if raising: |
| 161 |
raise AttributeError(name) |
| 162 |
else: |
| 163 |
self._setattr.append((target, name, getattr(target, name, notset))) |
| 164 |
delattr(target, name) |
| 165 |
|
| 166 |
def setitem(self, dic, name, value): |
| 167 |
""" Set dictionary entry ``name`` to value. """ |
| 168 |
self._setitem.append((dic, name, dic.get(name, notset))) |
| 169 |
dic[name] = value |
| 170 |
|
| 171 |
def delitem(self, dic, name, raising=True): |
| 172 |
""" Delete ``name`` from dict. Raise KeyError if it doesn't exist. |
| 173 |
|
| 174 |
If ``raising`` is set to False, no exception will be raised if the |
| 175 |
key is missing. |
| 176 |
""" |
| 177 |
if name not in dic: |
| 178 |
if raising: |
| 179 |
raise KeyError(name) |
| 180 |
else: |
| 181 |
self._setitem.append((dic, name, dic.get(name, notset))) |
| 182 |
del dic[name] |
| 183 |
|
| 184 |
def setenv(self, name, value, prepend=None): |
| 185 |
""" Set environment variable ``name`` to ``value``. If ``prepend`` |
| 186 |
is a character, read the current environment variable value |
| 187 |
and prepend the ``value`` adjoined with the ``prepend`` character.""" |
| 188 |
value = str(value) |
| 189 |
if prepend and name in os.environ: |
| 190 |
value = value + prepend + os.environ[name] |
| 191 |
self.setitem(os.environ, name, value) |
| 192 |
|
| 193 |
def delenv(self, name, raising=True): |
| 194 |
""" Delete ``name`` from the environment. Raise KeyError it does not |
| 195 |
exist. |
| 196 |
|
| 197 |
If ``raising`` is set to False, no exception will be raised if the |
| 198 |
environment variable is missing. |
| 199 |
""" |
| 200 |
self.delitem(os.environ, name, raising=raising) |
| 201 |
|
| 202 |
def syspath_prepend(self, path): |
| 203 |
""" Prepend ``path`` to ``sys.path`` list of import locations. """ |
| 204 |
if self._savesyspath is None: |
| 205 |
self._savesyspath = sys.path[:] |
| 206 |
sys.path.insert(0, str(path)) |
| 207 |
|
| 208 |
def chdir(self, path): |
| 209 |
""" Change the current working directory to the specified path. |
| 210 |
Path can be a string or a py.path.local object. |
| 211 |
""" |
| 212 |
if self._cwd is None: |
| 213 |
self._cwd = os.getcwd() |
| 214 |
if hasattr(path, "chdir"): |
| 215 |
path.chdir() |
| 216 |
else: |
| 217 |
os.chdir(path) |
| 218 |
|
| 219 |
def undo(self): |
| 220 |
""" Undo previous changes. This call consumes the |
| 221 |
undo stack. Calling it a second time has no effect unless |
| 222 |
you do more monkeypatching after the undo call. |
| 223 |
|
| 224 |
There is generally no need to call `undo()`, since it is |
| 225 |
called automatically during tear-down. |
| 226 |
|
| 227 |
Note that the same `monkeypatch` fixture is used across a |
| 228 |
single test function invocation. If `monkeypatch` is used both by |
| 229 |
the test function itself and one of the test fixtures, |
| 230 |
calling `undo()` will undo all of the changes made in |
| 231 |
both functions. |
| 232 |
""" |
| 233 |
for obj, name, value in reversed(self._setattr): |
| 234 |
if value is not notset: |
| 235 |
setattr(obj, name, value) |
| 236 |
else: |
| 237 |
delattr(obj, name) |
| 238 |
self._setattr[:] = [] |
| 239 |
for dictionary, name, value in reversed(self._setitem): |
| 240 |
if value is notset: |
| 241 |
try: |
| 242 |
del dictionary[name] |
| 243 |
except KeyError: |
| 244 |
pass |
| 245 |
else: |
| 246 |
dictionary[name] = value |
| 247 |
self._setitem[:] = [] |
| 248 |
if self._savesyspath is not None: |
| 249 |
sys.path[:] = self._savesyspath |
| 250 |
self._savesyspath = None |
| 251 |
|
| 252 |
if self._cwd is not None: |
| 253 |
os.chdir(self._cwd) |
| 254 |
self._cwd = None |