| 1 |
""" Python test discovery, setup and run of test functions. """ |
| 2 |
import fnmatch |
| 3 |
import functools |
| 4 |
import inspect |
| 5 |
import re |
| 6 |
import types |
| 7 |
import sys |
| 8 |
|
| 9 |
import py |
| 10 |
import pytest |
| 11 |
from _pytest._code.code import TerminalRepr |
| 12 |
from _pytest.mark import MarkDecorator, MarkerError |
| 13 |
|
| 14 |
try: |
| 15 |
import enum |
| 16 |
except ImportError: |
| 17 |
|
| 18 |
enum = None |
| 19 |
|
| 20 |
import _pytest |
| 21 |
import _pytest._pluggy as pluggy |
| 22 |
|
| 23 |
cutdir2 = py.path.local(_pytest.__file__).dirpath() |
| 24 |
cutdir1 = py.path.local(pluggy.__file__.rstrip("oc")) |
| 25 |
|
| 26 |
|
| 27 |
NoneType = type(None) |
| 28 |
NOTSET = object() |
| 29 |
isfunction = inspect.isfunction |
| 30 |
isclass = inspect.isclass |
| 31 |
callable = py.builtin.callable |
| 32 |
|
| 33 |
exc_clear = getattr(sys, 'exc_clear', lambda: None) |
| 34 |
|
| 35 |
REGEX_TYPE = type(re.compile('')) |
| 36 |
|
| 37 |
_PY3 = sys.version_info > (3, 0) |
| 38 |
_PY2 = not _PY3 |
| 39 |
|
| 40 |
|
| 41 |
if hasattr(inspect, 'signature'): |
| 42 |
def _format_args(func): |
| 43 |
return str(inspect.signature(func)) |
| 44 |
else: |
| 45 |
def _format_args(func): |
| 46 |
return inspect.formatargspec(*inspect.getargspec(func)) |
| 47 |
|
| 48 |
if sys.version_info[:2] == (2, 6): |
| 49 |
def isclass(object): |
| 50 |
""" Return true if the object is a class. Overrides inspect.isclass for |
| 51 |
python 2.6 because it will return True for objects which always return |
| 52 |
something on __getattr__ calls (see #1035). |
| 53 |
Backport of https://hg.python.org/cpython/rev/35bf8f7a8edc |
| 54 |
""" |
| 55 |
return isinstance(object, (type, types.ClassType)) |
| 56 |
|
| 57 |
def _has_positional_arg(func): |
| 58 |
return func.__code__.co_argcount |
| 59 |
|
| 60 |
|
| 61 |
def filter_traceback(entry): |
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
raw_filename = entry.frame.code.raw.co_filename |
| 66 |
is_generated = '<' in raw_filename and '>' in raw_filename |
| 67 |
if is_generated: |
| 68 |
return False |
| 69 |
|
| 70 |
|
| 71 |
p = py.path.local(entry.path) |
| 72 |
return p != cutdir1 and not p.relto(cutdir2) |
| 73 |
|
| 74 |
|
| 75 |
def get_real_func(obj): |
| 76 |
""" gets the real function object of the (possibly) wrapped object by |
| 77 |
functools.wraps or functools.partial. |
| 78 |
""" |
| 79 |
while hasattr(obj, "__wrapped__"): |
| 80 |
obj = obj.__wrapped__ |
| 81 |
if isinstance(obj, functools.partial): |
| 82 |
obj = obj.func |
| 83 |
return obj |
| 84 |
|
| 85 |
def getfslineno(obj): |
| 86 |
|
| 87 |
obj = get_real_func(obj) |
| 88 |
if hasattr(obj, 'place_as'): |
| 89 |
obj = obj.place_as |
| 90 |
fslineno = _pytest._code.getfslineno(obj) |
| 91 |
assert isinstance(fslineno[1], int), obj |
| 92 |
return fslineno |
| 93 |
|
| 94 |
def getimfunc(func): |
| 95 |
try: |
| 96 |
return func.__func__ |
| 97 |
except AttributeError: |
| 98 |
try: |
| 99 |
return func.im_func |
| 100 |
except AttributeError: |
| 101 |
return func |
| 102 |
|
| 103 |
def safe_getattr(object, name, default): |
| 104 |
""" Like getattr but return default upon any Exception. |
| 105 |
|
| 106 |
Attribute access can potentially fail for 'evil' Python objects. |
| 107 |
See issue214 |
| 108 |
""" |
| 109 |
try: |
| 110 |
return getattr(object, name, default) |
| 111 |
except Exception: |
| 112 |
return default |
| 113 |
|
| 114 |
|
| 115 |
class FixtureFunctionMarker: |
| 116 |
def __init__(self, scope, params, |
| 117 |
autouse=False, yieldctx=False, ids=None): |
| 118 |
self.scope = scope |
| 119 |
self.params = params |
| 120 |
self.autouse = autouse |
| 121 |
self.yieldctx = yieldctx |
| 122 |
self.ids = ids |
| 123 |
|
| 124 |
def __call__(self, function): |
| 125 |
if isclass(function): |
| 126 |
raise ValueError( |
| 127 |
"class fixtures not supported (may be in the future)") |
| 128 |
function._pytestfixturefunction = self |
| 129 |
return function |
| 130 |
|
| 131 |
|
| 132 |
def fixture(scope="function", params=None, autouse=False, ids=None): |
| 133 |
""" (return a) decorator to mark a fixture factory function. |
| 134 |
|
| 135 |
This decorator can be used (with or or without parameters) to define |
| 136 |
a fixture function. The name of the fixture function can later be |
| 137 |
referenced to cause its invocation ahead of running tests: test |
| 138 |
modules or classes can use the pytest.mark.usefixtures(fixturename) |
| 139 |
marker. Test functions can directly use fixture names as input |
| 140 |
arguments in which case the fixture instance returned from the fixture |
| 141 |
function will be injected. |
| 142 |
|
| 143 |
:arg scope: the scope for which this fixture is shared, one of |
| 144 |
"function" (default), "class", "module", "session". |
| 145 |
|
| 146 |
:arg params: an optional list of parameters which will cause multiple |
| 147 |
invocations of the fixture function and all of the tests |
| 148 |
using it. |
| 149 |
|
| 150 |
:arg autouse: if True, the fixture func is activated for all tests that |
| 151 |
can see it. If False (the default) then an explicit |
| 152 |
reference is needed to activate the fixture. |
| 153 |
|
| 154 |
:arg ids: list of string ids each corresponding to the params |
| 155 |
so that they are part of the test id. If no ids are provided |
| 156 |
they will be generated automatically from the params. |
| 157 |
|
| 158 |
""" |
| 159 |
if callable(scope) and params is None and autouse == False: |
| 160 |
|
| 161 |
return FixtureFunctionMarker( |
| 162 |
"function", params, autouse)(scope) |
| 163 |
if params is not None and not isinstance(params, (list, tuple)): |
| 164 |
params = list(params) |
| 165 |
return FixtureFunctionMarker(scope, params, autouse, ids=ids) |
| 166 |
|
| 167 |
def yield_fixture(scope="function", params=None, autouse=False, ids=None): |
| 168 |
""" (return a) decorator to mark a yield-fixture factory function |
| 169 |
(EXPERIMENTAL). |
| 170 |
|
| 171 |
This takes the same arguments as :py:func:`pytest.fixture` but |
| 172 |
expects a fixture function to use a ``yield`` instead of a ``return`` |
| 173 |
statement to provide a fixture. See |
| 174 |
http://pytest.org/en/latest/yieldfixture.html for more info. |
| 175 |
""" |
| 176 |
if callable(scope) and params is None and autouse == False: |
| 177 |
|
| 178 |
return FixtureFunctionMarker( |
| 179 |
"function", params, autouse, yieldctx=True)(scope) |
| 180 |
else: |
| 181 |
return FixtureFunctionMarker(scope, params, autouse, |
| 182 |
yieldctx=True, ids=ids) |
| 183 |
|
| 184 |
defaultfuncargprefixmarker = fixture() |
| 185 |
|
| 186 |
def pyobj_property(name): |
| 187 |
def get(self): |
| 188 |
node = self.getparent(getattr(pytest, name)) |
| 189 |
if node is not None: |
| 190 |
return node.obj |
| 191 |
doc = "python %s object this node was collected from (can be None)." % ( |
| 192 |
name.lower(),) |
| 193 |
return property(get, None, None, doc) |
| 194 |
|
| 195 |
|
| 196 |
def pytest_addoption(parser): |
| 197 |
group = parser.getgroup("general") |
| 198 |
group.addoption('--fixtures', '--funcargs', |
| 199 |
action="store_true", dest="showfixtures", default=False, |
| 200 |
help="show available fixtures, sorted by plugin appearance") |
| 201 |
parser.addini("usefixtures", type="args", default=[], |
| 202 |
help="list of default fixtures to be used with this project") |
| 203 |
parser.addini("python_files", type="args", |
| 204 |
default=['test_*.py', '*_test.py'], |
| 205 |
help="glob-style file patterns for Python test module discovery") |
| 206 |
parser.addini("python_classes", type="args", default=["Test",], |
| 207 |
help="prefixes or glob names for Python test class discovery") |
| 208 |
parser.addini("python_functions", type="args", default=["test",], |
| 209 |
help="prefixes or glob names for Python test function and " |
| 210 |
"method discovery") |
| 211 |
|
| 212 |
group.addoption("--import-mode", default="prepend", |
| 213 |
choices=["prepend", "append"], dest="importmode", |
| 214 |
help="prepend/append to sys.path when importing test modules, " |
| 215 |
"default is to prepend.") |
| 216 |
|
| 217 |
|
| 218 |
def pytest_cmdline_main(config): |
| 219 |
if config.option.showfixtures: |
| 220 |
showfixtures(config) |
| 221 |
return 0 |
| 222 |
|
| 223 |
|
| 224 |
def pytest_generate_tests(metafunc): |
| 225 |
|
| 226 |
|
| 227 |
alt_spellings = ['parameterize', 'parametrise', 'parameterise'] |
| 228 |
for attr in alt_spellings: |
| 229 |
if hasattr(metafunc.function, attr): |
| 230 |
msg = "{0} has '{1}', spelling should be 'parametrize'" |
| 231 |
raise MarkerError(msg.format(metafunc.function.__name__, attr)) |
| 232 |
try: |
| 233 |
markers = metafunc.function.parametrize |
| 234 |
except AttributeError: |
| 235 |
return |
| 236 |
for marker in markers: |
| 237 |
metafunc.parametrize(*marker.args, **marker.kwargs) |
| 238 |
|
| 239 |
def pytest_configure(config): |
| 240 |
config.addinivalue_line("markers", |
| 241 |
"parametrize(argnames, argvalues): call a test function multiple " |
| 242 |
"times passing in different arguments in turn. argvalues generally " |
| 243 |
"needs to be a list of values if argnames specifies only one name " |
| 244 |
"or a list of tuples of values if argnames specifies multiple names. " |
| 245 |
"Example: @parametrize('arg1', [1,2]) would lead to two calls of the " |
| 246 |
"decorated test function, one with arg1=1 and another with arg1=2." |
| 247 |
"see http://pytest.org/latest/parametrize.html for more info and " |
| 248 |
"examples." |
| 249 |
) |
| 250 |
config.addinivalue_line("markers", |
| 251 |
"usefixtures(fixturename1, fixturename2, ...): mark tests as needing " |
| 252 |
"all of the specified fixtures. see http://pytest.org/latest/fixture.html#usefixtures " |
| 253 |
) |
| 254 |
|
| 255 |
def pytest_sessionstart(session): |
| 256 |
session._fixturemanager = FixtureManager(session) |
| 257 |
|
| 258 |
@pytest.hookimpl(trylast=True) |
| 259 |
def pytest_namespace(): |
| 260 |
raises.Exception = pytest.fail.Exception |
| 261 |
return { |
| 262 |
'fixture': fixture, |
| 263 |
'yield_fixture': yield_fixture, |
| 264 |
'raises' : raises, |
| 265 |
'collect': { |
| 266 |
'Module': Module, 'Class': Class, 'Instance': Instance, |
| 267 |
'Function': Function, 'Generator': Generator, |
| 268 |
'_fillfuncargs': fillfixtures} |
| 269 |
} |
| 270 |
|
| 271 |
@fixture(scope="session") |
| 272 |
def pytestconfig(request): |
| 273 |
""" the pytest config object with access to command line opts.""" |
| 274 |
return request.config |
| 275 |
|
| 276 |
|
| 277 |
@pytest.hookimpl(trylast=True) |
| 278 |
def pytest_pyfunc_call(pyfuncitem): |
| 279 |
testfunction = pyfuncitem.obj |
| 280 |
if pyfuncitem._isyieldedfunction(): |
| 281 |
testfunction(*pyfuncitem._args) |
| 282 |
else: |
| 283 |
funcargs = pyfuncitem.funcargs |
| 284 |
testargs = {} |
| 285 |
for arg in pyfuncitem._fixtureinfo.argnames: |
| 286 |
testargs[arg] = funcargs[arg] |
| 287 |
testfunction(**testargs) |
| 288 |
return True |
| 289 |
|
| 290 |
def pytest_collect_file(path, parent): |
| 291 |
ext = path.ext |
| 292 |
if ext == ".py": |
| 293 |
if not parent.session.isinitpath(path): |
| 294 |
for pat in parent.config.getini('python_files'): |
| 295 |
if path.fnmatch(pat): |
| 296 |
break |
| 297 |
else: |
| 298 |
return |
| 299 |
ihook = parent.session.gethookproxy(path) |
| 300 |
return ihook.pytest_pycollect_makemodule(path=path, parent=parent) |
| 301 |
|
| 302 |
def pytest_pycollect_makemodule(path, parent): |
| 303 |
return Module(path, parent) |
| 304 |
|
| 305 |
@pytest.hookimpl(hookwrapper=True) |
| 306 |
def pytest_pycollect_makeitem(collector, name, obj): |
| 307 |
outcome = yield |
| 308 |
res = outcome.get_result() |
| 309 |
if res is not None: |
| 310 |
raise StopIteration |
| 311 |
|
| 312 |
if isclass(obj): |
| 313 |
if collector.istestclass(obj, name): |
| 314 |
Class = collector._getcustomclass("Class") |
| 315 |
outcome.force_result(Class(name, parent=collector)) |
| 316 |
elif collector.istestfunction(obj, name): |
| 317 |
|
| 318 |
obj = getattr(obj, "__func__", obj) |
| 319 |
|
| 320 |
|
| 321 |
|
| 322 |
if not (isfunction(obj) or isfunction(get_real_func(obj))): |
| 323 |
collector.warn(code="C2", message= |
| 324 |
"cannot collect %r because it is not a function." |
| 325 |
% name, ) |
| 326 |
elif getattr(obj, "__test__", True): |
| 327 |
if is_generator(obj): |
| 328 |
res = Generator(name, parent=collector) |
| 329 |
else: |
| 330 |
res = list(collector._genfunctions(name, obj)) |
| 331 |
outcome.force_result(res) |
| 332 |
|
| 333 |
def is_generator(func): |
| 334 |
try: |
| 335 |
return _pytest._code.getrawcode(func).co_flags & 32 |
| 336 |
except AttributeError: |
| 337 |
|
| 338 |
return False |
| 339 |
|
| 340 |
class PyobjContext(object): |
| 341 |
module = pyobj_property("Module") |
| 342 |
cls = pyobj_property("Class") |
| 343 |
instance = pyobj_property("Instance") |
| 344 |
|
| 345 |
class PyobjMixin(PyobjContext): |
| 346 |
def obj(): |
| 347 |
def fget(self): |
| 348 |
try: |
| 349 |
return self._obj |
| 350 |
except AttributeError: |
| 351 |
self._obj = obj = self._getobj() |
| 352 |
return obj |
| 353 |
def fset(self, value): |
| 354 |
self._obj = value |
| 355 |
return property(fget, fset, None, "underlying python object") |
| 356 |
obj = obj() |
| 357 |
|
| 358 |
def _getobj(self): |
| 359 |
return getattr(self.parent.obj, self.name) |
| 360 |
|
| 361 |
def getmodpath(self, stopatmodule=True, includemodule=False): |
| 362 |
""" return python path relative to the containing module. """ |
| 363 |
chain = self.listchain() |
| 364 |
chain.reverse() |
| 365 |
parts = [] |
| 366 |
for node in chain: |
| 367 |
if isinstance(node, Instance): |
| 368 |
continue |
| 369 |
name = node.name |
| 370 |
if isinstance(node, Module): |
| 371 |
assert name.endswith(".py") |
| 372 |
name = name[:-3] |
| 373 |
if stopatmodule: |
| 374 |
if includemodule: |
| 375 |
parts.append(name) |
| 376 |
break |
| 377 |
parts.append(name) |
| 378 |
parts.reverse() |
| 379 |
s = ".".join(parts) |
| 380 |
return s.replace(".[", "[") |
| 381 |
|
| 382 |
def _getfslineno(self): |
| 383 |
return getfslineno(self.obj) |
| 384 |
|
| 385 |
def reportinfo(self): |
| 386 |
|
| 387 |
obj = self.obj |
| 388 |
compat_co_firstlineno = getattr(obj, 'compat_co_firstlineno', None) |
| 389 |
if isinstance(compat_co_firstlineno, int): |
| 390 |
|
| 391 |
fspath = sys.modules[obj.__module__].__file__ |
| 392 |
if fspath.endswith(".pyc"): |
| 393 |
fspath = fspath[:-1] |
| 394 |
lineno = compat_co_firstlineno |
| 395 |
else: |
| 396 |
fspath, lineno = getfslineno(obj) |
| 397 |
modpath = self.getmodpath() |
| 398 |
assert isinstance(lineno, int) |
| 399 |
return fspath, lineno, modpath |
| 400 |
|
| 401 |
class PyCollector(PyobjMixin, pytest.Collector): |
| 402 |
|
| 403 |
def funcnamefilter(self, name): |
| 404 |
return self._matches_prefix_or_glob_option('python_functions', name) |
| 405 |
|
| 406 |
def isnosetest(self, obj): |
| 407 |
""" Look for the __test__ attribute, which is applied by the |
| 408 |
@nose.tools.istest decorator |
| 409 |
""" |
| 410 |
|
| 411 |
|
| 412 |
|
| 413 |
return safe_getattr(obj, '__test__', False) is True |
| 414 |
|
| 415 |
def classnamefilter(self, name): |
| 416 |
return self._matches_prefix_or_glob_option('python_classes', name) |
| 417 |
|
| 418 |
def istestfunction(self, obj, name): |
| 419 |
return ( |
| 420 |
(self.funcnamefilter(name) or self.isnosetest(obj)) and |
| 421 |
safe_getattr(obj, "__call__", False) and getfixturemarker(obj) is None |
| 422 |
) |
| 423 |
|
| 424 |
def istestclass(self, obj, name): |
| 425 |
return self.classnamefilter(name) or self.isnosetest(obj) |
| 426 |
|
| 427 |
def _matches_prefix_or_glob_option(self, option_name, name): |
| 428 |
""" |
| 429 |
checks if the given name matches the prefix or glob-pattern defined |
| 430 |
in ini configuration. |
| 431 |
""" |
| 432 |
for option in self.config.getini(option_name): |
| 433 |
if name.startswith(option): |
| 434 |
return True |
| 435 |
|
| 436 |
|
| 437 |
|
| 438 |
elif ('*' in option or '?' in option or '[' in option) and \ |
| 439 |
fnmatch.fnmatch(name, option): |
| 440 |
return True |
| 441 |
return False |
| 442 |
|
| 443 |
def collect(self): |
| 444 |
if not getattr(self.obj, "__test__", True): |
| 445 |
return [] |
| 446 |
|
| 447 |
|
| 448 |
|
| 449 |
dicts = [getattr(self.obj, '__dict__', {})] |
| 450 |
for basecls in inspect.getmro(self.obj.__class__): |
| 451 |
dicts.append(basecls.__dict__) |
| 452 |
seen = {} |
| 453 |
l = [] |
| 454 |
for dic in dicts: |
| 455 |
for name, obj in list(dic.items()): |
| 456 |
if name in seen: |
| 457 |
continue |
| 458 |
seen[name] = True |
| 459 |
res = self.makeitem(name, obj) |
| 460 |
if res is None: |
| 461 |
continue |
| 462 |
if not isinstance(res, list): |
| 463 |
res = [res] |
| 464 |
l.extend(res) |
| 465 |
l.sort(key=lambda item: item.reportinfo()[:2]) |
| 466 |
return l |
| 467 |
|
| 468 |
def makeitem(self, name, obj): |
| 469 |
|
| 470 |
return self.ihook.pytest_pycollect_makeitem( |
| 471 |
collector=self, name=name, obj=obj) |
| 472 |
|
| 473 |
def _genfunctions(self, name, funcobj): |
| 474 |
module = self.getparent(Module).obj |
| 475 |
clscol = self.getparent(Class) |
| 476 |
cls = clscol and clscol.obj or None |
| 477 |
transfer_markers(funcobj, cls, module) |
| 478 |
fm = self.session._fixturemanager |
| 479 |
fixtureinfo = fm.getfixtureinfo(self, funcobj, cls) |
| 480 |
metafunc = Metafunc(funcobj, fixtureinfo, self.config, |
| 481 |
cls=cls, module=module) |
| 482 |
methods = [] |
| 483 |
if hasattr(module, "pytest_generate_tests"): |
| 484 |
methods.append(module.pytest_generate_tests) |
| 485 |
if hasattr(cls, "pytest_generate_tests"): |
| 486 |
methods.append(cls().pytest_generate_tests) |
| 487 |
if methods: |
| 488 |
self.ihook.pytest_generate_tests.call_extra(methods, |
| 489 |
dict(metafunc=metafunc)) |
| 490 |
else: |
| 491 |
self.ihook.pytest_generate_tests(metafunc=metafunc) |
| 492 |
|
| 493 |
Function = self._getcustomclass("Function") |
| 494 |
if not metafunc._calls: |
| 495 |
yield Function(name, parent=self, fixtureinfo=fixtureinfo) |
| 496 |
else: |
| 497 |
|
| 498 |
add_funcarg_pseudo_fixture_def(self, metafunc, fm) |
| 499 |
|
| 500 |
for callspec in metafunc._calls: |
| 501 |
subname = "%s[%s]" %(name, callspec.id) |
| 502 |
yield Function(name=subname, parent=self, |
| 503 |
callspec=callspec, callobj=funcobj, |
| 504 |
fixtureinfo=fixtureinfo, |
| 505 |
keywords={callspec.id:True}) |
| 506 |
|
| 507 |
def add_funcarg_pseudo_fixture_def(collector, metafunc, fixturemanager): |
| 508 |
|
| 509 |
|
| 510 |
|
| 511 |
|
| 512 |
|
| 513 |
|
| 514 |
if not metafunc._calls[0].funcargs: |
| 515 |
return |
| 516 |
|
| 517 |
arg2params = {} |
| 518 |
arg2scope = {} |
| 519 |
for callspec in metafunc._calls: |
| 520 |
for argname, argvalue in callspec.funcargs.items(): |
| 521 |
assert argname not in callspec.params |
| 522 |
callspec.params[argname] = argvalue |
| 523 |
arg2params_list = arg2params.setdefault(argname, []) |
| 524 |
callspec.indices[argname] = len(arg2params_list) |
| 525 |
arg2params_list.append(argvalue) |
| 526 |
if argname not in arg2scope: |
| 527 |
scopenum = callspec._arg2scopenum.get(argname, |
| 528 |
scopenum_function) |
| 529 |
arg2scope[argname] = scopes[scopenum] |
| 530 |
callspec.funcargs.clear() |
| 531 |
|
| 532 |
|
| 533 |
|
| 534 |
arg2fixturedefs = metafunc._arg2fixturedefs |
| 535 |
for argname, valuelist in arg2params.items(): |
| 536 |
|
| 537 |
|
| 538 |
|
| 539 |
|
| 540 |
scope = arg2scope[argname] |
| 541 |
node = None |
| 542 |
if scope != "function": |
| 543 |
node = get_scope_node(collector, scope) |
| 544 |
if node is None: |
| 545 |
assert scope == "class" and isinstance(collector, Module) |
| 546 |
|
| 547 |
node = collector |
| 548 |
if node and argname in node._name2pseudofixturedef: |
| 549 |
arg2fixturedefs[argname] = [node._name2pseudofixturedef[argname]] |
| 550 |
else: |
| 551 |
fixturedef = FixtureDef(fixturemanager, '', argname, |
| 552 |
get_direct_param_fixture_func, |
| 553 |
arg2scope[argname], |
| 554 |
valuelist, False, False) |
| 555 |
arg2fixturedefs[argname] = [fixturedef] |
| 556 |
if node is not None: |
| 557 |
node._name2pseudofixturedef[argname] = fixturedef |
| 558 |
|
| 559 |
|
| 560 |
def get_direct_param_fixture_func(request): |
| 561 |
return request.param |
| 562 |
|
| 563 |
class FuncFixtureInfo: |
| 564 |
def __init__(self, argnames, names_closure, name2fixturedefs): |
| 565 |
self.argnames = argnames |
| 566 |
self.names_closure = names_closure |
| 567 |
self.name2fixturedefs = name2fixturedefs |
| 568 |
|
| 569 |
|
| 570 |
def _marked(func, mark): |
| 571 |
""" Returns True if :func: is already marked with :mark:, False otherwise. |
| 572 |
This can happen if marker is applied to class and the test file is |
| 573 |
invoked more than once. |
| 574 |
""" |
| 575 |
try: |
| 576 |
func_mark = getattr(func, mark.name) |
| 577 |
except AttributeError: |
| 578 |
return False |
| 579 |
return mark.args == func_mark.args and mark.kwargs == func_mark.kwargs |
| 580 |
|
| 581 |
|
| 582 |
def transfer_markers(funcobj, cls, mod): |
| 583 |
|
| 584 |
|
| 585 |
for holder in (cls, mod): |
| 586 |
try: |
| 587 |
pytestmark = holder.pytestmark |
| 588 |
except AttributeError: |
| 589 |
continue |
| 590 |
if isinstance(pytestmark, list): |
| 591 |
for mark in pytestmark: |
| 592 |
if not _marked(funcobj, mark): |
| 593 |
mark(funcobj) |
| 594 |
else: |
| 595 |
if not _marked(funcobj, pytestmark): |
| 596 |
pytestmark(funcobj) |
| 597 |
|
| 598 |
class Module(pytest.File, PyCollector): |
| 599 |
""" Collector for test classes and functions. """ |
| 600 |
def _getobj(self): |
| 601 |
return self._memoizedcall('_obj', self._importtestmodule) |
| 602 |
|
| 603 |
def collect(self): |
| 604 |
self.session._fixturemanager.parsefactories(self) |
| 605 |
return super(Module, self).collect() |
| 606 |
|
| 607 |
def _importtestmodule(self): |
| 608 |
|
| 609 |
importmode = self.config.getoption("--import-mode") |
| 610 |
try: |
| 611 |
mod = self.fspath.pyimport(ensuresyspath=importmode) |
| 612 |
except SyntaxError: |
| 613 |
raise self.CollectError( |
| 614 |
_pytest._code.ExceptionInfo().getrepr(style="short")) |
| 615 |
except self.fspath.ImportMismatchError: |
| 616 |
e = sys.exc_info()[1] |
| 617 |
raise self.CollectError( |
| 618 |
"import file mismatch:\n" |
| 619 |
"imported module %r has this __file__ attribute:\n" |
| 620 |
" %s\n" |
| 621 |
"which is not the same as the test file we want to collect:\n" |
| 622 |
" %s\n" |
| 623 |
"HINT: remove __pycache__ / .pyc files and/or use a " |
| 624 |
"unique basename for your test file modules" |
| 625 |
% e.args |
| 626 |
) |
| 627 |
|
| 628 |
self.config.pluginmanager.consider_module(mod) |
| 629 |
return mod |
| 630 |
|
| 631 |
def setup(self): |
| 632 |
setup_module = xunitsetup(self.obj, "setUpModule") |
| 633 |
if setup_module is None: |
| 634 |
setup_module = xunitsetup(self.obj, "setup_module") |
| 635 |
if setup_module is not None: |
| 636 |
|
| 637 |
|
| 638 |
|
| 639 |
if _has_positional_arg(setup_module): |
| 640 |
setup_module(self.obj) |
| 641 |
else: |
| 642 |
setup_module() |
| 643 |
fin = getattr(self.obj, 'tearDownModule', None) |
| 644 |
if fin is None: |
| 645 |
fin = getattr(self.obj, 'teardown_module', None) |
| 646 |
if fin is not None: |
| 647 |
|
| 648 |
|
| 649 |
|
| 650 |
if _has_positional_arg(fin): |
| 651 |
finalizer = lambda: fin(self.obj) |
| 652 |
else: |
| 653 |
finalizer = fin |
| 654 |
self.addfinalizer(finalizer) |
| 655 |
|
| 656 |
|
| 657 |
class Class(PyCollector): |
| 658 |
""" Collector for test methods. """ |
| 659 |
def collect(self): |
| 660 |
if hasinit(self.obj): |
| 661 |
self.warn("C1", "cannot collect test class %r because it has a " |
| 662 |
"__init__ constructor" % self.obj.__name__) |
| 663 |
return [] |
| 664 |
return [self._getcustomclass("Instance")(name="()", parent=self)] |
| 665 |
|
| 666 |
def setup(self): |
| 667 |
setup_class = xunitsetup(self.obj, 'setup_class') |
| 668 |
if setup_class is not None: |
| 669 |
setup_class = getattr(setup_class, 'im_func', setup_class) |
| 670 |
setup_class = getattr(setup_class, '__func__', setup_class) |
| 671 |
setup_class(self.obj) |
| 672 |
|
| 673 |
fin_class = getattr(self.obj, 'teardown_class', None) |
| 674 |
if fin_class is not None: |
| 675 |
fin_class = getattr(fin_class, 'im_func', fin_class) |
| 676 |
fin_class = getattr(fin_class, '__func__', fin_class) |
| 677 |
self.addfinalizer(lambda: fin_class(self.obj)) |
| 678 |
|
| 679 |
class Instance(PyCollector): |
| 680 |
def _getobj(self): |
| 681 |
obj = self.parent.obj() |
| 682 |
return obj |
| 683 |
|
| 684 |
def collect(self): |
| 685 |
self.session._fixturemanager.parsefactories(self) |
| 686 |
return super(Instance, self).collect() |
| 687 |
|
| 688 |
def newinstance(self): |
| 689 |
self.obj = self._getobj() |
| 690 |
return self.obj |
| 691 |
|
| 692 |
class FunctionMixin(PyobjMixin): |
| 693 |
""" mixin for the code common to Function and Generator. |
| 694 |
""" |
| 695 |
|
| 696 |
def setup(self): |
| 697 |
""" perform setup for this test function. """ |
| 698 |
if hasattr(self, '_preservedparent'): |
| 699 |
obj = self._preservedparent |
| 700 |
elif isinstance(self.parent, Instance): |
| 701 |
obj = self.parent.newinstance() |
| 702 |
self.obj = self._getobj() |
| 703 |
else: |
| 704 |
obj = self.parent.obj |
| 705 |
if inspect.ismethod(self.obj): |
| 706 |
setup_name = 'setup_method' |
| 707 |
teardown_name = 'teardown_method' |
| 708 |
else: |
| 709 |
setup_name = 'setup_function' |
| 710 |
teardown_name = 'teardown_function' |
| 711 |
setup_func_or_method = xunitsetup(obj, setup_name) |
| 712 |
if setup_func_or_method is not None: |
| 713 |
setup_func_or_method(self.obj) |
| 714 |
fin = getattr(obj, teardown_name, None) |
| 715 |
if fin is not None: |
| 716 |
self.addfinalizer(lambda: fin(self.obj)) |
| 717 |
|
| 718 |
def _prunetraceback(self, excinfo): |
| 719 |
if hasattr(self, '_obj') and not self.config.option.fulltrace: |
| 720 |
code = _pytest._code.Code(get_real_func(self.obj)) |
| 721 |
path, firstlineno = code.path, code.firstlineno |
| 722 |
traceback = excinfo.traceback |
| 723 |
ntraceback = traceback.cut(path=path, firstlineno=firstlineno) |
| 724 |
if ntraceback == traceback: |
| 725 |
ntraceback = ntraceback.cut(path=path) |
| 726 |
if ntraceback == traceback: |
| 727 |
|
| 728 |
ntraceback = ntraceback.filter(filter_traceback) |
| 729 |
if not ntraceback: |
| 730 |
ntraceback = traceback |
| 731 |
|
| 732 |
excinfo.traceback = ntraceback.filter() |
| 733 |
|
| 734 |
|
| 735 |
if self.config.option.tbstyle == "auto": |
| 736 |
if len(excinfo.traceback) > 2: |
| 737 |
for entry in excinfo.traceback[1:-1]: |
| 738 |
entry.set_repr_style('short') |
| 739 |
|
| 740 |
def _repr_failure_py(self, excinfo, style="long"): |
| 741 |
if excinfo.errisinstance(pytest.fail.Exception): |
| 742 |
if not excinfo.value.pytrace: |
| 743 |
return py._builtin._totext(excinfo.value) |
| 744 |
return super(FunctionMixin, self)._repr_failure_py(excinfo, |
| 745 |
style=style) |
| 746 |
|
| 747 |
def repr_failure(self, excinfo, outerr=None): |
| 748 |
assert outerr is None, "XXX outerr usage is deprecated" |
| 749 |
style = self.config.option.tbstyle |
| 750 |
if style == "auto": |
| 751 |
style = "long" |
| 752 |
return self._repr_failure_py(excinfo, style=style) |
| 753 |
|
| 754 |
|
| 755 |
class Generator(FunctionMixin, PyCollector): |
| 756 |
def collect(self): |
| 757 |
|
| 758 |
|
| 759 |
|
| 760 |
self.session._setupstate.prepare(self) |
| 761 |
|
| 762 |
self._preservedparent = self.parent.obj |
| 763 |
l = [] |
| 764 |
seen = {} |
| 765 |
for i, x in enumerate(self.obj()): |
| 766 |
name, call, args = self.getcallargs(x) |
| 767 |
if not callable(call): |
| 768 |
raise TypeError("%r yielded non callable test %r" %(self.obj, call,)) |
| 769 |
if name is None: |
| 770 |
name = "[%d]" % i |
| 771 |
else: |
| 772 |
name = "['%s']" % name |
| 773 |
if name in seen: |
| 774 |
raise ValueError("%r generated tests with non-unique name %r" %(self, name)) |
| 775 |
seen[name] = True |
| 776 |
l.append(self.Function(name, self, args=args, callobj=call)) |
| 777 |
return l |
| 778 |
|
| 779 |
def getcallargs(self, obj): |
| 780 |
if not isinstance(obj, (tuple, list)): |
| 781 |
obj = (obj,) |
| 782 |
|
| 783 |
if isinstance(obj[0], py.builtin._basestring): |
| 784 |
name = obj[0] |
| 785 |
obj = obj[1:] |
| 786 |
else: |
| 787 |
name = None |
| 788 |
call, args = obj[0], obj[1:] |
| 789 |
return name, call, args |
| 790 |
|
| 791 |
|
| 792 |
def hasinit(obj): |
| 793 |
init = getattr(obj, '__init__', None) |
| 794 |
if init: |
| 795 |
if init != object.__init__: |
| 796 |
return True |
| 797 |
|
| 798 |
|
| 799 |
|
| 800 |
def fillfixtures(function): |
| 801 |
""" fill missing funcargs for a test function. """ |
| 802 |
try: |
| 803 |
request = function._request |
| 804 |
except AttributeError: |
| 805 |
|
| 806 |
|
| 807 |
|
| 808 |
fm = function.session._fixturemanager |
| 809 |
fi = fm.getfixtureinfo(function.parent, function.obj, None) |
| 810 |
function._fixtureinfo = fi |
| 811 |
request = function._request = FixtureRequest(function) |
| 812 |
request._fillfixtures() |
| 813 |
|
| 814 |
newfuncargs = {} |
| 815 |
for name in fi.argnames: |
| 816 |
newfuncargs[name] = function.funcargs[name] |
| 817 |
function.funcargs = newfuncargs |
| 818 |
else: |
| 819 |
request._fillfixtures() |
| 820 |
|
| 821 |
|
| 822 |
_notexists = object() |
| 823 |
|
| 824 |
class CallSpec2(object): |
| 825 |
def __init__(self, metafunc): |
| 826 |
self.metafunc = metafunc |
| 827 |
self.funcargs = {} |
| 828 |
self._idlist = [] |
| 829 |
self.params = {} |
| 830 |
self._globalid = _notexists |
| 831 |
self._globalid_args = set() |
| 832 |
self._globalparam = _notexists |
| 833 |
self._arg2scopenum = {} |
| 834 |
self.keywords = {} |
| 835 |
self.indices = {} |
| 836 |
|
| 837 |
def copy(self, metafunc): |
| 838 |
cs = CallSpec2(self.metafunc) |
| 839 |
cs.funcargs.update(self.funcargs) |
| 840 |
cs.params.update(self.params) |
| 841 |
cs.keywords.update(self.keywords) |
| 842 |
cs.indices.update(self.indices) |
| 843 |
cs._arg2scopenum.update(self._arg2scopenum) |
| 844 |
cs._idlist = list(self._idlist) |
| 845 |
cs._globalid = self._globalid |
| 846 |
cs._globalid_args = self._globalid_args |
| 847 |
cs._globalparam = self._globalparam |
| 848 |
return cs |
| 849 |
|
| 850 |
def _checkargnotcontained(self, arg): |
| 851 |
if arg in self.params or arg in self.funcargs: |
| 852 |
raise ValueError("duplicate %r" %(arg,)) |
| 853 |
|
| 854 |
def getparam(self, name): |
| 855 |
try: |
| 856 |
return self.params[name] |
| 857 |
except KeyError: |
| 858 |
if self._globalparam is _notexists: |
| 859 |
raise ValueError(name) |
| 860 |
return self._globalparam |
| 861 |
|
| 862 |
@property |
| 863 |
def id(self): |
| 864 |
return "-".join(map(str, filter(None, self._idlist))) |
| 865 |
|
| 866 |
def setmulti(self, valtypes, argnames, valset, id, keywords, scopenum, |
| 867 |
param_index): |
| 868 |
for arg,val in zip(argnames, valset): |
| 869 |
self._checkargnotcontained(arg) |
| 870 |
valtype_for_arg = valtypes[arg] |
| 871 |
getattr(self, valtype_for_arg)[arg] = val |
| 872 |
self.indices[arg] = param_index |
| 873 |
self._arg2scopenum[arg] = scopenum |
| 874 |
self._idlist.append(id) |
| 875 |
self.keywords.update(keywords) |
| 876 |
|
| 877 |
def setall(self, funcargs, id, param): |
| 878 |
for x in funcargs: |
| 879 |
self._checkargnotcontained(x) |
| 880 |
self.funcargs.update(funcargs) |
| 881 |
if id is not _notexists: |
| 882 |
self._idlist.append(id) |
| 883 |
if param is not _notexists: |
| 884 |
assert self._globalparam is _notexists |
| 885 |
self._globalparam = param |
| 886 |
for arg in funcargs: |
| 887 |
self._arg2scopenum[arg] = scopenum_function |
| 888 |
|
| 889 |
|
| 890 |
class FuncargnamesCompatAttr: |
| 891 |
""" helper class so that Metafunc, Function and FixtureRequest |
| 892 |
don't need to each define the "funcargnames" compatibility attribute. |
| 893 |
""" |
| 894 |
@property |
| 895 |
def funcargnames(self): |
| 896 |
""" alias attribute for ``fixturenames`` for pre-2.3 compatibility""" |
| 897 |
return self.fixturenames |
| 898 |
|
| 899 |
class Metafunc(FuncargnamesCompatAttr): |
| 900 |
""" |
| 901 |
Metafunc objects are passed to the ``pytest_generate_tests`` hook. |
| 902 |
They help to inspect a test function and to generate tests according to |
| 903 |
test configuration or values specified in the class or module where a |
| 904 |
test function is defined. |
| 905 |
|
| 906 |
:ivar fixturenames: set of fixture names required by the test function |
| 907 |
|
| 908 |
:ivar function: underlying python test function |
| 909 |
|
| 910 |
:ivar cls: class object where the test function is defined in or ``None``. |
| 911 |
|
| 912 |
:ivar module: the module object where the test function is defined in. |
| 913 |
|
| 914 |
:ivar config: access to the :class:`_pytest.config.Config` object for the |
| 915 |
test session. |
| 916 |
|
| 917 |
:ivar funcargnames: |
| 918 |
.. deprecated:: 2.3 |
| 919 |
Use ``fixturenames`` instead. |
| 920 |
""" |
| 921 |
def __init__(self, function, fixtureinfo, config, cls=None, module=None): |
| 922 |
self.config = config |
| 923 |
self.module = module |
| 924 |
self.function = function |
| 925 |
self.fixturenames = fixtureinfo.names_closure |
| 926 |
self._arg2fixturedefs = fixtureinfo.name2fixturedefs |
| 927 |
self.cls = cls |
| 928 |
self._calls = [] |
| 929 |
self._ids = py.builtin.set() |
| 930 |
|
| 931 |
def parametrize(self, argnames, argvalues, indirect=False, ids=None, |
| 932 |
scope=None): |
| 933 |
""" Add new invocations to the underlying test function using the list |
| 934 |
of argvalues for the given argnames. Parametrization is performed |
| 935 |
during the collection phase. If you need to setup expensive resources |
| 936 |
see about setting indirect to do it rather at test setup time. |
| 937 |
|
| 938 |
:arg argnames: a comma-separated string denoting one or more argument |
| 939 |
names, or a list/tuple of argument strings. |
| 940 |
|
| 941 |
:arg argvalues: The list of argvalues determines how often a |
| 942 |
test is invoked with different argument values. If only one |
| 943 |
argname was specified argvalues is a list of values. If N |
| 944 |
argnames were specified, argvalues must be a list of N-tuples, |
| 945 |
where each tuple-element specifies a value for its respective |
| 946 |
argname. |
| 947 |
|
| 948 |
:arg indirect: The list of argnames or boolean. A list of arguments' |
| 949 |
names (subset of argnames). If True the list contains all names from |
| 950 |
the argnames. Each argvalue corresponding to an argname in this list will |
| 951 |
be passed as request.param to its respective argname fixture |
| 952 |
function so that it can perform more expensive setups during the |
| 953 |
setup phase of a test rather than at collection time. |
| 954 |
|
| 955 |
:arg ids: list of string ids, or a callable. |
| 956 |
If strings, each is corresponding to the argvalues so that they are |
| 957 |
part of the test id. |
| 958 |
If callable, it should take one argument (a single argvalue) and return |
| 959 |
a string or return None. If None, the automatically generated id for that |
| 960 |
argument will be used. |
| 961 |
If no ids are provided they will be generated automatically from |
| 962 |
the argvalues. |
| 963 |
|
| 964 |
:arg scope: if specified it denotes the scope of the parameters. |
| 965 |
The scope is used for grouping tests by parameter instances. |
| 966 |
It will also override any fixture-function defined scope, allowing |
| 967 |
to set a dynamic scope using test context or configuration. |
| 968 |
""" |
| 969 |
|
| 970 |
|
| 971 |
|
| 972 |
|
| 973 |
newkeywords = {} |
| 974 |
unwrapped_argvalues = [] |
| 975 |
for i, argval in enumerate(argvalues): |
| 976 |
while isinstance(argval, MarkDecorator): |
| 977 |
newmark = MarkDecorator(argval.markname, |
| 978 |
argval.args[:-1], argval.kwargs) |
| 979 |
newmarks = newkeywords.setdefault(i, {}) |
| 980 |
newmarks[newmark.markname] = newmark |
| 981 |
argval = argval.args[-1] |
| 982 |
unwrapped_argvalues.append(argval) |
| 983 |
argvalues = unwrapped_argvalues |
| 984 |
|
| 985 |
if not isinstance(argnames, (tuple, list)): |
| 986 |
argnames = [x.strip() for x in argnames.split(",") if x.strip()] |
| 987 |
if len(argnames) == 1: |
| 988 |
argvalues = [(val,) for val in argvalues] |
| 989 |
if not argvalues: |
| 990 |
argvalues = [(_notexists,) * len(argnames)] |
| 991 |
|
| 992 |
|
| 993 |
fs, lineno = getfslineno(self.function) |
| 994 |
newmark = pytest.mark.skip( |
| 995 |
reason="got empty parameter set %r, function %s at %s:%d" % ( |
| 996 |
argnames, self.function.__name__, fs, lineno)) |
| 997 |
newmarks = newkeywords.setdefault(0, {}) |
| 998 |
newmarks[newmark.markname] = newmark |
| 999 |
|
| 1000 |
|
| 1001 |
if scope is None: |
| 1002 |
scope = "function" |
| 1003 |
scopenum = scopes.index(scope) |
| 1004 |
valtypes = {} |
| 1005 |
for arg in argnames: |
| 1006 |
if arg not in self.fixturenames: |
| 1007 |
raise ValueError("%r uses no fixture %r" %(self.function, arg)) |
| 1008 |
|
| 1009 |
if indirect is True: |
| 1010 |
valtypes = dict.fromkeys(argnames, "params") |
| 1011 |
elif indirect is False: |
| 1012 |
valtypes = dict.fromkeys(argnames, "funcargs") |
| 1013 |
elif isinstance(indirect, (tuple, list)): |
| 1014 |
valtypes = dict.fromkeys(argnames, "funcargs") |
| 1015 |
for arg in indirect: |
| 1016 |
if arg not in argnames: |
| 1017 |
raise ValueError("indirect given to %r: fixture %r doesn't exist" %( |
| 1018 |
self.function, arg)) |
| 1019 |
valtypes[arg] = "params" |
| 1020 |
idfn = None |
| 1021 |
if callable(ids): |
| 1022 |
idfn = ids |
| 1023 |
ids = None |
| 1024 |
if ids and len(ids) != len(argvalues): |
| 1025 |
raise ValueError('%d tests specified with %d ids' %( |
| 1026 |
len(argvalues), len(ids))) |
| 1027 |
if not ids: |
| 1028 |
ids = idmaker(argnames, argvalues, idfn) |
| 1029 |
newcalls = [] |
| 1030 |
for callspec in self._calls or [CallSpec2(self)]: |
| 1031 |
for param_index, valset in enumerate(argvalues): |
| 1032 |
assert len(valset) == len(argnames) |
| 1033 |
newcallspec = callspec.copy(self) |
| 1034 |
newcallspec.setmulti(valtypes, argnames, valset, ids[param_index], |
| 1035 |
newkeywords.get(param_index, {}), scopenum, |
| 1036 |
param_index) |
| 1037 |
newcalls.append(newcallspec) |
| 1038 |
self._calls = newcalls |
| 1039 |
|
| 1040 |
def addcall(self, funcargs=None, id=_notexists, param=_notexists): |
| 1041 |
""" (deprecated, use parametrize) Add a new call to the underlying |
| 1042 |
test function during the collection phase of a test run. Note that |
| 1043 |
request.addcall() is called during the test collection phase prior and |
| 1044 |
independently to actual test execution. You should only use addcall() |
| 1045 |
if you need to specify multiple arguments of a test function. |
| 1046 |
|
| 1047 |
:arg funcargs: argument keyword dictionary used when invoking |
| 1048 |
the test function. |
| 1049 |
|
| 1050 |
:arg id: used for reporting and identification purposes. If you |
| 1051 |
don't supply an `id` an automatic unique id will be generated. |
| 1052 |
|
| 1053 |
:arg param: a parameter which will be exposed to a later fixture function |
| 1054 |
invocation through the ``request.param`` attribute. |
| 1055 |
""" |
| 1056 |
assert funcargs is None or isinstance(funcargs, dict) |
| 1057 |
if funcargs is not None: |
| 1058 |
for name in funcargs: |
| 1059 |
if name not in self.fixturenames: |
| 1060 |
pytest.fail("funcarg %r not used in this function." % name) |
| 1061 |
else: |
| 1062 |
funcargs = {} |
| 1063 |
if id is None: |
| 1064 |
raise ValueError("id=None not allowed") |
| 1065 |
if id is _notexists: |
| 1066 |
id = len(self._calls) |
| 1067 |
id = str(id) |
| 1068 |
if id in self._ids: |
| 1069 |
raise ValueError("duplicate id %r" % id) |
| 1070 |
self._ids.add(id) |
| 1071 |
|
| 1072 |
cs = CallSpec2(self) |
| 1073 |
cs.setall(funcargs, id, param) |
| 1074 |
self._calls.append(cs) |
| 1075 |
|
| 1076 |
|
| 1077 |
if _PY3: |
| 1078 |
import codecs |
| 1079 |
|
| 1080 |
def _escape_bytes(val): |
| 1081 |
""" |
| 1082 |
If val is pure ascii, returns it as a str(), otherwise escapes |
| 1083 |
into a sequence of escaped bytes: |
| 1084 |
b'\xc3\xb4\xc5\xd6' -> u'\\xc3\\xb4\\xc5\\xd6' |
| 1085 |
|
| 1086 |
note: |
| 1087 |
the obvious "v.decode('unicode-escape')" will return |
| 1088 |
valid utf-8 unicode if it finds them in the string, but we |
| 1089 |
want to return escaped bytes for any byte, even if they match |
| 1090 |
a utf-8 string. |
| 1091 |
""" |
| 1092 |
if val: |
| 1093 |
|
| 1094 |
encoded_bytes, _ = codecs.escape_encode(val) |
| 1095 |
return encoded_bytes.decode('ascii') |
| 1096 |
else: |
| 1097 |
|
| 1098 |
return '' |
| 1099 |
else: |
| 1100 |
def _escape_bytes(val): |
| 1101 |
""" |
| 1102 |
In py2 bytes and str are the same type, so return it unchanged if it |
| 1103 |
is a full ascii string, otherwise escape it into its binary form. |
| 1104 |
""" |
| 1105 |
try: |
| 1106 |
return val.decode('ascii') |
| 1107 |
except UnicodeDecodeError: |
| 1108 |
return val.encode('string-escape') |
| 1109 |
|
| 1110 |
|
| 1111 |
def _idval(val, argname, idx, idfn): |
| 1112 |
if idfn: |
| 1113 |
try: |
| 1114 |
s = idfn(val) |
| 1115 |
if s: |
| 1116 |
return s |
| 1117 |
except Exception: |
| 1118 |
pass |
| 1119 |
|
| 1120 |
if isinstance(val, bytes): |
| 1121 |
return _escape_bytes(val) |
| 1122 |
elif isinstance(val, (float, int, str, bool, NoneType)): |
| 1123 |
return str(val) |
| 1124 |
elif isinstance(val, REGEX_TYPE): |
| 1125 |
return _escape_bytes(val.pattern) if isinstance(val.pattern, bytes) else val.pattern |
| 1126 |
elif enum is not None and isinstance(val, enum.Enum): |
| 1127 |
return str(val) |
| 1128 |
elif isclass(val) and hasattr(val, '__name__'): |
| 1129 |
return val.__name__ |
| 1130 |
elif _PY2 and isinstance(val, unicode): |
| 1131 |
|
| 1132 |
|
| 1133 |
try: |
| 1134 |
return str(val) |
| 1135 |
except UnicodeError: |
| 1136 |
|
| 1137 |
pass |
| 1138 |
return str(argname)+str(idx) |
| 1139 |
|
| 1140 |
def _idvalset(idx, valset, argnames, idfn): |
| 1141 |
this_id = [_idval(val, argname, idx, idfn) |
| 1142 |
for val, argname in zip(valset, argnames)] |
| 1143 |
return "-".join(this_id) |
| 1144 |
|
| 1145 |
def idmaker(argnames, argvalues, idfn=None): |
| 1146 |
ids = [_idvalset(valindex, valset, argnames, idfn) |
| 1147 |
for valindex, valset in enumerate(argvalues)] |
| 1148 |
if len(set(ids)) < len(ids): |
| 1149 |
|
| 1150 |
ids = [str(i) + testid for i, testid in enumerate(ids)] |
| 1151 |
return ids |
| 1152 |
|
| 1153 |
def showfixtures(config): |
| 1154 |
from _pytest.main import wrap_session |
| 1155 |
return wrap_session(config, _showfixtures_main) |
| 1156 |
|
| 1157 |
def _showfixtures_main(config, session): |
| 1158 |
import _pytest.config |
| 1159 |
session.perform_collect() |
| 1160 |
curdir = py.path.local() |
| 1161 |
tw = _pytest.config.create_terminal_writer(config) |
| 1162 |
verbose = config.getvalue("verbose") |
| 1163 |
|
| 1164 |
fm = session._fixturemanager |
| 1165 |
|
| 1166 |
available = [] |
| 1167 |
for argname, fixturedefs in fm._arg2fixturedefs.items(): |
| 1168 |
assert fixturedefs is not None |
| 1169 |
if not fixturedefs: |
| 1170 |
continue |
| 1171 |
for fixturedef in fixturedefs: |
| 1172 |
loc = getlocation(fixturedef.func, curdir) |
| 1173 |
available.append((len(fixturedef.baseid), |
| 1174 |
fixturedef.func.__module__, |
| 1175 |
curdir.bestrelpath(loc), |
| 1176 |
fixturedef.argname, fixturedef)) |
| 1177 |
|
| 1178 |
available.sort() |
| 1179 |
currentmodule = None |
| 1180 |
for baseid, module, bestrel, argname, fixturedef in available: |
| 1181 |
if currentmodule != module: |
| 1182 |
if not module.startswith("_pytest."): |
| 1183 |
tw.line() |
| 1184 |
tw.sep("-", "fixtures defined from %s" %(module,)) |
| 1185 |
currentmodule = module |
| 1186 |
if verbose <= 0 and argname[0] == "_": |
| 1187 |
continue |
| 1188 |
if verbose > 0: |
| 1189 |
funcargspec = "%s -- %s" %(argname, bestrel,) |
| 1190 |
else: |
| 1191 |
funcargspec = argname |
| 1192 |
tw.line(funcargspec, green=True) |
| 1193 |
loc = getlocation(fixturedef.func, curdir) |
| 1194 |
doc = fixturedef.func.__doc__ or "" |
| 1195 |
if doc: |
| 1196 |
for line in doc.strip().split("\n"): |
| 1197 |
tw.line(" " + line.strip()) |
| 1198 |
else: |
| 1199 |
tw.line(" %s: no docstring available" %(loc,), |
| 1200 |
red=True) |
| 1201 |
|
| 1202 |
def getlocation(function, curdir): |
| 1203 |
import inspect |
| 1204 |
fn = py.path.local(inspect.getfile(function)) |
| 1205 |
lineno = py.builtin._getcode(function).co_firstlineno |
| 1206 |
if fn.relto(curdir): |
| 1207 |
fn = fn.relto(curdir) |
| 1208 |
return "%s:%d" %(fn, lineno+1) |
| 1209 |
|
| 1210 |
|
| 1211 |
|
| 1212 |
def raises(expected_exception, *args, **kwargs): |
| 1213 |
""" assert that a code block/function call raises ``expected_exception`` |
| 1214 |
and raise a failure exception otherwise. |
| 1215 |
|
| 1216 |
This helper produces a ``ExceptionInfo()`` object (see below). |
| 1217 |
|
| 1218 |
If using Python 2.5 or above, you may use this function as a |
| 1219 |
context manager:: |
| 1220 |
|
| 1221 |
>>> with raises(ZeroDivisionError): |
| 1222 |
... 1/0 |
| 1223 |
|
| 1224 |
.. note:: |
| 1225 |
|
| 1226 |
When using ``pytest.raises`` as a context manager, it's worthwhile to |
| 1227 |
note that normal context manager rules apply and that the exception |
| 1228 |
raised *must* be the final line in the scope of the context manager. |
| 1229 |
Lines of code after that, within the scope of the context manager will |
| 1230 |
not be executed. For example:: |
| 1231 |
|
| 1232 |
>>> with raises(OSError) as exc_info: |
| 1233 |
assert 1 == 1 # this will execute as expected |
| 1234 |
raise OSError(errno.EEXISTS, 'directory exists') |
| 1235 |
assert exc_info.value.errno == errno.EEXISTS # this will not execute |
| 1236 |
|
| 1237 |
Instead, the following approach must be taken (note the difference in |
| 1238 |
scope):: |
| 1239 |
|
| 1240 |
>>> with raises(OSError) as exc_info: |
| 1241 |
assert 1 == 1 # this will execute as expected |
| 1242 |
raise OSError(errno.EEXISTS, 'directory exists') |
| 1243 |
|
| 1244 |
assert exc_info.value.errno == errno.EEXISTS # this will now execute |
| 1245 |
|
| 1246 |
Or you can specify a callable by passing a to-be-called lambda:: |
| 1247 |
|
| 1248 |
>>> raises(ZeroDivisionError, lambda: 1/0) |
| 1249 |
<ExceptionInfo ...> |
| 1250 |
|
| 1251 |
or you can specify an arbitrary callable with arguments:: |
| 1252 |
|
| 1253 |
>>> def f(x): return 1/x |
| 1254 |
... |
| 1255 |
>>> raises(ZeroDivisionError, f, 0) |
| 1256 |
<ExceptionInfo ...> |
| 1257 |
>>> raises(ZeroDivisionError, f, x=0) |
| 1258 |
<ExceptionInfo ...> |
| 1259 |
|
| 1260 |
A third possibility is to use a string to be executed:: |
| 1261 |
|
| 1262 |
>>> raises(ZeroDivisionError, "f(0)") |
| 1263 |
<ExceptionInfo ...> |
| 1264 |
|
| 1265 |
.. autoclass:: _pytest._code.ExceptionInfo |
| 1266 |
:members: |
| 1267 |
|
| 1268 |
.. note:: |
| 1269 |
Similar to caught exception objects in Python, explicitly clearing |
| 1270 |
local references to returned ``ExceptionInfo`` objects can |
| 1271 |
help the Python interpreter speed up its garbage collection. |
| 1272 |
|
| 1273 |
Clearing those references breaks a reference cycle |
| 1274 |
(``ExceptionInfo`` --> caught exception --> frame stack raising |
| 1275 |
the exception --> current frame stack --> local variables --> |
| 1276 |
``ExceptionInfo``) which makes Python keep all objects referenced |
| 1277 |
from that cycle (including all local variables in the current |
| 1278 |
frame) alive until the next cyclic garbage collection run. See the |
| 1279 |
official Python ``try`` statement documentation for more detailed |
| 1280 |
information. |
| 1281 |
|
| 1282 |
""" |
| 1283 |
__tracebackhide__ = True |
| 1284 |
if expected_exception is AssertionError: |
| 1285 |
|
| 1286 |
|
| 1287 |
|
| 1288 |
from _pytest.assertion.util import BuiltinAssertionError \ |
| 1289 |
as expected_exception |
| 1290 |
msg = ("exceptions must be old-style classes or" |
| 1291 |
" derived from BaseException, not %s") |
| 1292 |
if isinstance(expected_exception, tuple): |
| 1293 |
for exc in expected_exception: |
| 1294 |
if not isclass(exc): |
| 1295 |
raise TypeError(msg % type(exc)) |
| 1296 |
elif not isclass(expected_exception): |
| 1297 |
raise TypeError(msg % type(expected_exception)) |
| 1298 |
|
| 1299 |
if not args: |
| 1300 |
return RaisesContext(expected_exception) |
| 1301 |
elif isinstance(args[0], str): |
| 1302 |
code, = args |
| 1303 |
assert isinstance(code, str) |
| 1304 |
frame = sys._getframe(1) |
| 1305 |
loc = frame.f_locals.copy() |
| 1306 |
loc.update(kwargs) |
| 1307 |
|
| 1308 |
try: |
| 1309 |
code = _pytest._code.Source(code).compile() |
| 1310 |
py.builtin.exec_(code, frame.f_globals, loc) |
| 1311 |
|
| 1312 |
|
| 1313 |
except expected_exception: |
| 1314 |
return _pytest._code.ExceptionInfo() |
| 1315 |
else: |
| 1316 |
func = args[0] |
| 1317 |
try: |
| 1318 |
func(*args[1:], **kwargs) |
| 1319 |
except expected_exception: |
| 1320 |
return _pytest._code.ExceptionInfo() |
| 1321 |
pytest.fail("DID NOT RAISE {0}".format(expected_exception)) |
| 1322 |
|
| 1323 |
class RaisesContext(object): |
| 1324 |
def __init__(self, expected_exception): |
| 1325 |
self.expected_exception = expected_exception |
| 1326 |
self.excinfo = None |
| 1327 |
|
| 1328 |
def __enter__(self): |
| 1329 |
self.excinfo = object.__new__(_pytest._code.ExceptionInfo) |
| 1330 |
return self.excinfo |
| 1331 |
|
| 1332 |
def __exit__(self, *tp): |
| 1333 |
__tracebackhide__ = True |
| 1334 |
if tp[0] is None: |
| 1335 |
pytest.fail("DID NOT RAISE") |
| 1336 |
if sys.version_info < (2, 7): |
| 1337 |
|
| 1338 |
|
| 1339 |
|
| 1340 |
if not isinstance(tp[1], BaseException): |
| 1341 |
exc_type, value, traceback = tp |
| 1342 |
tp = exc_type, exc_type(value), traceback |
| 1343 |
self.excinfo.__init__(tp) |
| 1344 |
return issubclass(self.excinfo.type, self.expected_exception) |
| 1345 |
|
| 1346 |
|
| 1347 |
|
| 1348 |
|
| 1349 |
|
| 1350 |
class Function(FunctionMixin, pytest.Item, FuncargnamesCompatAttr): |
| 1351 |
""" a Function Item is responsible for setting up and executing a |
| 1352 |
Python test function. |
| 1353 |
""" |
| 1354 |
_genid = None |
| 1355 |
def __init__(self, name, parent, args=None, config=None, |
| 1356 |
callspec=None, callobj=NOTSET, keywords=None, session=None, |
| 1357 |
fixtureinfo=None): |
| 1358 |
super(Function, self).__init__(name, parent, config=config, |
| 1359 |
session=session) |
| 1360 |
self._args = args |
| 1361 |
if callobj is not NOTSET: |
| 1362 |
self.obj = callobj |
| 1363 |
|
| 1364 |
self.keywords.update(self.obj.__dict__) |
| 1365 |
if callspec: |
| 1366 |
self.callspec = callspec |
| 1367 |
self.keywords.update(callspec.keywords) |
| 1368 |
if keywords: |
| 1369 |
self.keywords.update(keywords) |
| 1370 |
|
| 1371 |
if fixtureinfo is None: |
| 1372 |
fixtureinfo = self.session._fixturemanager.getfixtureinfo( |
| 1373 |
self.parent, self.obj, self.cls, |
| 1374 |
funcargs=not self._isyieldedfunction()) |
| 1375 |
self._fixtureinfo = fixtureinfo |
| 1376 |
self.fixturenames = fixtureinfo.names_closure |
| 1377 |
self._initrequest() |
| 1378 |
|
| 1379 |
def _initrequest(self): |
| 1380 |
self.funcargs = {} |
| 1381 |
if self._isyieldedfunction(): |
| 1382 |
assert not hasattr(self, "callspec"), ( |
| 1383 |
"yielded functions (deprecated) cannot have funcargs") |
| 1384 |
else: |
| 1385 |
if hasattr(self, "callspec"): |
| 1386 |
callspec = self.callspec |
| 1387 |
assert not callspec.funcargs |
| 1388 |
self._genid = callspec.id |
| 1389 |
if hasattr(callspec, "param"): |
| 1390 |
self.param = callspec.param |
| 1391 |
self._request = FixtureRequest(self) |
| 1392 |
|
| 1393 |
@property |
| 1394 |
def function(self): |
| 1395 |
"underlying python 'function' object" |
| 1396 |
return getattr(self.obj, 'im_func', self.obj) |
| 1397 |
|
| 1398 |
def _getobj(self): |
| 1399 |
name = self.name |
| 1400 |
i = name.find("[") |
| 1401 |
if i != -1: |
| 1402 |
name = name[:i] |
| 1403 |
return getattr(self.parent.obj, name) |
| 1404 |
|
| 1405 |
@property |
| 1406 |
def _pyfuncitem(self): |
| 1407 |
"(compatonly) for code expecting pytest-2.2 style request objects" |
| 1408 |
return self |
| 1409 |
|
| 1410 |
def _isyieldedfunction(self): |
| 1411 |
return getattr(self, "_args", None) is not None |
| 1412 |
|
| 1413 |
def runtest(self): |
| 1414 |
""" execute the underlying test function. """ |
| 1415 |
self.ihook.pytest_pyfunc_call(pyfuncitem=self) |
| 1416 |
|
| 1417 |
def setup(self): |
| 1418 |
super(Function, self).setup() |
| 1419 |
fillfixtures(self) |
| 1420 |
|
| 1421 |
|
| 1422 |
scope2props = dict(session=()) |
| 1423 |
scope2props["module"] = ("fspath", "module") |
| 1424 |
scope2props["class"] = scope2props["module"] + ("cls",) |
| 1425 |
scope2props["instance"] = scope2props["class"] + ("instance", ) |
| 1426 |
scope2props["function"] = scope2props["instance"] + ("function", "keywords") |
| 1427 |
|
| 1428 |
def scopeproperty(name=None, doc=None): |
| 1429 |
def decoratescope(func): |
| 1430 |
scopename = name or func.__name__ |
| 1431 |
def provide(self): |
| 1432 |
if func.__name__ in scope2props[self.scope]: |
| 1433 |
return func(self) |
| 1434 |
raise AttributeError("%s not available in %s-scoped context" % ( |
| 1435 |
scopename, self.scope)) |
| 1436 |
return property(provide, None, None, func.__doc__) |
| 1437 |
return decoratescope |
| 1438 |
|
| 1439 |
|
| 1440 |
class FixtureRequest(FuncargnamesCompatAttr): |
| 1441 |
""" A request for a fixture from a test or fixture function. |
| 1442 |
|
| 1443 |
A request object gives access to the requesting test context |
| 1444 |
and has an optional ``param`` attribute in case |
| 1445 |
the fixture is parametrized indirectly. |
| 1446 |
""" |
| 1447 |
|
| 1448 |
def __init__(self, pyfuncitem): |
| 1449 |
self._pyfuncitem = pyfuncitem |
| 1450 |
|
| 1451 |
self.fixturename = None |
| 1452 |
|
| 1453 |
self.scope = "function" |
| 1454 |
self._funcargs = {} |
| 1455 |
self._fixturedefs = {} |
| 1456 |
fixtureinfo = pyfuncitem._fixtureinfo |
| 1457 |
self._arg2fixturedefs = fixtureinfo.name2fixturedefs.copy() |
| 1458 |
self._arg2index = {} |
| 1459 |
self.fixturenames = fixtureinfo.names_closure |
| 1460 |
self._fixturemanager = pyfuncitem.session._fixturemanager |
| 1461 |
|
| 1462 |
@property |
| 1463 |
def node(self): |
| 1464 |
""" underlying collection node (depends on current request scope)""" |
| 1465 |
return self._getscopeitem(self.scope) |
| 1466 |
|
| 1467 |
|
| 1468 |
def _getnextfixturedef(self, argname): |
| 1469 |
fixturedefs = self._arg2fixturedefs.get(argname, None) |
| 1470 |
if fixturedefs is None: |
| 1471 |
|
| 1472 |
|
| 1473 |
|
| 1474 |
fixturedefs = self._fixturemanager.getfixturedefs( |
| 1475 |
argname, self._pyfuncitem.parent.nodeid) |
| 1476 |
self._arg2fixturedefs[argname] = fixturedefs |
| 1477 |
|
| 1478 |
index = self._arg2index.get(argname, 0) - 1 |
| 1479 |
if fixturedefs is None or (-index > len(fixturedefs)): |
| 1480 |
raise FixtureLookupError(argname, self) |
| 1481 |
self._arg2index[argname] = index |
| 1482 |
return fixturedefs[index] |
| 1483 |
|
| 1484 |
@property |
| 1485 |
def config(self): |
| 1486 |
""" the pytest config object associated with this request. """ |
| 1487 |
return self._pyfuncitem.config |
| 1488 |
|
| 1489 |
|
| 1490 |
@scopeproperty() |
| 1491 |
def function(self): |
| 1492 |
""" test function object if the request has a per-function scope. """ |
| 1493 |
return self._pyfuncitem.obj |
| 1494 |
|
| 1495 |
@scopeproperty("class") |
| 1496 |
def cls(self): |
| 1497 |
""" class (can be None) where the test function was collected. """ |
| 1498 |
clscol = self._pyfuncitem.getparent(pytest.Class) |
| 1499 |
if clscol: |
| 1500 |
return clscol.obj |
| 1501 |
|
| 1502 |
@property |
| 1503 |
def instance(self): |
| 1504 |
""" instance (can be None) on which test function was collected. """ |
| 1505 |
|
| 1506 |
try: |
| 1507 |
return self._pyfuncitem._testcase |
| 1508 |
except AttributeError: |
| 1509 |
function = getattr(self, "function", None) |
| 1510 |
if function is not None: |
| 1511 |
return py.builtin._getimself(function) |
| 1512 |
|
| 1513 |
@scopeproperty() |
| 1514 |
def module(self): |
| 1515 |
""" python module object where the test function was collected. """ |
| 1516 |
return self._pyfuncitem.getparent(pytest.Module).obj |
| 1517 |
|
| 1518 |
@scopeproperty() |
| 1519 |
def fspath(self): |
| 1520 |
""" the file system path of the test module which collected this test. """ |
| 1521 |
return self._pyfuncitem.fspath |
| 1522 |
|
| 1523 |
@property |
| 1524 |
def keywords(self): |
| 1525 |
""" keywords/markers dictionary for the underlying node. """ |
| 1526 |
return self.node.keywords |
| 1527 |
|
| 1528 |
@property |
| 1529 |
def session(self): |
| 1530 |
""" pytest session object. """ |
| 1531 |
return self._pyfuncitem.session |
| 1532 |
|
| 1533 |
def addfinalizer(self, finalizer): |
| 1534 |
""" add finalizer/teardown function to be called after the |
| 1535 |
last test within the requesting test context finished |
| 1536 |
execution. """ |
| 1537 |
|
| 1538 |
self._addfinalizer(finalizer, scope=self.scope) |
| 1539 |
|
| 1540 |
def _addfinalizer(self, finalizer, scope): |
| 1541 |
colitem = self._getscopeitem(scope) |
| 1542 |
self._pyfuncitem.session._setupstate.addfinalizer( |
| 1543 |
finalizer=finalizer, colitem=colitem) |
| 1544 |
|
| 1545 |
def applymarker(self, marker): |
| 1546 |
""" Apply a marker to a single test function invocation. |
| 1547 |
This method is useful if you don't want to have a keyword/marker |
| 1548 |
on all function invocations. |
| 1549 |
|
| 1550 |
:arg marker: a :py:class:`_pytest.mark.MarkDecorator` object |
| 1551 |
created by a call to ``pytest.mark.NAME(...)``. |
| 1552 |
""" |
| 1553 |
try: |
| 1554 |
self.node.keywords[marker.markname] = marker |
| 1555 |
except AttributeError: |
| 1556 |
raise ValueError(marker) |
| 1557 |
|
| 1558 |
def raiseerror(self, msg): |
| 1559 |
""" raise a FixtureLookupError with the given message. """ |
| 1560 |
raise self._fixturemanager.FixtureLookupError(None, self, msg) |
| 1561 |
|
| 1562 |
def _fillfixtures(self): |
| 1563 |
item = self._pyfuncitem |
| 1564 |
fixturenames = getattr(item, "fixturenames", self.fixturenames) |
| 1565 |
for argname in fixturenames: |
| 1566 |
if argname not in item.funcargs: |
| 1567 |
item.funcargs[argname] = self.getfuncargvalue(argname) |
| 1568 |
|
| 1569 |
def cached_setup(self, setup, teardown=None, scope="module", extrakey=None): |
| 1570 |
""" (deprecated) Return a testing resource managed by ``setup`` & |
| 1571 |
``teardown`` calls. ``scope`` and ``extrakey`` determine when the |
| 1572 |
``teardown`` function will be called so that subsequent calls to |
| 1573 |
``setup`` would recreate the resource. With pytest-2.3 you often |
| 1574 |
do not need ``cached_setup()`` as you can directly declare a scope |
| 1575 |
on a fixture function and register a finalizer through |
| 1576 |
``request.addfinalizer()``. |
| 1577 |
|
| 1578 |
:arg teardown: function receiving a previously setup resource. |
| 1579 |
:arg setup: a no-argument function creating a resource. |
| 1580 |
:arg scope: a string value out of ``function``, ``class``, ``module`` |
| 1581 |
or ``session`` indicating the caching lifecycle of the resource. |
| 1582 |
:arg extrakey: added to internal caching key of (funcargname, scope). |
| 1583 |
""" |
| 1584 |
if not hasattr(self.config, '_setupcache'): |
| 1585 |
self.config._setupcache = {} |
| 1586 |
cachekey = (self.fixturename, self._getscopeitem(scope), extrakey) |
| 1587 |
cache = self.config._setupcache |
| 1588 |
try: |
| 1589 |
val = cache[cachekey] |
| 1590 |
except KeyError: |
| 1591 |
self._check_scope(self.fixturename, self.scope, scope) |
| 1592 |
val = setup() |
| 1593 |
cache[cachekey] = val |
| 1594 |
if teardown is not None: |
| 1595 |
def finalizer(): |
| 1596 |
del cache[cachekey] |
| 1597 |
teardown(val) |
| 1598 |
self._addfinalizer(finalizer, scope=scope) |
| 1599 |
return val |
| 1600 |
|
| 1601 |
def getfuncargvalue(self, argname): |
| 1602 |
""" Dynamically retrieve a named fixture function argument. |
| 1603 |
|
| 1604 |
As of pytest-2.3, it is easier and usually better to access other |
| 1605 |
fixture values by stating it as an input argument in the fixture |
| 1606 |
function. If you only can decide about using another fixture at test |
| 1607 |
setup time, you may use this function to retrieve it inside a fixture |
| 1608 |
function body. |
| 1609 |
""" |
| 1610 |
return self._get_active_fixturedef(argname).cached_result[0] |
| 1611 |
|
| 1612 |
def _get_active_fixturedef(self, argname): |
| 1613 |
try: |
| 1614 |
return self._fixturedefs[argname] |
| 1615 |
except KeyError: |
| 1616 |
try: |
| 1617 |
fixturedef = self._getnextfixturedef(argname) |
| 1618 |
except FixtureLookupError: |
| 1619 |
if argname == "request": |
| 1620 |
class PseudoFixtureDef: |
| 1621 |
cached_result = (self, [0], None) |
| 1622 |
scope = "function" |
| 1623 |
return PseudoFixtureDef |
| 1624 |
raise |
| 1625 |
|
| 1626 |
|
| 1627 |
result = self._getfuncargvalue(fixturedef) |
| 1628 |
self._funcargs[argname] = result |
| 1629 |
self._fixturedefs[argname] = fixturedef |
| 1630 |
return fixturedef |
| 1631 |
|
| 1632 |
def _get_fixturestack(self): |
| 1633 |
current = self |
| 1634 |
l = [] |
| 1635 |
while 1: |
| 1636 |
fixturedef = getattr(current, "_fixturedef", None) |
| 1637 |
if fixturedef is None: |
| 1638 |
l.reverse() |
| 1639 |
return l |
| 1640 |
l.append(fixturedef) |
| 1641 |
current = current._parent_request |
| 1642 |
|
| 1643 |
def _getfuncargvalue(self, fixturedef): |
| 1644 |
|
| 1645 |
|
| 1646 |
argname = fixturedef.argname |
| 1647 |
funcitem = self._pyfuncitem |
| 1648 |
scope = fixturedef.scope |
| 1649 |
try: |
| 1650 |
param = funcitem.callspec.getparam(argname) |
| 1651 |
except (AttributeError, ValueError): |
| 1652 |
param = NOTSET |
| 1653 |
param_index = 0 |
| 1654 |
else: |
| 1655 |
|
| 1656 |
param_index = funcitem.callspec.indices.get(argname, 0) |
| 1657 |
|
| 1658 |
|
| 1659 |
paramscopenum = funcitem.callspec._arg2scopenum.get(argname) |
| 1660 |
if paramscopenum is not None: |
| 1661 |
scope = scopes[paramscopenum] |
| 1662 |
|
| 1663 |
subrequest = SubRequest(self, scope, param, param_index, fixturedef) |
| 1664 |
|
| 1665 |
|
| 1666 |
subrequest._check_scope(argname, self.scope, scope) |
| 1667 |
|
| 1668 |
|
| 1669 |
|
| 1670 |
exc_clear() |
| 1671 |
try: |
| 1672 |
|
| 1673 |
val = fixturedef.execute(request=subrequest) |
| 1674 |
finally: |
| 1675 |
|
| 1676 |
self.session._setupstate.addfinalizer(fixturedef.finish, |
| 1677 |
subrequest.node) |
| 1678 |
return val |
| 1679 |
|
| 1680 |
def _check_scope(self, argname, invoking_scope, requested_scope): |
| 1681 |
if argname == "request": |
| 1682 |
return |
| 1683 |
if scopemismatch(invoking_scope, requested_scope): |
| 1684 |
|
| 1685 |
lines = self._factorytraceback() |
| 1686 |
pytest.fail("ScopeMismatch: You tried to access the %r scoped " |
| 1687 |
"fixture %r with a %r scoped request object, " |
| 1688 |
"involved factories\n%s" %( |
| 1689 |
(requested_scope, argname, invoking_scope, "\n".join(lines))), |
| 1690 |
pytrace=False) |
| 1691 |
|
| 1692 |
def _factorytraceback(self): |
| 1693 |
lines = [] |
| 1694 |
for fixturedef in self._get_fixturestack(): |
| 1695 |
factory = fixturedef.func |
| 1696 |
fs, lineno = getfslineno(factory) |
| 1697 |
p = self._pyfuncitem.session.fspath.bestrelpath(fs) |
| 1698 |
args = _format_args(factory) |
| 1699 |
lines.append("%s:%d: def %s%s" %( |
| 1700 |
p, lineno, factory.__name__, args)) |
| 1701 |
return lines |
| 1702 |
|
| 1703 |
def _getscopeitem(self, scope): |
| 1704 |
if scope == "function": |
| 1705 |
|
| 1706 |
return self._pyfuncitem |
| 1707 |
node = get_scope_node(self._pyfuncitem, scope) |
| 1708 |
if node is None and scope == "class": |
| 1709 |
|
| 1710 |
node = self._pyfuncitem |
| 1711 |
assert node |
| 1712 |
return node |
| 1713 |
|
| 1714 |
def __repr__(self): |
| 1715 |
return "<FixtureRequest for %r>" %(self.node) |
| 1716 |
|
| 1717 |
|
| 1718 |
class SubRequest(FixtureRequest): |
| 1719 |
""" a sub request for handling getting a fixture from a |
| 1720 |
test function/fixture. """ |
| 1721 |
def __init__(self, request, scope, param, param_index, fixturedef): |
| 1722 |
self._parent_request = request |
| 1723 |
self.fixturename = fixturedef.argname |
| 1724 |
if param is not NOTSET: |
| 1725 |
self.param = param |
| 1726 |
self.param_index = param_index |
| 1727 |
self.scope = scope |
| 1728 |
self._fixturedef = fixturedef |
| 1729 |
self.addfinalizer = fixturedef.addfinalizer |
| 1730 |
self._pyfuncitem = request._pyfuncitem |
| 1731 |
self._funcargs = request._funcargs |
| 1732 |
self._fixturedefs = request._fixturedefs |
| 1733 |
self._arg2fixturedefs = request._arg2fixturedefs |
| 1734 |
self._arg2index = request._arg2index |
| 1735 |
self.fixturenames = request.fixturenames |
| 1736 |
self._fixturemanager = request._fixturemanager |
| 1737 |
|
| 1738 |
def __repr__(self): |
| 1739 |
return "<SubRequest %r for %r>" % (self.fixturename, self._pyfuncitem) |
| 1740 |
|
| 1741 |
|
| 1742 |
class ScopeMismatchError(Exception): |
| 1743 |
""" A fixture function tries to use a different fixture function which |
| 1744 |
which has a lower scope (e.g. a Session one calls a function one) |
| 1745 |
""" |
| 1746 |
|
| 1747 |
scopes = "session module class function".split() |
| 1748 |
scopenum_function = scopes.index("function") |
| 1749 |
def scopemismatch(currentscope, newscope): |
| 1750 |
return scopes.index(newscope) > scopes.index(currentscope) |
| 1751 |
|
| 1752 |
|
| 1753 |
class FixtureLookupError(LookupError): |
| 1754 |
""" could not return a requested Fixture (missing or invalid). """ |
| 1755 |
def __init__(self, argname, request, msg=None): |
| 1756 |
self.argname = argname |
| 1757 |
self.request = request |
| 1758 |
self.fixturestack = request._get_fixturestack() |
| 1759 |
self.msg = msg |
| 1760 |
|
| 1761 |
def formatrepr(self): |
| 1762 |
tblines = [] |
| 1763 |
addline = tblines.append |
| 1764 |
stack = [self.request._pyfuncitem.obj] |
| 1765 |
stack.extend(map(lambda x: x.func, self.fixturestack)) |
| 1766 |
msg = self.msg |
| 1767 |
if msg is not None: |
| 1768 |
|
| 1769 |
|
| 1770 |
stack = stack[:-1] |
| 1771 |
for function in stack: |
| 1772 |
fspath, lineno = getfslineno(function) |
| 1773 |
try: |
| 1774 |
lines, _ = inspect.getsourcelines(get_real_func(function)) |
| 1775 |
except (IOError, IndexError): |
| 1776 |
error_msg = "file %s, line %s: source code not available" |
| 1777 |
addline(error_msg % (fspath, lineno+1)) |
| 1778 |
else: |
| 1779 |
addline("file %s, line %s" % (fspath, lineno+1)) |
| 1780 |
for i, line in enumerate(lines): |
| 1781 |
line = line.rstrip() |
| 1782 |
addline(" " + line) |
| 1783 |
if line.lstrip().startswith('def'): |
| 1784 |
break |
| 1785 |
|
| 1786 |
if msg is None: |
| 1787 |
fm = self.request._fixturemanager |
| 1788 |
available = [] |
| 1789 |
for name, fixturedef in fm._arg2fixturedefs.items(): |
| 1790 |
parentid = self.request._pyfuncitem.parent.nodeid |
| 1791 |
faclist = list(fm._matchfactories(fixturedef, parentid)) |
| 1792 |
if faclist: |
| 1793 |
available.append(name) |
| 1794 |
msg = "fixture %r not found" % (self.argname,) |
| 1795 |
msg += "\n available fixtures: %s" %(", ".join(available),) |
| 1796 |
msg += "\n use 'py.test --fixtures [testpath]' for help on them." |
| 1797 |
|
| 1798 |
return FixtureLookupErrorRepr(fspath, lineno, tblines, msg, self.argname) |
| 1799 |
|
| 1800 |
class FixtureLookupErrorRepr(TerminalRepr): |
| 1801 |
def __init__(self, filename, firstlineno, tblines, errorstring, argname): |
| 1802 |
self.tblines = tblines |
| 1803 |
self.errorstring = errorstring |
| 1804 |
self.filename = filename |
| 1805 |
self.firstlineno = firstlineno |
| 1806 |
self.argname = argname |
| 1807 |
|
| 1808 |
def toterminal(self, tw): |
| 1809 |
|
| 1810 |
for tbline in self.tblines: |
| 1811 |
tw.line(tbline.rstrip()) |
| 1812 |
for line in self.errorstring.split("\n"): |
| 1813 |
tw.line(" " + line.strip(), red=True) |
| 1814 |
tw.line() |
| 1815 |
tw.line("%s:%d" % (self.filename, self.firstlineno+1)) |
| 1816 |
|
| 1817 |
class FixtureManager: |
| 1818 |
""" |
| 1819 |
pytest fixtures definitions and information is stored and managed |
| 1820 |
from this class. |
| 1821 |
|
| 1822 |
During collection fm.parsefactories() is called multiple times to parse |
| 1823 |
fixture function definitions into FixtureDef objects and internal |
| 1824 |
data structures. |
| 1825 |
|
| 1826 |
During collection of test functions, metafunc-mechanics instantiate |
| 1827 |
a FuncFixtureInfo object which is cached per node/func-name. |
| 1828 |
This FuncFixtureInfo object is later retrieved by Function nodes |
| 1829 |
which themselves offer a fixturenames attribute. |
| 1830 |
|
| 1831 |
The FuncFixtureInfo object holds information about fixtures and FixtureDefs |
| 1832 |
relevant for a particular function. An initial list of fixtures is |
| 1833 |
assembled like this: |
| 1834 |
|
| 1835 |
- ini-defined usefixtures |
| 1836 |
- autouse-marked fixtures along the collection chain up from the function |
| 1837 |
- usefixtures markers at module/class/function level |
| 1838 |
- test function funcargs |
| 1839 |
|
| 1840 |
Subsequently the funcfixtureinfo.fixturenames attribute is computed |
| 1841 |
as the closure of the fixtures needed to setup the initial fixtures, |
| 1842 |
i. e. fixtures needed by fixture functions themselves are appended |
| 1843 |
to the fixturenames list. |
| 1844 |
|
| 1845 |
Upon the test-setup phases all fixturenames are instantiated, retrieved |
| 1846 |
by a lookup of their FuncFixtureInfo. |
| 1847 |
""" |
| 1848 |
|
| 1849 |
_argprefix = "pytest_funcarg__" |
| 1850 |
FixtureLookupError = FixtureLookupError |
| 1851 |
FixtureLookupErrorRepr = FixtureLookupErrorRepr |
| 1852 |
|
| 1853 |
def __init__(self, session): |
| 1854 |
self.session = session |
| 1855 |
self.config = session.config |
| 1856 |
self._arg2fixturedefs = {} |
| 1857 |
self._holderobjseen = set() |
| 1858 |
self._arg2finish = {} |
| 1859 |
self._nodeid_and_autousenames = [("", self.config.getini("usefixtures"))] |
| 1860 |
session.config.pluginmanager.register(self, "funcmanage") |
| 1861 |
|
| 1862 |
|
| 1863 |
def getfixtureinfo(self, node, func, cls, funcargs=True): |
| 1864 |
if funcargs and not hasattr(node, "nofuncargs"): |
| 1865 |
if cls is not None: |
| 1866 |
startindex = 1 |
| 1867 |
else: |
| 1868 |
startindex = None |
| 1869 |
argnames = getfuncargnames(func, startindex) |
| 1870 |
else: |
| 1871 |
argnames = () |
| 1872 |
usefixtures = getattr(func, "usefixtures", None) |
| 1873 |
initialnames = argnames |
| 1874 |
if usefixtures is not None: |
| 1875 |
initialnames = usefixtures.args + initialnames |
| 1876 |
fm = node.session._fixturemanager |
| 1877 |
names_closure, arg2fixturedefs = fm.getfixtureclosure(initialnames, |
| 1878 |
node) |
| 1879 |
return FuncFixtureInfo(argnames, names_closure, arg2fixturedefs) |
| 1880 |
|
| 1881 |
def pytest_plugin_registered(self, plugin): |
| 1882 |
nodeid = None |
| 1883 |
try: |
| 1884 |
p = py.path.local(plugin.__file__) |
| 1885 |
except AttributeError: |
| 1886 |
pass |
| 1887 |
else: |
| 1888 |
|
| 1889 |
|
| 1890 |
|
| 1891 |
if p.basename.startswith("conftest.py"): |
| 1892 |
nodeid = p.dirpath().relto(self.config.rootdir) |
| 1893 |
if p.sep != "/": |
| 1894 |
nodeid = nodeid.replace(p.sep, "/") |
| 1895 |
self.parsefactories(plugin, nodeid) |
| 1896 |
|
| 1897 |
def _getautousenames(self, nodeid): |
| 1898 |
""" return a tuple of fixture names to be used. """ |
| 1899 |
autousenames = [] |
| 1900 |
for baseid, basenames in self._nodeid_and_autousenames: |
| 1901 |
if nodeid.startswith(baseid): |
| 1902 |
if baseid: |
| 1903 |
i = len(baseid) |
| 1904 |
nextchar = nodeid[i:i+1] |
| 1905 |
if nextchar and nextchar not in ":/": |
| 1906 |
continue |
| 1907 |
autousenames.extend(basenames) |
| 1908 |
|
| 1909 |
autousenames.sort( |
| 1910 |
key=lambda x: self._arg2fixturedefs[x][-1].scopenum) |
| 1911 |
return autousenames |
| 1912 |
|
| 1913 |
def getfixtureclosure(self, fixturenames, parentnode): |
| 1914 |
|
| 1915 |
|
| 1916 |
|
| 1917 |
|
| 1918 |
|
| 1919 |
|
| 1920 |
|
| 1921 |
parentid = parentnode.nodeid |
| 1922 |
fixturenames_closure = self._getautousenames(parentid) |
| 1923 |
def merge(otherlist): |
| 1924 |
for arg in otherlist: |
| 1925 |
if arg not in fixturenames_closure: |
| 1926 |
fixturenames_closure.append(arg) |
| 1927 |
merge(fixturenames) |
| 1928 |
arg2fixturedefs = {} |
| 1929 |
lastlen = -1 |
| 1930 |
while lastlen != len(fixturenames_closure): |
| 1931 |
lastlen = len(fixturenames_closure) |
| 1932 |
for argname in fixturenames_closure: |
| 1933 |
if argname in arg2fixturedefs: |
| 1934 |
continue |
| 1935 |
fixturedefs = self.getfixturedefs(argname, parentid) |
| 1936 |
if fixturedefs: |
| 1937 |
arg2fixturedefs[argname] = fixturedefs |
| 1938 |
merge(fixturedefs[-1].argnames) |
| 1939 |
return fixturenames_closure, arg2fixturedefs |
| 1940 |
|
| 1941 |
def pytest_generate_tests(self, metafunc): |
| 1942 |
for argname in metafunc.fixturenames: |
| 1943 |
faclist = metafunc._arg2fixturedefs.get(argname) |
| 1944 |
if faclist: |
| 1945 |
fixturedef = faclist[-1] |
| 1946 |
if fixturedef.params is not None: |
| 1947 |
func_params = getattr(getattr(metafunc.function, 'parametrize', None), 'args', [[None]]) |
| 1948 |
|
| 1949 |
argnames = func_params[0] |
| 1950 |
if not isinstance(argnames, (tuple, list)): |
| 1951 |
argnames = [x.strip() for x in argnames.split(",") if x.strip()] |
| 1952 |
if argname not in func_params and argname not in argnames: |
| 1953 |
metafunc.parametrize(argname, fixturedef.params, |
| 1954 |
indirect=True, scope=fixturedef.scope, |
| 1955 |
ids=fixturedef.ids) |
| 1956 |
else: |
| 1957 |
continue |
| 1958 |
|
| 1959 |
def pytest_collection_modifyitems(self, items): |
| 1960 |
|
| 1961 |
items[:] = reorder_items(items) |
| 1962 |
|
| 1963 |
def parsefactories(self, node_or_obj, nodeid=NOTSET, unittest=False): |
| 1964 |
if nodeid is not NOTSET: |
| 1965 |
holderobj = node_or_obj |
| 1966 |
else: |
| 1967 |
holderobj = node_or_obj.obj |
| 1968 |
nodeid = node_or_obj.nodeid |
| 1969 |
if holderobj in self._holderobjseen: |
| 1970 |
return |
| 1971 |
self._holderobjseen.add(holderobj) |
| 1972 |
autousenames = [] |
| 1973 |
for name in dir(holderobj): |
| 1974 |
obj = getattr(holderobj, name, None) |
| 1975 |
|
| 1976 |
|
| 1977 |
marker = getfixturemarker(obj) |
| 1978 |
if marker is None: |
| 1979 |
if not name.startswith(self._argprefix): |
| 1980 |
continue |
| 1981 |
if not callable(obj): |
| 1982 |
continue |
| 1983 |
marker = defaultfuncargprefixmarker |
| 1984 |
name = name[len(self._argprefix):] |
| 1985 |
elif not isinstance(marker, FixtureFunctionMarker): |
| 1986 |
|
| 1987 |
|
| 1988 |
continue |
| 1989 |
else: |
| 1990 |
assert not name.startswith(self._argprefix) |
| 1991 |
fixturedef = FixtureDef(self, nodeid, name, obj, |
| 1992 |
marker.scope, marker.params, |
| 1993 |
yieldctx=marker.yieldctx, |
| 1994 |
unittest=unittest, ids=marker.ids) |
| 1995 |
faclist = self._arg2fixturedefs.setdefault(name, []) |
| 1996 |
if fixturedef.has_location: |
| 1997 |
faclist.append(fixturedef) |
| 1998 |
else: |
| 1999 |
|
| 2000 |
|
| 2001 |
|
| 2002 |
|
| 2003 |
i = len([f for f in faclist if not f.has_location]) |
| 2004 |
faclist.insert(i, fixturedef) |
| 2005 |
if marker.autouse: |
| 2006 |
autousenames.append(name) |
| 2007 |
if autousenames: |
| 2008 |
self._nodeid_and_autousenames.append((nodeid or '', autousenames)) |
| 2009 |
|
| 2010 |
def getfixturedefs(self, argname, nodeid): |
| 2011 |
try: |
| 2012 |
fixturedefs = self._arg2fixturedefs[argname] |
| 2013 |
except KeyError: |
| 2014 |
return None |
| 2015 |
else: |
| 2016 |
return tuple(self._matchfactories(fixturedefs, nodeid)) |
| 2017 |
|
| 2018 |
def _matchfactories(self, fixturedefs, nodeid): |
| 2019 |
for fixturedef in fixturedefs: |
| 2020 |
if nodeid.startswith(fixturedef.baseid): |
| 2021 |
yield fixturedef |
| 2022 |
|
| 2023 |
|
| 2024 |
def fail_fixturefunc(fixturefunc, msg): |
| 2025 |
fs, lineno = getfslineno(fixturefunc) |
| 2026 |
location = "%s:%s" % (fs, lineno+1) |
| 2027 |
source = _pytest._code.Source(fixturefunc) |
| 2028 |
pytest.fail(msg + ":\n\n" + str(source.indent()) + "\n" + location, |
| 2029 |
pytrace=False) |
| 2030 |
|
| 2031 |
def call_fixture_func(fixturefunc, request, kwargs, yieldctx): |
| 2032 |
if yieldctx: |
| 2033 |
if not is_generator(fixturefunc): |
| 2034 |
fail_fixturefunc(fixturefunc, |
| 2035 |
msg="yield_fixture requires yield statement in function") |
| 2036 |
iter = fixturefunc(**kwargs) |
| 2037 |
next = getattr(iter, "__next__", None) |
| 2038 |
if next is None: |
| 2039 |
next = getattr(iter, "next") |
| 2040 |
res = next() |
| 2041 |
def teardown(): |
| 2042 |
try: |
| 2043 |
next() |
| 2044 |
except StopIteration: |
| 2045 |
pass |
| 2046 |
else: |
| 2047 |
fail_fixturefunc(fixturefunc, |
| 2048 |
"yield_fixture function has more than one 'yield'") |
| 2049 |
request.addfinalizer(teardown) |
| 2050 |
else: |
| 2051 |
if is_generator(fixturefunc): |
| 2052 |
fail_fixturefunc(fixturefunc, |
| 2053 |
msg="pytest.fixture functions cannot use ``yield``. " |
| 2054 |
"Instead write and return an inner function/generator " |
| 2055 |
"and let the consumer call and iterate over it.") |
| 2056 |
res = fixturefunc(**kwargs) |
| 2057 |
return res |
| 2058 |
|
| 2059 |
class FixtureDef: |
| 2060 |
""" A container for a factory definition. """ |
| 2061 |
def __init__(self, fixturemanager, baseid, argname, func, scope, params, |
| 2062 |
yieldctx, unittest=False, ids=None): |
| 2063 |
self._fixturemanager = fixturemanager |
| 2064 |
self.baseid = baseid or '' |
| 2065 |
self.has_location = baseid is not None |
| 2066 |
self.func = func |
| 2067 |
self.argname = argname |
| 2068 |
self.scope = scope |
| 2069 |
self.scopenum = scopes.index(scope or "function") |
| 2070 |
self.params = params |
| 2071 |
startindex = unittest and 1 or None |
| 2072 |
self.argnames = getfuncargnames(func, startindex=startindex) |
| 2073 |
self.yieldctx = yieldctx |
| 2074 |
self.unittest = unittest |
| 2075 |
self.ids = ids |
| 2076 |
self._finalizer = [] |
| 2077 |
|
| 2078 |
def addfinalizer(self, finalizer): |
| 2079 |
self._finalizer.append(finalizer) |
| 2080 |
|
| 2081 |
def finish(self): |
| 2082 |
try: |
| 2083 |
while self._finalizer: |
| 2084 |
func = self._finalizer.pop() |
| 2085 |
func() |
| 2086 |
finally: |
| 2087 |
|
| 2088 |
|
| 2089 |
if hasattr(self, "cached_result"): |
| 2090 |
del self.cached_result |
| 2091 |
|
| 2092 |
def execute(self, request): |
| 2093 |
|
| 2094 |
|
| 2095 |
kwargs = {} |
| 2096 |
for argname in self.argnames: |
| 2097 |
fixturedef = request._get_active_fixturedef(argname) |
| 2098 |
result, arg_cache_key, exc = fixturedef.cached_result |
| 2099 |
request._check_scope(argname, request.scope, fixturedef.scope) |
| 2100 |
kwargs[argname] = result |
| 2101 |
if argname != "request": |
| 2102 |
fixturedef.addfinalizer(self.finish) |
| 2103 |
|
| 2104 |
my_cache_key = request.param_index |
| 2105 |
cached_result = getattr(self, "cached_result", None) |
| 2106 |
if cached_result is not None: |
| 2107 |
result, cache_key, err = cached_result |
| 2108 |
if my_cache_key == cache_key: |
| 2109 |
if err is not None: |
| 2110 |
py.builtin._reraise(*err) |
| 2111 |
else: |
| 2112 |
return result |
| 2113 |
|
| 2114 |
|
| 2115 |
self.finish() |
| 2116 |
assert not hasattr(self, "cached_result") |
| 2117 |
|
| 2118 |
fixturefunc = self.func |
| 2119 |
|
| 2120 |
if self.unittest: |
| 2121 |
if request.instance is not None: |
| 2122 |
|
| 2123 |
fixturefunc = self.func.__get__(request.instance) |
| 2124 |
else: |
| 2125 |
|
| 2126 |
|
| 2127 |
|
| 2128 |
if request.instance is not None: |
| 2129 |
fixturefunc = getimfunc(self.func) |
| 2130 |
if fixturefunc != self.func: |
| 2131 |
fixturefunc = fixturefunc.__get__(request.instance) |
| 2132 |
|
| 2133 |
try: |
| 2134 |
result = call_fixture_func(fixturefunc, request, kwargs, |
| 2135 |
self.yieldctx) |
| 2136 |
except Exception: |
| 2137 |
self.cached_result = (None, my_cache_key, sys.exc_info()) |
| 2138 |
raise |
| 2139 |
self.cached_result = (result, my_cache_key, None) |
| 2140 |
return result |
| 2141 |
|
| 2142 |
def __repr__(self): |
| 2143 |
return ("<FixtureDef name=%r scope=%r baseid=%r >" % |
| 2144 |
(self.argname, self.scope, self.baseid)) |
| 2145 |
|
| 2146 |
def num_mock_patch_args(function): |
| 2147 |
""" return number of arguments used up by mock arguments (if any) """ |
| 2148 |
patchings = getattr(function, "patchings", None) |
| 2149 |
if not patchings: |
| 2150 |
return 0 |
| 2151 |
mock = sys.modules.get("mock", sys.modules.get("unittest.mock", None)) |
| 2152 |
if mock is not None: |
| 2153 |
return len([p for p in patchings |
| 2154 |
if not p.attribute_name and p.new is mock.DEFAULT]) |
| 2155 |
return len(patchings) |
| 2156 |
|
| 2157 |
|
| 2158 |
def getfuncargnames(function, startindex=None): |
| 2159 |
|
| 2160 |
|
| 2161 |
realfunction = function |
| 2162 |
while hasattr(realfunction, "__wrapped__"): |
| 2163 |
realfunction = realfunction.__wrapped__ |
| 2164 |
if startindex is None: |
| 2165 |
startindex = inspect.ismethod(function) and 1 or 0 |
| 2166 |
if realfunction != function: |
| 2167 |
startindex += num_mock_patch_args(function) |
| 2168 |
function = realfunction |
| 2169 |
if isinstance(function, functools.partial): |
| 2170 |
argnames = inspect.getargs(_pytest._code.getrawcode(function.func))[0] |
| 2171 |
partial = function |
| 2172 |
argnames = argnames[len(partial.args):] |
| 2173 |
if partial.keywords: |
| 2174 |
for kw in partial.keywords: |
| 2175 |
argnames.remove(kw) |
| 2176 |
else: |
| 2177 |
argnames = inspect.getargs(_pytest._code.getrawcode(function))[0] |
| 2178 |
defaults = getattr(function, 'func_defaults', |
| 2179 |
getattr(function, '__defaults__', None)) or () |
| 2180 |
numdefaults = len(defaults) |
| 2181 |
if numdefaults: |
| 2182 |
return tuple(argnames[startindex:-numdefaults]) |
| 2183 |
return tuple(argnames[startindex:]) |
| 2184 |
|
| 2185 |
|
| 2186 |
|
| 2187 |
|
| 2188 |
|
| 2189 |
|
| 2190 |
def reorder_items(items): |
| 2191 |
argkeys_cache = {} |
| 2192 |
for scopenum in range(0, scopenum_function): |
| 2193 |
argkeys_cache[scopenum] = d = {} |
| 2194 |
for item in items: |
| 2195 |
keys = set(get_parametrized_fixture_keys(item, scopenum)) |
| 2196 |
if keys: |
| 2197 |
d[item] = keys |
| 2198 |
return reorder_items_atscope(items, set(), argkeys_cache, 0) |
| 2199 |
|
| 2200 |
def reorder_items_atscope(items, ignore, argkeys_cache, scopenum): |
| 2201 |
if scopenum >= scopenum_function or len(items) < 3: |
| 2202 |
return items |
| 2203 |
items_done = [] |
| 2204 |
while 1: |
| 2205 |
items_before, items_same, items_other, newignore = \ |
| 2206 |
slice_items(items, ignore, argkeys_cache[scopenum]) |
| 2207 |
items_before = reorder_items_atscope( |
| 2208 |
items_before, ignore, argkeys_cache,scopenum+1) |
| 2209 |
if items_same is None: |
| 2210 |
|
| 2211 |
assert items_other is None |
| 2212 |
return items_done + items_before |
| 2213 |
items_done.extend(items_before) |
| 2214 |
items = items_same + items_other |
| 2215 |
ignore = newignore |
| 2216 |
|
| 2217 |
|
| 2218 |
def slice_items(items, ignore, scoped_argkeys_cache): |
| 2219 |
|
| 2220 |
|
| 2221 |
|
| 2222 |
|
| 2223 |
if scoped_argkeys_cache: |
| 2224 |
it = iter(items) |
| 2225 |
|
| 2226 |
for i, item in enumerate(it): |
| 2227 |
argkeys = scoped_argkeys_cache.get(item) |
| 2228 |
if argkeys is not None: |
| 2229 |
argkeys = argkeys.difference(ignore) |
| 2230 |
if argkeys: |
| 2231 |
slicing_argkey = argkeys.pop() |
| 2232 |
items_before = items[:i] |
| 2233 |
items_same = [item] |
| 2234 |
items_other = [] |
| 2235 |
|
| 2236 |
for item in it: |
| 2237 |
argkeys = scoped_argkeys_cache.get(item) |
| 2238 |
if argkeys and slicing_argkey in argkeys and \ |
| 2239 |
slicing_argkey not in ignore: |
| 2240 |
items_same.append(item) |
| 2241 |
else: |
| 2242 |
items_other.append(item) |
| 2243 |
newignore = ignore.copy() |
| 2244 |
newignore.add(slicing_argkey) |
| 2245 |
return (items_before, items_same, items_other, newignore) |
| 2246 |
return items, None, None, None |
| 2247 |
|
| 2248 |
def get_parametrized_fixture_keys(item, scopenum): |
| 2249 |
""" return list of keys for all parametrized arguments which match |
| 2250 |
the specified scope. """ |
| 2251 |
assert scopenum < scopenum_function |
| 2252 |
try: |
| 2253 |
cs = item.callspec |
| 2254 |
except AttributeError: |
| 2255 |
pass |
| 2256 |
else: |
| 2257 |
|
| 2258 |
|
| 2259 |
|
| 2260 |
for argname, param_index in cs.indices.items(): |
| 2261 |
if cs._arg2scopenum[argname] != scopenum: |
| 2262 |
continue |
| 2263 |
if scopenum == 0: |
| 2264 |
key = (argname, param_index) |
| 2265 |
elif scopenum == 1: |
| 2266 |
key = (argname, param_index, item.fspath) |
| 2267 |
elif scopenum == 2: |
| 2268 |
key = (argname, param_index, item.fspath, item.cls) |
| 2269 |
yield key |
| 2270 |
|
| 2271 |
|
| 2272 |
def xunitsetup(obj, name): |
| 2273 |
meth = getattr(obj, name, None) |
| 2274 |
if getfixturemarker(meth) is None: |
| 2275 |
return meth |
| 2276 |
|
| 2277 |
def getfixturemarker(obj): |
| 2278 |
""" return fixturemarker or None if it doesn't exist or raised |
| 2279 |
exceptions.""" |
| 2280 |
try: |
| 2281 |
return getattr(obj, "_pytestfixturefunction", None) |
| 2282 |
except KeyboardInterrupt: |
| 2283 |
raise |
| 2284 |
except Exception: |
| 2285 |
|
| 2286 |
|
| 2287 |
return None |
| 2288 |
|
| 2289 |
scopename2class = { |
| 2290 |
'class': Class, |
| 2291 |
'module': Module, |
| 2292 |
'function': pytest.Item, |
| 2293 |
} |
| 2294 |
def get_scope_node(node, scope): |
| 2295 |
cls = scopename2class.get(scope) |
| 2296 |
if cls is None: |
| 2297 |
if scope == "session": |
| 2298 |
return node.session |
| 2299 |
raise ValueError("unknown scope") |
| 2300 |
return node.getparent(cls) |