fixtures.py 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356
  1. # -*- coding: utf-8 -*-
  2. from __future__ import absolute_import
  3. from __future__ import division
  4. from __future__ import print_function
  5. import functools
  6. import inspect
  7. import itertools
  8. import sys
  9. import warnings
  10. from collections import defaultdict
  11. from collections import deque
  12. from collections import OrderedDict
  13. import attr
  14. import py
  15. import six
  16. import _pytest
  17. from _pytest import nodes
  18. from _pytest._code.code import FormattedExcinfo
  19. from _pytest._code.code import TerminalRepr
  20. from _pytest.compat import _format_args
  21. from _pytest.compat import _PytestWrapper
  22. from _pytest.compat import exc_clear
  23. from _pytest.compat import FuncargnamesCompatAttr
  24. from _pytest.compat import get_real_func
  25. from _pytest.compat import get_real_method
  26. from _pytest.compat import getfslineno
  27. from _pytest.compat import getfuncargnames
  28. from _pytest.compat import getimfunc
  29. from _pytest.compat import getlocation
  30. from _pytest.compat import is_generator
  31. from _pytest.compat import isclass
  32. from _pytest.compat import NOTSET
  33. from _pytest.compat import safe_getattr
  34. from _pytest.deprecated import FIXTURE_FUNCTION_CALL
  35. from _pytest.deprecated import FIXTURE_NAMED_REQUEST
  36. from _pytest.outcomes import fail
  37. from _pytest.outcomes import TEST_OUTCOME
  38. @attr.s(frozen=True)
  39. class PseudoFixtureDef(object):
  40. cached_result = attr.ib()
  41. scope = attr.ib()
  42. def pytest_sessionstart(session):
  43. import _pytest.python
  44. import _pytest.nodes
  45. scopename2class.update(
  46. {
  47. "package": _pytest.python.Package,
  48. "class": _pytest.python.Class,
  49. "module": _pytest.python.Module,
  50. "function": _pytest.nodes.Item,
  51. "session": _pytest.main.Session,
  52. }
  53. )
  54. session._fixturemanager = FixtureManager(session)
  55. scopename2class = {}
  56. scope2props = dict(session=())
  57. scope2props["package"] = ("fspath",)
  58. scope2props["module"] = ("fspath", "module")
  59. scope2props["class"] = scope2props["module"] + ("cls",)
  60. scope2props["instance"] = scope2props["class"] + ("instance",)
  61. scope2props["function"] = scope2props["instance"] + ("function", "keywords")
  62. def scopeproperty(name=None, doc=None):
  63. def decoratescope(func):
  64. scopename = name or func.__name__
  65. def provide(self):
  66. if func.__name__ in scope2props[self.scope]:
  67. return func(self)
  68. raise AttributeError(
  69. "%s not available in %s-scoped context" % (scopename, self.scope)
  70. )
  71. return property(provide, None, None, func.__doc__)
  72. return decoratescope
  73. def get_scope_package(node, fixturedef):
  74. import pytest
  75. cls = pytest.Package
  76. current = node
  77. fixture_package_name = "%s/%s" % (fixturedef.baseid, "__init__.py")
  78. while current and (
  79. type(current) is not cls or fixture_package_name != current.nodeid
  80. ):
  81. current = current.parent
  82. if current is None:
  83. return node.session
  84. return current
  85. def get_scope_node(node, scope):
  86. cls = scopename2class.get(scope)
  87. if cls is None:
  88. raise ValueError("unknown scope")
  89. return node.getparent(cls)
  90. def add_funcarg_pseudo_fixture_def(collector, metafunc, fixturemanager):
  91. # this function will transform all collected calls to a functions
  92. # if they use direct funcargs (i.e. direct parametrization)
  93. # because we want later test execution to be able to rely on
  94. # an existing FixtureDef structure for all arguments.
  95. # XXX we can probably avoid this algorithm if we modify CallSpec2
  96. # to directly care for creating the fixturedefs within its methods.
  97. if not metafunc._calls[0].funcargs:
  98. return # this function call does not have direct parametrization
  99. # collect funcargs of all callspecs into a list of values
  100. arg2params = {}
  101. arg2scope = {}
  102. for callspec in metafunc._calls:
  103. for argname, argvalue in callspec.funcargs.items():
  104. assert argname not in callspec.params
  105. callspec.params[argname] = argvalue
  106. arg2params_list = arg2params.setdefault(argname, [])
  107. callspec.indices[argname] = len(arg2params_list)
  108. arg2params_list.append(argvalue)
  109. if argname not in arg2scope:
  110. scopenum = callspec._arg2scopenum.get(argname, scopenum_function)
  111. arg2scope[argname] = scopes[scopenum]
  112. callspec.funcargs.clear()
  113. # register artificial FixtureDef's so that later at test execution
  114. # time we can rely on a proper FixtureDef to exist for fixture setup.
  115. arg2fixturedefs = metafunc._arg2fixturedefs
  116. for argname, valuelist in arg2params.items():
  117. # if we have a scope that is higher than function we need
  118. # to make sure we only ever create an according fixturedef on
  119. # a per-scope basis. We thus store and cache the fixturedef on the
  120. # node related to the scope.
  121. scope = arg2scope[argname]
  122. node = None
  123. if scope != "function":
  124. node = get_scope_node(collector, scope)
  125. if node is None:
  126. assert scope == "class" and isinstance(collector, _pytest.python.Module)
  127. # use module-level collector for class-scope (for now)
  128. node = collector
  129. if node and argname in node._name2pseudofixturedef:
  130. arg2fixturedefs[argname] = [node._name2pseudofixturedef[argname]]
  131. else:
  132. fixturedef = FixtureDef(
  133. fixturemanager,
  134. "",
  135. argname,
  136. get_direct_param_fixture_func,
  137. arg2scope[argname],
  138. valuelist,
  139. False,
  140. False,
  141. )
  142. arg2fixturedefs[argname] = [fixturedef]
  143. if node is not None:
  144. node._name2pseudofixturedef[argname] = fixturedef
  145. def getfixturemarker(obj):
  146. """ return fixturemarker or None if it doesn't exist or raised
  147. exceptions."""
  148. try:
  149. return getattr(obj, "_pytestfixturefunction", None)
  150. except TEST_OUTCOME:
  151. # some objects raise errors like request (from flask import request)
  152. # we don't expect them to be fixture functions
  153. return None
  154. def get_parametrized_fixture_keys(item, scopenum):
  155. """ return list of keys for all parametrized arguments which match
  156. the specified scope. """
  157. assert scopenum < scopenum_function # function
  158. try:
  159. cs = item.callspec
  160. except AttributeError:
  161. pass
  162. else:
  163. # cs.indices.items() is random order of argnames. Need to
  164. # sort this so that different calls to
  165. # get_parametrized_fixture_keys will be deterministic.
  166. for argname, param_index in sorted(cs.indices.items()):
  167. if cs._arg2scopenum[argname] != scopenum:
  168. continue
  169. if scopenum == 0: # session
  170. key = (argname, param_index)
  171. elif scopenum == 1: # package
  172. key = (argname, param_index, item.fspath.dirpath())
  173. elif scopenum == 2: # module
  174. key = (argname, param_index, item.fspath)
  175. elif scopenum == 3: # class
  176. key = (argname, param_index, item.fspath, item.cls)
  177. yield key
  178. # algorithm for sorting on a per-parametrized resource setup basis
  179. # it is called for scopenum==0 (session) first and performs sorting
  180. # down to the lower scopes such as to minimize number of "high scope"
  181. # setups and teardowns
  182. def reorder_items(items):
  183. argkeys_cache = {}
  184. items_by_argkey = {}
  185. for scopenum in range(0, scopenum_function):
  186. argkeys_cache[scopenum] = d = {}
  187. items_by_argkey[scopenum] = item_d = defaultdict(deque)
  188. for item in items:
  189. keys = OrderedDict.fromkeys(get_parametrized_fixture_keys(item, scopenum))
  190. if keys:
  191. d[item] = keys
  192. for key in keys:
  193. item_d[key].append(item)
  194. items = OrderedDict.fromkeys(items)
  195. return list(reorder_items_atscope(items, argkeys_cache, items_by_argkey, 0))
  196. def fix_cache_order(item, argkeys_cache, items_by_argkey):
  197. for scopenum in range(0, scopenum_function):
  198. for key in argkeys_cache[scopenum].get(item, []):
  199. items_by_argkey[scopenum][key].appendleft(item)
  200. def reorder_items_atscope(items, argkeys_cache, items_by_argkey, scopenum):
  201. if scopenum >= scopenum_function or len(items) < 3:
  202. return items
  203. ignore = set()
  204. items_deque = deque(items)
  205. items_done = OrderedDict()
  206. scoped_items_by_argkey = items_by_argkey[scopenum]
  207. scoped_argkeys_cache = argkeys_cache[scopenum]
  208. while items_deque:
  209. no_argkey_group = OrderedDict()
  210. slicing_argkey = None
  211. while items_deque:
  212. item = items_deque.popleft()
  213. if item in items_done or item in no_argkey_group:
  214. continue
  215. argkeys = OrderedDict.fromkeys(
  216. k for k in scoped_argkeys_cache.get(item, []) if k not in ignore
  217. )
  218. if not argkeys:
  219. no_argkey_group[item] = None
  220. else:
  221. slicing_argkey, _ = argkeys.popitem()
  222. # we don't have to remove relevant items from later in the deque because they'll just be ignored
  223. matching_items = [
  224. i for i in scoped_items_by_argkey[slicing_argkey] if i in items
  225. ]
  226. for i in reversed(matching_items):
  227. fix_cache_order(i, argkeys_cache, items_by_argkey)
  228. items_deque.appendleft(i)
  229. break
  230. if no_argkey_group:
  231. no_argkey_group = reorder_items_atscope(
  232. no_argkey_group, argkeys_cache, items_by_argkey, scopenum + 1
  233. )
  234. for item in no_argkey_group:
  235. items_done[item] = None
  236. ignore.add(slicing_argkey)
  237. return items_done
  238. def fillfixtures(function):
  239. """ fill missing funcargs for a test function. """
  240. try:
  241. request = function._request
  242. except AttributeError:
  243. # XXX this special code path is only expected to execute
  244. # with the oejskit plugin. It uses classes with funcargs
  245. # and we thus have to work a bit to allow this.
  246. fm = function.session._fixturemanager
  247. fi = fm.getfixtureinfo(function.parent, function.obj, None)
  248. function._fixtureinfo = fi
  249. request = function._request = FixtureRequest(function)
  250. request._fillfixtures()
  251. # prune out funcargs for jstests
  252. newfuncargs = {}
  253. for name in fi.argnames:
  254. newfuncargs[name] = function.funcargs[name]
  255. function.funcargs = newfuncargs
  256. else:
  257. request._fillfixtures()
  258. def get_direct_param_fixture_func(request):
  259. return request.param
  260. @attr.s(slots=True)
  261. class FuncFixtureInfo(object):
  262. # original function argument names
  263. argnames = attr.ib(type=tuple)
  264. # argnames that function immediately requires. These include argnames +
  265. # fixture names specified via usefixtures and via autouse=True in fixture
  266. # definitions.
  267. initialnames = attr.ib(type=tuple)
  268. names_closure = attr.ib() # List[str]
  269. name2fixturedefs = attr.ib() # List[str, List[FixtureDef]]
  270. def prune_dependency_tree(self):
  271. """Recompute names_closure from initialnames and name2fixturedefs
  272. Can only reduce names_closure, which means that the new closure will
  273. always be a subset of the old one. The order is preserved.
  274. This method is needed because direct parametrization may shadow some
  275. of the fixtures that were included in the originally built dependency
  276. tree. In this way the dependency tree can get pruned, and the closure
  277. of argnames may get reduced.
  278. """
  279. closure = set()
  280. working_set = set(self.initialnames)
  281. while working_set:
  282. argname = working_set.pop()
  283. # argname may be smth not included in the original names_closure,
  284. # in which case we ignore it. This currently happens with pseudo
  285. # FixtureDefs which wrap 'get_direct_param_fixture_func(request)'.
  286. # So they introduce the new dependency 'request' which might have
  287. # been missing in the original tree (closure).
  288. if argname not in closure and argname in self.names_closure:
  289. closure.add(argname)
  290. if argname in self.name2fixturedefs:
  291. working_set.update(self.name2fixturedefs[argname][-1].argnames)
  292. self.names_closure[:] = sorted(closure, key=self.names_closure.index)
  293. class FixtureRequest(FuncargnamesCompatAttr):
  294. """ A request for a fixture from a test or fixture function.
  295. A request object gives access to the requesting test context
  296. and has an optional ``param`` attribute in case
  297. the fixture is parametrized indirectly.
  298. """
  299. def __init__(self, pyfuncitem):
  300. self._pyfuncitem = pyfuncitem
  301. #: fixture for which this request is being performed
  302. self.fixturename = None
  303. #: Scope string, one of "function", "class", "module", "session"
  304. self.scope = "function"
  305. self._fixture_defs = {} # argname -> FixtureDef
  306. fixtureinfo = pyfuncitem._fixtureinfo
  307. self._arg2fixturedefs = fixtureinfo.name2fixturedefs.copy()
  308. self._arg2index = {}
  309. self._fixturemanager = pyfuncitem.session._fixturemanager
  310. @property
  311. def fixturenames(self):
  312. """names of all active fixtures in this request"""
  313. result = list(self._pyfuncitem._fixtureinfo.names_closure)
  314. result.extend(set(self._fixture_defs).difference(result))
  315. return result
  316. @property
  317. def node(self):
  318. """ underlying collection node (depends on current request scope)"""
  319. return self._getscopeitem(self.scope)
  320. def _getnextfixturedef(self, argname):
  321. fixturedefs = self._arg2fixturedefs.get(argname, None)
  322. if fixturedefs is None:
  323. # we arrive here because of a dynamic call to
  324. # getfixturevalue(argname) usage which was naturally
  325. # not known at parsing/collection time
  326. parentid = self._pyfuncitem.parent.nodeid
  327. fixturedefs = self._fixturemanager.getfixturedefs(argname, parentid)
  328. self._arg2fixturedefs[argname] = fixturedefs
  329. # fixturedefs list is immutable so we maintain a decreasing index
  330. index = self._arg2index.get(argname, 0) - 1
  331. if fixturedefs is None or (-index > len(fixturedefs)):
  332. raise FixtureLookupError(argname, self)
  333. self._arg2index[argname] = index
  334. return fixturedefs[index]
  335. @property
  336. def config(self):
  337. """ the pytest config object associated with this request. """
  338. return self._pyfuncitem.config
  339. @scopeproperty()
  340. def function(self):
  341. """ test function object if the request has a per-function scope. """
  342. return self._pyfuncitem.obj
  343. @scopeproperty("class")
  344. def cls(self):
  345. """ class (can be None) where the test function was collected. """
  346. clscol = self._pyfuncitem.getparent(_pytest.python.Class)
  347. if clscol:
  348. return clscol.obj
  349. @property
  350. def instance(self):
  351. """ instance (can be None) on which test function was collected. """
  352. # unittest support hack, see _pytest.unittest.TestCaseFunction
  353. try:
  354. return self._pyfuncitem._testcase
  355. except AttributeError:
  356. function = getattr(self, "function", None)
  357. return getattr(function, "__self__", None)
  358. @scopeproperty()
  359. def module(self):
  360. """ python module object where the test function was collected. """
  361. return self._pyfuncitem.getparent(_pytest.python.Module).obj
  362. @scopeproperty()
  363. def fspath(self):
  364. """ the file system path of the test module which collected this test. """
  365. return self._pyfuncitem.fspath
  366. @property
  367. def keywords(self):
  368. """ keywords/markers dictionary for the underlying node. """
  369. return self.node.keywords
  370. @property
  371. def session(self):
  372. """ pytest session object. """
  373. return self._pyfuncitem.session
  374. def addfinalizer(self, finalizer):
  375. """ add finalizer/teardown function to be called after the
  376. last test within the requesting test context finished
  377. execution. """
  378. # XXX usually this method is shadowed by fixturedef specific ones
  379. self._addfinalizer(finalizer, scope=self.scope)
  380. def _addfinalizer(self, finalizer, scope):
  381. colitem = self._getscopeitem(scope)
  382. self._pyfuncitem.session._setupstate.addfinalizer(
  383. finalizer=finalizer, colitem=colitem
  384. )
  385. def applymarker(self, marker):
  386. """ Apply a marker to a single test function invocation.
  387. This method is useful if you don't want to have a keyword/marker
  388. on all function invocations.
  389. :arg marker: a :py:class:`_pytest.mark.MarkDecorator` object
  390. created by a call to ``pytest.mark.NAME(...)``.
  391. """
  392. self.node.add_marker(marker)
  393. def raiseerror(self, msg):
  394. """ raise a FixtureLookupError with the given message. """
  395. raise self._fixturemanager.FixtureLookupError(None, self, msg)
  396. def _fillfixtures(self):
  397. item = self._pyfuncitem
  398. fixturenames = getattr(item, "fixturenames", self.fixturenames)
  399. for argname in fixturenames:
  400. if argname not in item.funcargs:
  401. item.funcargs[argname] = self.getfixturevalue(argname)
  402. def getfixturevalue(self, argname):
  403. """ Dynamically run a named fixture function.
  404. Declaring fixtures via function argument is recommended where possible.
  405. But if you can only decide whether to use another fixture at test
  406. setup time, you may use this function to retrieve it inside a fixture
  407. or test function body.
  408. """
  409. return self._get_active_fixturedef(argname).cached_result[0]
  410. def getfuncargvalue(self, argname):
  411. """ Deprecated, use getfixturevalue. """
  412. from _pytest import deprecated
  413. warnings.warn(deprecated.GETFUNCARGVALUE, stacklevel=2)
  414. return self.getfixturevalue(argname)
  415. def _get_active_fixturedef(self, argname):
  416. try:
  417. return self._fixture_defs[argname]
  418. except KeyError:
  419. try:
  420. fixturedef = self._getnextfixturedef(argname)
  421. except FixtureLookupError:
  422. if argname == "request":
  423. cached_result = (self, [0], None)
  424. scope = "function"
  425. return PseudoFixtureDef(cached_result, scope)
  426. raise
  427. # remove indent to prevent the python3 exception
  428. # from leaking into the call
  429. self._compute_fixture_value(fixturedef)
  430. self._fixture_defs[argname] = fixturedef
  431. return fixturedef
  432. def _get_fixturestack(self):
  433. current = self
  434. values = []
  435. while 1:
  436. fixturedef = getattr(current, "_fixturedef", None)
  437. if fixturedef is None:
  438. values.reverse()
  439. return values
  440. values.append(fixturedef)
  441. current = current._parent_request
  442. def _compute_fixture_value(self, fixturedef):
  443. """
  444. Creates a SubRequest based on "self" and calls the execute method of the given fixturedef object. This will
  445. force the FixtureDef object to throw away any previous results and compute a new fixture value, which
  446. will be stored into the FixtureDef object itself.
  447. :param FixtureDef fixturedef:
  448. """
  449. # prepare a subrequest object before calling fixture function
  450. # (latter managed by fixturedef)
  451. argname = fixturedef.argname
  452. funcitem = self._pyfuncitem
  453. scope = fixturedef.scope
  454. try:
  455. param = funcitem.callspec.getparam(argname)
  456. except (AttributeError, ValueError):
  457. param = NOTSET
  458. param_index = 0
  459. has_params = fixturedef.params is not None
  460. fixtures_not_supported = getattr(funcitem, "nofuncargs", False)
  461. if has_params and fixtures_not_supported:
  462. msg = (
  463. "{name} does not support fixtures, maybe unittest.TestCase subclass?\n"
  464. "Node id: {nodeid}\n"
  465. "Function type: {typename}"
  466. ).format(
  467. name=funcitem.name,
  468. nodeid=funcitem.nodeid,
  469. typename=type(funcitem).__name__,
  470. )
  471. fail(msg, pytrace=False)
  472. if has_params:
  473. frame = inspect.stack()[3]
  474. frameinfo = inspect.getframeinfo(frame[0])
  475. source_path = frameinfo.filename
  476. source_lineno = frameinfo.lineno
  477. source_path = py.path.local(source_path)
  478. if source_path.relto(funcitem.config.rootdir):
  479. source_path = source_path.relto(funcitem.config.rootdir)
  480. msg = (
  481. "The requested fixture has no parameter defined for test:\n"
  482. " {}\n\n"
  483. "Requested fixture '{}' defined in:\n{}"
  484. "\n\nRequested here:\n{}:{}".format(
  485. funcitem.nodeid,
  486. fixturedef.argname,
  487. getlocation(fixturedef.func, funcitem.config.rootdir),
  488. source_path,
  489. source_lineno,
  490. )
  491. )
  492. fail(msg, pytrace=False)
  493. else:
  494. param_index = funcitem.callspec.indices[argname]
  495. # if a parametrize invocation set a scope it will override
  496. # the static scope defined with the fixture function
  497. paramscopenum = funcitem.callspec._arg2scopenum.get(argname)
  498. if paramscopenum is not None:
  499. scope = scopes[paramscopenum]
  500. subrequest = SubRequest(self, scope, param, param_index, fixturedef)
  501. # check if a higher-level scoped fixture accesses a lower level one
  502. subrequest._check_scope(argname, self.scope, scope)
  503. # clear sys.exc_info before invoking the fixture (python bug?)
  504. # if it's not explicitly cleared it will leak into the call
  505. exc_clear()
  506. try:
  507. # call the fixture function
  508. fixturedef.execute(request=subrequest)
  509. finally:
  510. self._schedule_finalizers(fixturedef, subrequest)
  511. def _schedule_finalizers(self, fixturedef, subrequest):
  512. # if fixture function failed it might have registered finalizers
  513. self.session._setupstate.addfinalizer(
  514. functools.partial(fixturedef.finish, request=subrequest), subrequest.node
  515. )
  516. def _check_scope(self, argname, invoking_scope, requested_scope):
  517. if argname == "request":
  518. return
  519. if scopemismatch(invoking_scope, requested_scope):
  520. # try to report something helpful
  521. lines = self._factorytraceback()
  522. fail(
  523. "ScopeMismatch: You tried to access the %r scoped "
  524. "fixture %r with a %r scoped request object, "
  525. "involved factories\n%s"
  526. % ((requested_scope, argname, invoking_scope, "\n".join(lines))),
  527. pytrace=False,
  528. )
  529. def _factorytraceback(self):
  530. lines = []
  531. for fixturedef in self._get_fixturestack():
  532. factory = fixturedef.func
  533. fs, lineno = getfslineno(factory)
  534. p = self._pyfuncitem.session.fspath.bestrelpath(fs)
  535. args = _format_args(factory)
  536. lines.append("%s:%d: def %s%s" % (p, lineno + 1, factory.__name__, args))
  537. return lines
  538. def _getscopeitem(self, scope):
  539. if scope == "function":
  540. # this might also be a non-function Item despite its attribute name
  541. return self._pyfuncitem
  542. if scope == "package":
  543. node = get_scope_package(self._pyfuncitem, self._fixturedef)
  544. else:
  545. node = get_scope_node(self._pyfuncitem, scope)
  546. if node is None and scope == "class":
  547. # fallback to function item itself
  548. node = self._pyfuncitem
  549. assert node, 'Could not obtain a node for scope "{}" for function {!r}'.format(
  550. scope, self._pyfuncitem
  551. )
  552. return node
  553. def __repr__(self):
  554. return "<FixtureRequest for %r>" % (self.node)
  555. class SubRequest(FixtureRequest):
  556. """ a sub request for handling getting a fixture from a
  557. test function/fixture. """
  558. def __init__(self, request, scope, param, param_index, fixturedef):
  559. self._parent_request = request
  560. self.fixturename = fixturedef.argname
  561. if param is not NOTSET:
  562. self.param = param
  563. self.param_index = param_index
  564. self.scope = scope
  565. self._fixturedef = fixturedef
  566. self._pyfuncitem = request._pyfuncitem
  567. self._fixture_defs = request._fixture_defs
  568. self._arg2fixturedefs = request._arg2fixturedefs
  569. self._arg2index = request._arg2index
  570. self._fixturemanager = request._fixturemanager
  571. def __repr__(self):
  572. return "<SubRequest %r for %r>" % (self.fixturename, self._pyfuncitem)
  573. def addfinalizer(self, finalizer):
  574. self._fixturedef.addfinalizer(finalizer)
  575. def _schedule_finalizers(self, fixturedef, subrequest):
  576. # if the executing fixturedef was not explicitly requested in the argument list (via
  577. # getfixturevalue inside the fixture call) then ensure this fixture def will be finished
  578. # first
  579. if fixturedef.argname not in self.funcargnames:
  580. fixturedef.addfinalizer(
  581. functools.partial(self._fixturedef.finish, request=self)
  582. )
  583. super(SubRequest, self)._schedule_finalizers(fixturedef, subrequest)
  584. scopes = "session package module class function".split()
  585. scopenum_function = scopes.index("function")
  586. def scopemismatch(currentscope, newscope):
  587. return scopes.index(newscope) > scopes.index(currentscope)
  588. def scope2index(scope, descr, where=None):
  589. """Look up the index of ``scope`` and raise a descriptive value error
  590. if not defined.
  591. """
  592. try:
  593. return scopes.index(scope)
  594. except ValueError:
  595. fail(
  596. "{} {}got an unexpected scope value '{}'".format(
  597. descr, "from {} ".format(where) if where else "", scope
  598. ),
  599. pytrace=False,
  600. )
  601. class FixtureLookupError(LookupError):
  602. """ could not return a requested Fixture (missing or invalid). """
  603. def __init__(self, argname, request, msg=None):
  604. self.argname = argname
  605. self.request = request
  606. self.fixturestack = request._get_fixturestack()
  607. self.msg = msg
  608. def formatrepr(self):
  609. tblines = []
  610. addline = tblines.append
  611. stack = [self.request._pyfuncitem.obj]
  612. stack.extend(map(lambda x: x.func, self.fixturestack))
  613. msg = self.msg
  614. if msg is not None:
  615. # the last fixture raise an error, let's present
  616. # it at the requesting side
  617. stack = stack[:-1]
  618. for function in stack:
  619. fspath, lineno = getfslineno(function)
  620. try:
  621. lines, _ = inspect.getsourcelines(get_real_func(function))
  622. except (IOError, IndexError, TypeError):
  623. error_msg = "file %s, line %s: source code not available"
  624. addline(error_msg % (fspath, lineno + 1))
  625. else:
  626. addline("file %s, line %s" % (fspath, lineno + 1))
  627. for i, line in enumerate(lines):
  628. line = line.rstrip()
  629. addline(" " + line)
  630. if line.lstrip().startswith("def"):
  631. break
  632. if msg is None:
  633. fm = self.request._fixturemanager
  634. available = set()
  635. parentid = self.request._pyfuncitem.parent.nodeid
  636. for name, fixturedefs in fm._arg2fixturedefs.items():
  637. faclist = list(fm._matchfactories(fixturedefs, parentid))
  638. if faclist:
  639. available.add(name)
  640. if self.argname in available:
  641. msg = " recursive dependency involving fixture '{}' detected".format(
  642. self.argname
  643. )
  644. else:
  645. msg = "fixture '{}' not found".format(self.argname)
  646. msg += "\n available fixtures: {}".format(", ".join(sorted(available)))
  647. msg += "\n use 'pytest --fixtures [testpath]' for help on them."
  648. return FixtureLookupErrorRepr(fspath, lineno, tblines, msg, self.argname)
  649. class FixtureLookupErrorRepr(TerminalRepr):
  650. def __init__(self, filename, firstlineno, tblines, errorstring, argname):
  651. self.tblines = tblines
  652. self.errorstring = errorstring
  653. self.filename = filename
  654. self.firstlineno = firstlineno
  655. self.argname = argname
  656. def toterminal(self, tw):
  657. # tw.line("FixtureLookupError: %s" %(self.argname), red=True)
  658. for tbline in self.tblines:
  659. tw.line(tbline.rstrip())
  660. lines = self.errorstring.split("\n")
  661. if lines:
  662. tw.line(
  663. "{} {}".format(FormattedExcinfo.fail_marker, lines[0].strip()),
  664. red=True,
  665. )
  666. for line in lines[1:]:
  667. tw.line(
  668. "{} {}".format(FormattedExcinfo.flow_marker, line.strip()),
  669. red=True,
  670. )
  671. tw.line()
  672. tw.line("%s:%d" % (self.filename, self.firstlineno + 1))
  673. def fail_fixturefunc(fixturefunc, msg):
  674. fs, lineno = getfslineno(fixturefunc)
  675. location = "%s:%s" % (fs, lineno + 1)
  676. source = _pytest._code.Source(fixturefunc)
  677. fail(msg + ":\n\n" + str(source.indent()) + "\n" + location, pytrace=False)
  678. def call_fixture_func(fixturefunc, request, kwargs):
  679. yieldctx = is_generator(fixturefunc)
  680. if yieldctx:
  681. it = fixturefunc(**kwargs)
  682. res = next(it)
  683. finalizer = functools.partial(_teardown_yield_fixture, fixturefunc, it)
  684. request.addfinalizer(finalizer)
  685. else:
  686. res = fixturefunc(**kwargs)
  687. return res
  688. def _teardown_yield_fixture(fixturefunc, it):
  689. """Executes the teardown of a fixture function by advancing the iterator after the
  690. yield and ensure the iteration ends (if not it means there is more than one yield in the function)"""
  691. try:
  692. next(it)
  693. except StopIteration:
  694. pass
  695. else:
  696. fail_fixturefunc(
  697. fixturefunc, "yield_fixture function has more than one 'yield'"
  698. )
  699. class FixtureDef(object):
  700. """ A container for a factory definition. """
  701. def __init__(
  702. self,
  703. fixturemanager,
  704. baseid,
  705. argname,
  706. func,
  707. scope,
  708. params,
  709. unittest=False,
  710. ids=None,
  711. ):
  712. self._fixturemanager = fixturemanager
  713. self.baseid = baseid or ""
  714. self.has_location = baseid is not None
  715. self.func = func
  716. self.argname = argname
  717. self.scope = scope
  718. self.scopenum = scope2index(
  719. scope or "function",
  720. descr="Fixture '{}'".format(func.__name__),
  721. where=baseid,
  722. )
  723. self.params = params
  724. self.argnames = getfuncargnames(func, is_method=unittest)
  725. self.unittest = unittest
  726. self.ids = ids
  727. self._finalizers = []
  728. def addfinalizer(self, finalizer):
  729. self._finalizers.append(finalizer)
  730. def finish(self, request):
  731. exceptions = []
  732. try:
  733. while self._finalizers:
  734. try:
  735. func = self._finalizers.pop()
  736. func()
  737. except: # noqa
  738. exceptions.append(sys.exc_info())
  739. if exceptions:
  740. e = exceptions[0]
  741. # Ensure to not keep frame references through traceback.
  742. del exceptions
  743. six.reraise(*e)
  744. finally:
  745. hook = self._fixturemanager.session.gethookproxy(request.node.fspath)
  746. hook.pytest_fixture_post_finalizer(fixturedef=self, request=request)
  747. # even if finalization fails, we invalidate
  748. # the cached fixture value and remove
  749. # all finalizers because they may be bound methods which will
  750. # keep instances alive
  751. if hasattr(self, "cached_result"):
  752. del self.cached_result
  753. self._finalizers = []
  754. def execute(self, request):
  755. # get required arguments and register our own finish()
  756. # with their finalization
  757. for argname in self.argnames:
  758. fixturedef = request._get_active_fixturedef(argname)
  759. if argname != "request":
  760. fixturedef.addfinalizer(functools.partial(self.finish, request=request))
  761. my_cache_key = request.param_index
  762. cached_result = getattr(self, "cached_result", None)
  763. if cached_result is not None:
  764. result, cache_key, err = cached_result
  765. if my_cache_key == cache_key:
  766. if err is not None:
  767. six.reraise(*err)
  768. else:
  769. return result
  770. # we have a previous but differently parametrized fixture instance
  771. # so we need to tear it down before creating a new one
  772. self.finish(request)
  773. assert not hasattr(self, "cached_result")
  774. hook = self._fixturemanager.session.gethookproxy(request.node.fspath)
  775. return hook.pytest_fixture_setup(fixturedef=self, request=request)
  776. def __repr__(self):
  777. return "<FixtureDef argname=%r scope=%r baseid=%r>" % (
  778. self.argname,
  779. self.scope,
  780. self.baseid,
  781. )
  782. def resolve_fixture_function(fixturedef, request):
  783. """Gets the actual callable that can be called to obtain the fixture value, dealing with unittest-specific
  784. instances and bound methods.
  785. """
  786. fixturefunc = fixturedef.func
  787. if fixturedef.unittest:
  788. if request.instance is not None:
  789. # bind the unbound method to the TestCase instance
  790. fixturefunc = fixturedef.func.__get__(request.instance)
  791. else:
  792. # the fixture function needs to be bound to the actual
  793. # request.instance so that code working with "fixturedef" behaves
  794. # as expected.
  795. if request.instance is not None:
  796. fixturefunc = getimfunc(fixturedef.func)
  797. if fixturefunc != fixturedef.func:
  798. fixturefunc = fixturefunc.__get__(request.instance)
  799. return fixturefunc
  800. def pytest_fixture_setup(fixturedef, request):
  801. """ Execution of fixture setup. """
  802. kwargs = {}
  803. for argname in fixturedef.argnames:
  804. fixdef = request._get_active_fixturedef(argname)
  805. result, arg_cache_key, exc = fixdef.cached_result
  806. request._check_scope(argname, request.scope, fixdef.scope)
  807. kwargs[argname] = result
  808. fixturefunc = resolve_fixture_function(fixturedef, request)
  809. my_cache_key = request.param_index
  810. try:
  811. result = call_fixture_func(fixturefunc, request, kwargs)
  812. except TEST_OUTCOME:
  813. fixturedef.cached_result = (None, my_cache_key, sys.exc_info())
  814. raise
  815. fixturedef.cached_result = (result, my_cache_key, None)
  816. return result
  817. def _ensure_immutable_ids(ids):
  818. if ids is None:
  819. return
  820. if callable(ids):
  821. return ids
  822. return tuple(ids)
  823. def wrap_function_to_error_out_if_called_directly(function, fixture_marker):
  824. """Wrap the given fixture function so we can raise an error about it being called directly,
  825. instead of used as an argument in a test function.
  826. """
  827. message = FIXTURE_FUNCTION_CALL.format(
  828. name=fixture_marker.name or function.__name__
  829. )
  830. @six.wraps(function)
  831. def result(*args, **kwargs):
  832. fail(message, pytrace=False)
  833. # keep reference to the original function in our own custom attribute so we don't unwrap
  834. # further than this point and lose useful wrappings like @mock.patch (#3774)
  835. result.__pytest_wrapped__ = _PytestWrapper(function)
  836. return result
  837. @attr.s(frozen=True)
  838. class FixtureFunctionMarker(object):
  839. scope = attr.ib()
  840. params = attr.ib(converter=attr.converters.optional(tuple))
  841. autouse = attr.ib(default=False)
  842. ids = attr.ib(default=None, converter=_ensure_immutable_ids)
  843. name = attr.ib(default=None)
  844. def __call__(self, function):
  845. if isclass(function):
  846. raise ValueError("class fixtures not supported (maybe in the future)")
  847. if getattr(function, "_pytestfixturefunction", False):
  848. raise ValueError(
  849. "fixture is being applied more than once to the same function"
  850. )
  851. function = wrap_function_to_error_out_if_called_directly(function, self)
  852. name = self.name or function.__name__
  853. if name == "request":
  854. warnings.warn(FIXTURE_NAMED_REQUEST)
  855. function._pytestfixturefunction = self
  856. return function
  857. def fixture(scope="function", params=None, autouse=False, ids=None, name=None):
  858. """Decorator to mark a fixture factory function.
  859. This decorator can be used, with or without parameters, to define a
  860. fixture function.
  861. The name of the fixture function can later be referenced to cause its
  862. invocation ahead of running tests: test
  863. modules or classes can use the ``pytest.mark.usefixtures(fixturename)``
  864. marker.
  865. Test functions can directly use fixture names as input
  866. arguments in which case the fixture instance returned from the fixture
  867. function will be injected.
  868. Fixtures can provide their values to test functions using ``return`` or ``yield``
  869. statements. When using ``yield`` the code block after the ``yield`` statement is executed
  870. as teardown code regardless of the test outcome, and must yield exactly once.
  871. :arg scope: the scope for which this fixture is shared, one of
  872. ``"function"`` (default), ``"class"``, ``"module"``,
  873. ``"package"`` or ``"session"``.
  874. ``"package"`` is considered **experimental** at this time.
  875. :arg params: an optional list of parameters which will cause multiple
  876. invocations of the fixture function and all of the tests
  877. using it.
  878. The current parameter is available in ``request.param``.
  879. :arg autouse: if True, the fixture func is activated for all tests that
  880. can see it. If False (the default) then an explicit
  881. reference is needed to activate the fixture.
  882. :arg ids: list of string ids each corresponding to the params
  883. so that they are part of the test id. If no ids are provided
  884. they will be generated automatically from the params.
  885. :arg name: the name of the fixture. This defaults to the name of the
  886. decorated function. If a fixture is used in the same module in
  887. which it is defined, the function name of the fixture will be
  888. shadowed by the function arg that requests the fixture; one way
  889. to resolve this is to name the decorated function
  890. ``fixture_<fixturename>`` and then use
  891. ``@pytest.fixture(name='<fixturename>')``.
  892. """
  893. if callable(scope) and params is None and autouse is False:
  894. # direct decoration
  895. return FixtureFunctionMarker("function", params, autouse, name=name)(scope)
  896. if params is not None and not isinstance(params, (list, tuple)):
  897. params = list(params)
  898. return FixtureFunctionMarker(scope, params, autouse, ids=ids, name=name)
  899. def yield_fixture(scope="function", params=None, autouse=False, ids=None, name=None):
  900. """ (return a) decorator to mark a yield-fixture factory function.
  901. .. deprecated:: 3.0
  902. Use :py:func:`pytest.fixture` directly instead.
  903. """
  904. return fixture(scope=scope, params=params, autouse=autouse, ids=ids, name=name)
  905. defaultfuncargprefixmarker = fixture()
  906. @fixture(scope="session")
  907. def pytestconfig(request):
  908. """Session-scoped fixture that returns the :class:`_pytest.config.Config` object.
  909. Example::
  910. def test_foo(pytestconfig):
  911. if pytestconfig.getoption("verbose") > 0:
  912. ...
  913. """
  914. return request.config
  915. def pytest_addoption(parser):
  916. parser.addini(
  917. "usefixtures",
  918. type="args",
  919. default=[],
  920. help="list of default fixtures to be used with this project",
  921. )
  922. class FixtureManager(object):
  923. """
  924. pytest fixtures definitions and information is stored and managed
  925. from this class.
  926. During collection fm.parsefactories() is called multiple times to parse
  927. fixture function definitions into FixtureDef objects and internal
  928. data structures.
  929. During collection of test functions, metafunc-mechanics instantiate
  930. a FuncFixtureInfo object which is cached per node/func-name.
  931. This FuncFixtureInfo object is later retrieved by Function nodes
  932. which themselves offer a fixturenames attribute.
  933. The FuncFixtureInfo object holds information about fixtures and FixtureDefs
  934. relevant for a particular function. An initial list of fixtures is
  935. assembled like this:
  936. - ini-defined usefixtures
  937. - autouse-marked fixtures along the collection chain up from the function
  938. - usefixtures markers at module/class/function level
  939. - test function funcargs
  940. Subsequently the funcfixtureinfo.fixturenames attribute is computed
  941. as the closure of the fixtures needed to setup the initial fixtures,
  942. i. e. fixtures needed by fixture functions themselves are appended
  943. to the fixturenames list.
  944. Upon the test-setup phases all fixturenames are instantiated, retrieved
  945. by a lookup of their FuncFixtureInfo.
  946. """
  947. FixtureLookupError = FixtureLookupError
  948. FixtureLookupErrorRepr = FixtureLookupErrorRepr
  949. def __init__(self, session):
  950. self.session = session
  951. self.config = session.config
  952. self._arg2fixturedefs = {}
  953. self._holderobjseen = set()
  954. self._arg2finish = {}
  955. self._nodeid_and_autousenames = [("", self.config.getini("usefixtures"))]
  956. session.config.pluginmanager.register(self, "funcmanage")
  957. def _get_direct_parametrize_args(self, node):
  958. """This function returns all the direct parametrization
  959. arguments of a node, so we don't mistake them for fixtures
  960. Check https://github.com/pytest-dev/pytest/issues/5036
  961. This things are done later as well when dealing with parametrization
  962. so this could be improved
  963. """
  964. from _pytest.mark import ParameterSet
  965. parametrize_argnames = []
  966. for marker in node.iter_markers(name="parametrize"):
  967. if not marker.kwargs.get("indirect", False):
  968. p_argnames, _ = ParameterSet._parse_parametrize_args(
  969. *marker.args, **marker.kwargs
  970. )
  971. parametrize_argnames.extend(p_argnames)
  972. return parametrize_argnames
  973. def getfixtureinfo(self, node, func, cls, funcargs=True):
  974. if funcargs and not getattr(node, "nofuncargs", False):
  975. argnames = getfuncargnames(func, cls=cls)
  976. else:
  977. argnames = ()
  978. usefixtures = itertools.chain.from_iterable(
  979. mark.args for mark in node.iter_markers(name="usefixtures")
  980. )
  981. initialnames = tuple(usefixtures) + argnames
  982. fm = node.session._fixturemanager
  983. initialnames, names_closure, arg2fixturedefs = fm.getfixtureclosure(
  984. initialnames, node, ignore_args=self._get_direct_parametrize_args(node)
  985. )
  986. return FuncFixtureInfo(argnames, initialnames, names_closure, arg2fixturedefs)
  987. def pytest_plugin_registered(self, plugin):
  988. nodeid = None
  989. try:
  990. p = py.path.local(plugin.__file__).realpath()
  991. except AttributeError:
  992. pass
  993. else:
  994. # construct the base nodeid which is later used to check
  995. # what fixtures are visible for particular tests (as denoted
  996. # by their test id)
  997. if p.basename.startswith("conftest.py"):
  998. nodeid = p.dirpath().relto(self.config.rootdir)
  999. if p.sep != nodes.SEP:
  1000. nodeid = nodeid.replace(p.sep, nodes.SEP)
  1001. self.parsefactories(plugin, nodeid)
  1002. def _getautousenames(self, nodeid):
  1003. """ return a tuple of fixture names to be used. """
  1004. autousenames = []
  1005. for baseid, basenames in self._nodeid_and_autousenames:
  1006. if nodeid.startswith(baseid):
  1007. if baseid:
  1008. i = len(baseid)
  1009. nextchar = nodeid[i : i + 1]
  1010. if nextchar and nextchar not in ":/":
  1011. continue
  1012. autousenames.extend(basenames)
  1013. return autousenames
  1014. def getfixtureclosure(self, fixturenames, parentnode, ignore_args=()):
  1015. # collect the closure of all fixtures , starting with the given
  1016. # fixturenames as the initial set. As we have to visit all
  1017. # factory definitions anyway, we also return an arg2fixturedefs
  1018. # mapping so that the caller can reuse it and does not have
  1019. # to re-discover fixturedefs again for each fixturename
  1020. # (discovering matching fixtures for a given name/node is expensive)
  1021. parentid = parentnode.nodeid
  1022. fixturenames_closure = self._getautousenames(parentid)
  1023. def merge(otherlist):
  1024. for arg in otherlist:
  1025. if arg not in fixturenames_closure:
  1026. fixturenames_closure.append(arg)
  1027. merge(fixturenames)
  1028. # at this point, fixturenames_closure contains what we call "initialnames",
  1029. # which is a set of fixturenames the function immediately requests. We
  1030. # need to return it as well, so save this.
  1031. initialnames = tuple(fixturenames_closure)
  1032. arg2fixturedefs = {}
  1033. lastlen = -1
  1034. while lastlen != len(fixturenames_closure):
  1035. lastlen = len(fixturenames_closure)
  1036. for argname in fixturenames_closure:
  1037. if argname in ignore_args:
  1038. continue
  1039. if argname in arg2fixturedefs:
  1040. continue
  1041. fixturedefs = self.getfixturedefs(argname, parentid)
  1042. if fixturedefs:
  1043. arg2fixturedefs[argname] = fixturedefs
  1044. merge(fixturedefs[-1].argnames)
  1045. def sort_by_scope(arg_name):
  1046. try:
  1047. fixturedefs = arg2fixturedefs[arg_name]
  1048. except KeyError:
  1049. return scopes.index("function")
  1050. else:
  1051. return fixturedefs[-1].scopenum
  1052. fixturenames_closure.sort(key=sort_by_scope)
  1053. return initialnames, fixturenames_closure, arg2fixturedefs
  1054. def pytest_generate_tests(self, metafunc):
  1055. for argname in metafunc.fixturenames:
  1056. faclist = metafunc._arg2fixturedefs.get(argname)
  1057. if faclist:
  1058. fixturedef = faclist[-1]
  1059. if fixturedef.params is not None:
  1060. markers = list(metafunc.definition.iter_markers("parametrize"))
  1061. for parametrize_mark in markers:
  1062. if "argnames" in parametrize_mark.kwargs:
  1063. argnames = parametrize_mark.kwargs["argnames"]
  1064. else:
  1065. argnames = parametrize_mark.args[0]
  1066. if not isinstance(argnames, (tuple, list)):
  1067. argnames = [
  1068. x.strip() for x in argnames.split(",") if x.strip()
  1069. ]
  1070. if argname in argnames:
  1071. break
  1072. else:
  1073. metafunc.parametrize(
  1074. argname,
  1075. fixturedef.params,
  1076. indirect=True,
  1077. scope=fixturedef.scope,
  1078. ids=fixturedef.ids,
  1079. )
  1080. else:
  1081. continue # will raise FixtureLookupError at setup time
  1082. def pytest_collection_modifyitems(self, items):
  1083. # separate parametrized setups
  1084. items[:] = reorder_items(items)
  1085. def parsefactories(self, node_or_obj, nodeid=NOTSET, unittest=False):
  1086. if nodeid is not NOTSET:
  1087. holderobj = node_or_obj
  1088. else:
  1089. holderobj = node_or_obj.obj
  1090. nodeid = node_or_obj.nodeid
  1091. if holderobj in self._holderobjseen:
  1092. return
  1093. self._holderobjseen.add(holderobj)
  1094. autousenames = []
  1095. for name in dir(holderobj):
  1096. # The attribute can be an arbitrary descriptor, so the attribute
  1097. # access below can raise. safe_getatt() ignores such exceptions.
  1098. obj = safe_getattr(holderobj, name, None)
  1099. marker = getfixturemarker(obj)
  1100. if not isinstance(marker, FixtureFunctionMarker):
  1101. # magic globals with __getattr__ might have got us a wrong
  1102. # fixture attribute
  1103. continue
  1104. if marker.name:
  1105. name = marker.name
  1106. # during fixture definition we wrap the original fixture function
  1107. # to issue a warning if called directly, so here we unwrap it in order to not emit the warning
  1108. # when pytest itself calls the fixture function
  1109. if six.PY2 and unittest:
  1110. # hack on Python 2 because of the unbound methods
  1111. obj = get_real_func(obj)
  1112. else:
  1113. obj = get_real_method(obj, holderobj)
  1114. fixture_def = FixtureDef(
  1115. self,
  1116. nodeid,
  1117. name,
  1118. obj,
  1119. marker.scope,
  1120. marker.params,
  1121. unittest=unittest,
  1122. ids=marker.ids,
  1123. )
  1124. faclist = self._arg2fixturedefs.setdefault(name, [])
  1125. if fixture_def.has_location:
  1126. faclist.append(fixture_def)
  1127. else:
  1128. # fixturedefs with no location are at the front
  1129. # so this inserts the current fixturedef after the
  1130. # existing fixturedefs from external plugins but
  1131. # before the fixturedefs provided in conftests.
  1132. i = len([f for f in faclist if not f.has_location])
  1133. faclist.insert(i, fixture_def)
  1134. if marker.autouse:
  1135. autousenames.append(name)
  1136. if autousenames:
  1137. self._nodeid_and_autousenames.append((nodeid or "", autousenames))
  1138. def getfixturedefs(self, argname, nodeid):
  1139. """
  1140. Gets a list of fixtures which are applicable to the given node id.
  1141. :param str argname: name of the fixture to search for
  1142. :param str nodeid: full node id of the requesting test.
  1143. :return: list[FixtureDef]
  1144. """
  1145. try:
  1146. fixturedefs = self._arg2fixturedefs[argname]
  1147. except KeyError:
  1148. return None
  1149. return tuple(self._matchfactories(fixturedefs, nodeid))
  1150. def _matchfactories(self, fixturedefs, nodeid):
  1151. for fixturedef in fixturedefs:
  1152. if nodes.ischildnode(fixturedef.baseid, nodeid):
  1153. yield fixturedef