| 1 |
""" generic mechanism for marking and selecting python functions. """ |
| 2 |
import inspect |
| 3 |
|
| 4 |
|
| 5 |
class MarkerError(Exception): |
| 6 |
|
| 7 |
"""Error in use of a pytest marker/attribute.""" |
| 8 |
|
| 9 |
|
| 10 |
def pytest_namespace(): |
| 11 |
return {'mark': MarkGenerator()} |
| 12 |
|
| 13 |
|
| 14 |
def pytest_addoption(parser): |
| 15 |
group = parser.getgroup("general") |
| 16 |
group._addoption( |
| 17 |
'-k', |
| 18 |
action="store", dest="keyword", default='', metavar="EXPRESSION", |
| 19 |
help="only run tests which match the given substring expression. " |
| 20 |
"An expression is a python evaluatable expression " |
| 21 |
"where all names are substring-matched against test names " |
| 22 |
"and their parent classes. Example: -k 'test_method or test " |
| 23 |
"other' matches all test functions and classes whose name " |
| 24 |
"contains 'test_method' or 'test_other'. " |
| 25 |
"Additionally keywords are matched to classes and functions " |
| 26 |
"containing extra names in their 'extra_keyword_matches' set, " |
| 27 |
"as well as functions which have names assigned directly to them." |
| 28 |
) |
| 29 |
|
| 30 |
group._addoption( |
| 31 |
"-m", |
| 32 |
action="store", dest="markexpr", default="", metavar="MARKEXPR", |
| 33 |
help="only run tests matching given mark expression. " |
| 34 |
"example: -m 'mark1 and not mark2'." |
| 35 |
) |
| 36 |
|
| 37 |
group.addoption( |
| 38 |
"--markers", action="store_true", |
| 39 |
help="show markers (builtin, plugin and per-project ones)." |
| 40 |
) |
| 41 |
|
| 42 |
parser.addini("markers", "markers for test functions", 'linelist') |
| 43 |
|
| 44 |
|
| 45 |
def pytest_cmdline_main(config): |
| 46 |
import _pytest.config |
| 47 |
if config.option.markers: |
| 48 |
config._do_configure() |
| 49 |
tw = _pytest.config.create_terminal_writer(config) |
| 50 |
for line in config.getini("markers"): |
| 51 |
name, rest = line.split(":", 1) |
| 52 |
tw.write("@pytest.mark.%s:" % name, bold=True) |
| 53 |
tw.line(rest) |
| 54 |
tw.line() |
| 55 |
config._ensure_unconfigure() |
| 56 |
return 0 |
| 57 |
pytest_cmdline_main.tryfirst = True |
| 58 |
|
| 59 |
|
| 60 |
def pytest_collection_modifyitems(items, config): |
| 61 |
keywordexpr = config.option.keyword.lstrip() |
| 62 |
matchexpr = config.option.markexpr |
| 63 |
if not keywordexpr and not matchexpr: |
| 64 |
return |
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
if keywordexpr.startswith("-"): |
| 69 |
keywordexpr = "not " + keywordexpr[1:] |
| 70 |
selectuntil = False |
| 71 |
if keywordexpr[-1:] == ":": |
| 72 |
selectuntil = True |
| 73 |
keywordexpr = keywordexpr[:-1] |
| 74 |
|
| 75 |
remaining = [] |
| 76 |
deselected = [] |
| 77 |
for colitem in items: |
| 78 |
if keywordexpr and not matchkeyword(colitem, keywordexpr): |
| 79 |
deselected.append(colitem) |
| 80 |
else: |
| 81 |
if selectuntil: |
| 82 |
keywordexpr = None |
| 83 |
if matchexpr: |
| 84 |
if not matchmark(colitem, matchexpr): |
| 85 |
deselected.append(colitem) |
| 86 |
continue |
| 87 |
remaining.append(colitem) |
| 88 |
|
| 89 |
if deselected: |
| 90 |
config.hook.pytest_deselected(items=deselected) |
| 91 |
items[:] = remaining |
| 92 |
|
| 93 |
|
| 94 |
class MarkMapping: |
| 95 |
"""Provides a local mapping for markers where item access |
| 96 |
resolves to True if the marker is present. """ |
| 97 |
def __init__(self, keywords): |
| 98 |
mymarks = set() |
| 99 |
for key, value in keywords.items(): |
| 100 |
if isinstance(value, MarkInfo) or isinstance(value, MarkDecorator): |
| 101 |
mymarks.add(key) |
| 102 |
self._mymarks = mymarks |
| 103 |
|
| 104 |
def __getitem__(self, name): |
| 105 |
return name in self._mymarks |
| 106 |
|
| 107 |
|
| 108 |
class KeywordMapping: |
| 109 |
"""Provides a local mapping for keywords. |
| 110 |
Given a list of names, map any substring of one of these names to True. |
| 111 |
""" |
| 112 |
def __init__(self, names): |
| 113 |
self._names = names |
| 114 |
|
| 115 |
def __getitem__(self, subname): |
| 116 |
for name in self._names: |
| 117 |
if subname in name: |
| 118 |
return True |
| 119 |
return False |
| 120 |
|
| 121 |
|
| 122 |
def matchmark(colitem, markexpr): |
| 123 |
"""Tries to match on any marker names, attached to the given colitem.""" |
| 124 |
return eval(markexpr, {}, MarkMapping(colitem.keywords)) |
| 125 |
|
| 126 |
|
| 127 |
def matchkeyword(colitem, keywordexpr): |
| 128 |
"""Tries to match given keyword expression to given collector item. |
| 129 |
|
| 130 |
Will match on the name of colitem, including the names of its parents. |
| 131 |
Only matches names of items which are either a :class:`Class` or a |
| 132 |
:class:`Function`. |
| 133 |
Additionally, matches on names in the 'extra_keyword_matches' set of |
| 134 |
any item, as well as names directly assigned to test functions. |
| 135 |
""" |
| 136 |
mapped_names = set() |
| 137 |
|
| 138 |
|
| 139 |
import pytest |
| 140 |
for item in colitem.listchain(): |
| 141 |
if not isinstance(item, pytest.Instance): |
| 142 |
mapped_names.add(item.name) |
| 143 |
|
| 144 |
|
| 145 |
for name in colitem.listextrakeywords(): |
| 146 |
mapped_names.add(name) |
| 147 |
|
| 148 |
|
| 149 |
if hasattr(colitem, 'function'): |
| 150 |
for name in colitem.function.__dict__: |
| 151 |
mapped_names.add(name) |
| 152 |
|
| 153 |
mapping = KeywordMapping(mapped_names) |
| 154 |
if " " not in keywordexpr: |
| 155 |
|
| 156 |
return mapping[keywordexpr] |
| 157 |
elif keywordexpr.startswith("not ") and " " not in keywordexpr[4:]: |
| 158 |
return not mapping[keywordexpr[4:]] |
| 159 |
return eval(keywordexpr, {}, mapping) |
| 160 |
|
| 161 |
|
| 162 |
def pytest_configure(config): |
| 163 |
import pytest |
| 164 |
if config.option.strict: |
| 165 |
pytest.mark._config = config |
| 166 |
|
| 167 |
|
| 168 |
class MarkGenerator: |
| 169 |
""" Factory for :class:`MarkDecorator` objects - exposed as |
| 170 |
a ``pytest.mark`` singleton instance. Example:: |
| 171 |
|
| 172 |
import pytest |
| 173 |
@pytest.mark.slowtest |
| 174 |
def test_function(): |
| 175 |
pass |
| 176 |
|
| 177 |
will set a 'slowtest' :class:`MarkInfo` object |
| 178 |
on the ``test_function`` object. """ |
| 179 |
|
| 180 |
def __getattr__(self, name): |
| 181 |
if name[0] == "_": |
| 182 |
raise AttributeError("Marker name must NOT start with underscore") |
| 183 |
if hasattr(self, '_config'): |
| 184 |
self._check(name) |
| 185 |
return MarkDecorator(name) |
| 186 |
|
| 187 |
def _check(self, name): |
| 188 |
try: |
| 189 |
if name in self._markers: |
| 190 |
return |
| 191 |
except AttributeError: |
| 192 |
pass |
| 193 |
self._markers = l = set() |
| 194 |
for line in self._config.getini("markers"): |
| 195 |
beginning = line.split(":", 1) |
| 196 |
x = beginning[0].split("(", 1)[0] |
| 197 |
l.add(x) |
| 198 |
if name not in self._markers: |
| 199 |
raise AttributeError("%r not a registered marker" % (name,)) |
| 200 |
|
| 201 |
def istestfunc(func): |
| 202 |
return hasattr(func, "__call__") and \ |
| 203 |
getattr(func, "__name__", "<lambda>") != "<lambda>" |
| 204 |
|
| 205 |
class MarkDecorator: |
| 206 |
""" A decorator for test functions and test classes. When applied |
| 207 |
it will create :class:`MarkInfo` objects which may be |
| 208 |
:ref:`retrieved by hooks as item keywords <excontrolskip>`. |
| 209 |
MarkDecorator instances are often created like this:: |
| 210 |
|
| 211 |
mark1 = pytest.mark.NAME # simple MarkDecorator |
| 212 |
mark2 = pytest.mark.NAME(name1=value) # parametrized MarkDecorator |
| 213 |
|
| 214 |
and can then be applied as decorators to test functions:: |
| 215 |
|
| 216 |
@mark2 |
| 217 |
def test_function(): |
| 218 |
pass |
| 219 |
|
| 220 |
When a MarkDecorator instance is called it does the following: |
| 221 |
1. If called with a single class as its only positional argument and no |
| 222 |
additional keyword arguments, it attaches itself to the class so it |
| 223 |
gets applied automatically to all test cases found in that class. |
| 224 |
2. If called with a single function as its only positional argument and |
| 225 |
no additional keyword arguments, it attaches a MarkInfo object to the |
| 226 |
function, containing all the arguments already stored internally in |
| 227 |
the MarkDecorator. |
| 228 |
3. When called in any other case, it performs a 'fake construction' call, |
| 229 |
i.e. it returns a new MarkDecorator instance with the original |
| 230 |
MarkDecorator's content updated with the arguments passed to this |
| 231 |
call. |
| 232 |
|
| 233 |
Note: The rules above prevent MarkDecorator objects from storing only a |
| 234 |
single function or class reference as their positional argument with no |
| 235 |
additional keyword or positional arguments. |
| 236 |
|
| 237 |
""" |
| 238 |
def __init__(self, name, args=None, kwargs=None): |
| 239 |
self.name = name |
| 240 |
self.args = args or () |
| 241 |
self.kwargs = kwargs or {} |
| 242 |
|
| 243 |
@property |
| 244 |
def markname(self): |
| 245 |
return self.name |
| 246 |
|
| 247 |
def __repr__(self): |
| 248 |
d = self.__dict__.copy() |
| 249 |
name = d.pop('name') |
| 250 |
return "<MarkDecorator %r %r>" % (name, d) |
| 251 |
|
| 252 |
def __call__(self, *args, **kwargs): |
| 253 |
""" if passed a single callable argument: decorate it with mark info. |
| 254 |
otherwise add *args/**kwargs in-place to mark information. """ |
| 255 |
if args and not kwargs: |
| 256 |
func = args[0] |
| 257 |
is_class = inspect.isclass(func) |
| 258 |
if len(args) == 1 and (istestfunc(func) or is_class): |
| 259 |
if is_class: |
| 260 |
if hasattr(func, 'pytestmark'): |
| 261 |
mark_list = func.pytestmark |
| 262 |
if not isinstance(mark_list, list): |
| 263 |
mark_list = [mark_list] |
| 264 |
|
| 265 |
|
| 266 |
mark_list = mark_list + [self] |
| 267 |
func.pytestmark = mark_list |
| 268 |
else: |
| 269 |
func.pytestmark = [self] |
| 270 |
else: |
| 271 |
holder = getattr(func, self.name, None) |
| 272 |
if holder is None: |
| 273 |
holder = MarkInfo( |
| 274 |
self.name, self.args, self.kwargs |
| 275 |
) |
| 276 |
setattr(func, self.name, holder) |
| 277 |
else: |
| 278 |
holder.add(self.args, self.kwargs) |
| 279 |
return func |
| 280 |
kw = self.kwargs.copy() |
| 281 |
kw.update(kwargs) |
| 282 |
args = self.args + args |
| 283 |
return self.__class__(self.name, args=args, kwargs=kw) |
| 284 |
|
| 285 |
|
| 286 |
class MarkInfo: |
| 287 |
""" Marking object created by :class:`MarkDecorator` instances. """ |
| 288 |
def __init__(self, name, args, kwargs): |
| 289 |
|
| 290 |
self.name = name |
| 291 |
|
| 292 |
self.args = args |
| 293 |
|
| 294 |
self.kwargs = kwargs.copy() |
| 295 |
self._arglist = [(args, kwargs.copy())] |
| 296 |
|
| 297 |
def __repr__(self): |
| 298 |
return "<MarkInfo %r args=%r kwargs=%r>" % ( |
| 299 |
self.name, self.args, self.kwargs |
| 300 |
) |
| 301 |
|
| 302 |
def add(self, args, kwargs): |
| 303 |
""" add a MarkInfo with the given args and kwargs. """ |
| 304 |
self._arglist.append((args, kwargs)) |
| 305 |
self.args += args |
| 306 |
self.kwargs.update(kwargs) |
| 307 |
|
| 308 |
def __iter__(self): |
| 309 |
""" yield MarkInfo objects each relating to a marking-call. """ |
| 310 |
for args, kwargs in self._arglist: |
| 311 |
yield MarkInfo(self.name, args, kwargs) |