python.py 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467
  1. """ Python test discovery, setup and run of test functions. """
  2. from __future__ import absolute_import, division, print_function
  3. import fnmatch
  4. import inspect
  5. import sys
  6. import os
  7. import collections
  8. import warnings
  9. from textwrap import dedent
  10. import py
  11. import six
  12. from _pytest.main import FSHookProxy
  13. from _pytest.mark import MarkerError
  14. from _pytest.config import hookimpl
  15. import _pytest
  16. import pluggy
  17. from _pytest import fixtures
  18. from _pytest import nodes
  19. from _pytest import deprecated
  20. from _pytest.compat import (
  21. isclass,
  22. isfunction,
  23. is_generator,
  24. ascii_escaped,
  25. REGEX_TYPE,
  26. STRING_TYPES,
  27. NoneType,
  28. NOTSET,
  29. get_real_func,
  30. getfslineno,
  31. safe_getattr,
  32. safe_str,
  33. getlocation,
  34. enum,
  35. get_default_arg_names,
  36. )
  37. from _pytest.outcomes import fail
  38. from _pytest.mark.structures import (
  39. transfer_markers,
  40. get_unpacked_marks,
  41. normalize_mark_list,
  42. )
  43. # relative paths that we use to filter traceback entries from appearing to the user;
  44. # see filter_traceback
  45. # note: if we need to add more paths than what we have now we should probably use a list
  46. # for better maintenance
  47. _pluggy_dir = py.path.local(pluggy.__file__.rstrip("oc"))
  48. # pluggy is either a package or a single module depending on the version
  49. if _pluggy_dir.basename == "__init__.py":
  50. _pluggy_dir = _pluggy_dir.dirpath()
  51. _pytest_dir = py.path.local(_pytest.__file__).dirpath()
  52. _py_dir = py.path.local(py.__file__).dirpath()
  53. def filter_traceback(entry):
  54. """Return True if a TracebackEntry instance should be removed from tracebacks:
  55. * dynamically generated code (no code to show up for it);
  56. * internal traceback from pytest or its internal libraries, py and pluggy.
  57. """
  58. # entry.path might sometimes return a str object when the entry
  59. # points to dynamically generated code
  60. # see https://bitbucket.org/pytest-dev/py/issues/71
  61. raw_filename = entry.frame.code.raw.co_filename
  62. is_generated = "<" in raw_filename and ">" in raw_filename
  63. if is_generated:
  64. return False
  65. # entry.path might point to a non-existing file, in which case it will
  66. # also return a str object. see #1133
  67. p = py.path.local(entry.path)
  68. return (
  69. not p.relto(_pluggy_dir) and not p.relto(_pytest_dir) and not p.relto(_py_dir)
  70. )
  71. def pyobj_property(name):
  72. def get(self):
  73. node = self.getparent(getattr(__import__("pytest"), name))
  74. if node is not None:
  75. return node.obj
  76. doc = "python %s object this node was collected from (can be None)." % (
  77. name.lower(),
  78. )
  79. return property(get, None, None, doc)
  80. def pytest_addoption(parser):
  81. group = parser.getgroup("general")
  82. group.addoption(
  83. "--fixtures",
  84. "--funcargs",
  85. action="store_true",
  86. dest="showfixtures",
  87. default=False,
  88. help="show available fixtures, sorted by plugin appearance "
  89. "(fixtures with leading '_' are only shown with '-v')",
  90. )
  91. group.addoption(
  92. "--fixtures-per-test",
  93. action="store_true",
  94. dest="show_fixtures_per_test",
  95. default=False,
  96. help="show fixtures per test",
  97. )
  98. parser.addini(
  99. "usefixtures",
  100. type="args",
  101. default=[],
  102. help="list of default fixtures to be used with this project",
  103. )
  104. parser.addini(
  105. "python_files",
  106. type="args",
  107. default=["test_*.py", "*_test.py"],
  108. help="glob-style file patterns for Python test module discovery",
  109. )
  110. parser.addini(
  111. "python_classes",
  112. type="args",
  113. default=["Test"],
  114. help="prefixes or glob names for Python test class discovery",
  115. )
  116. parser.addini(
  117. "python_functions",
  118. type="args",
  119. default=["test"],
  120. help="prefixes or glob names for Python test function and " "method discovery",
  121. )
  122. group.addoption(
  123. "--import-mode",
  124. default="prepend",
  125. choices=["prepend", "append"],
  126. dest="importmode",
  127. help="prepend/append to sys.path when importing test modules, "
  128. "default is to prepend.",
  129. )
  130. def pytest_cmdline_main(config):
  131. if config.option.showfixtures:
  132. showfixtures(config)
  133. return 0
  134. if config.option.show_fixtures_per_test:
  135. show_fixtures_per_test(config)
  136. return 0
  137. def pytest_generate_tests(metafunc):
  138. # those alternative spellings are common - raise a specific error to alert
  139. # the user
  140. alt_spellings = ["parameterize", "parametrise", "parameterise"]
  141. for attr in alt_spellings:
  142. if hasattr(metafunc.function, attr):
  143. msg = "{0} has '{1}', spelling should be 'parametrize'"
  144. raise MarkerError(msg.format(metafunc.function.__name__, attr))
  145. for marker in metafunc.definition.iter_markers(name="parametrize"):
  146. metafunc.parametrize(*marker.args, **marker.kwargs)
  147. def pytest_configure(config):
  148. config.addinivalue_line(
  149. "markers",
  150. "parametrize(argnames, argvalues): call a test function multiple "
  151. "times passing in different arguments in turn. argvalues generally "
  152. "needs to be a list of values if argnames specifies only one name "
  153. "or a list of tuples of values if argnames specifies multiple names. "
  154. "Example: @parametrize('arg1', [1,2]) would lead to two calls of the "
  155. "decorated test function, one with arg1=1 and another with arg1=2."
  156. "see https://docs.pytest.org/en/latest/parametrize.html for more info "
  157. "and examples.",
  158. )
  159. config.addinivalue_line(
  160. "markers",
  161. "usefixtures(fixturename1, fixturename2, ...): mark tests as needing "
  162. "all of the specified fixtures. see "
  163. "https://docs.pytest.org/en/latest/fixture.html#usefixtures ",
  164. )
  165. @hookimpl(trylast=True)
  166. def pytest_pyfunc_call(pyfuncitem):
  167. testfunction = pyfuncitem.obj
  168. if pyfuncitem._isyieldedfunction():
  169. testfunction(*pyfuncitem._args)
  170. else:
  171. funcargs = pyfuncitem.funcargs
  172. testargs = {}
  173. for arg in pyfuncitem._fixtureinfo.argnames:
  174. testargs[arg] = funcargs[arg]
  175. testfunction(**testargs)
  176. return True
  177. def pytest_collect_file(path, parent):
  178. ext = path.ext
  179. if ext == ".py":
  180. if not parent.session.isinitpath(path):
  181. if not path_matches_patterns(
  182. path, parent.config.getini("python_files") + ["__init__.py"]
  183. ):
  184. return
  185. ihook = parent.session.gethookproxy(path)
  186. return ihook.pytest_pycollect_makemodule(path=path, parent=parent)
  187. def path_matches_patterns(path, patterns):
  188. """Returns True if the given py.path.local matches one of the patterns in the list of globs given"""
  189. return any(path.fnmatch(pattern) for pattern in patterns)
  190. def pytest_pycollect_makemodule(path, parent):
  191. if path.basename == "__init__.py":
  192. return Package(path, parent)
  193. return Module(path, parent)
  194. @hookimpl(hookwrapper=True)
  195. def pytest_pycollect_makeitem(collector, name, obj):
  196. outcome = yield
  197. res = outcome.get_result()
  198. if res is not None:
  199. return
  200. # nothing was collected elsewhere, let's do it here
  201. if isclass(obj):
  202. if collector.istestclass(obj, name):
  203. Class = collector._getcustomclass("Class")
  204. outcome.force_result(Class(name, parent=collector))
  205. elif collector.istestfunction(obj, name):
  206. # mock seems to store unbound methods (issue473), normalize it
  207. obj = getattr(obj, "__func__", obj)
  208. # We need to try and unwrap the function if it's a functools.partial
  209. # or a funtools.wrapped.
  210. # We musn't if it's been wrapped with mock.patch (python 2 only)
  211. if not (isfunction(obj) or isfunction(get_real_func(obj))):
  212. collector.warn(
  213. code="C2",
  214. message="cannot collect %r because it is not a function." % name,
  215. )
  216. elif getattr(obj, "__test__", True):
  217. if is_generator(obj):
  218. res = Generator(name, parent=collector)
  219. else:
  220. res = list(collector._genfunctions(name, obj))
  221. outcome.force_result(res)
  222. def pytest_make_parametrize_id(config, val, argname=None):
  223. return None
  224. class PyobjContext(object):
  225. module = pyobj_property("Module")
  226. cls = pyobj_property("Class")
  227. instance = pyobj_property("Instance")
  228. class PyobjMixin(PyobjContext):
  229. _ALLOW_MARKERS = True
  230. def __init__(self, *k, **kw):
  231. super(PyobjMixin, self).__init__(*k, **kw)
  232. def obj():
  233. def fget(self):
  234. obj = getattr(self, "_obj", None)
  235. if obj is None:
  236. self._obj = obj = self._getobj()
  237. # XXX evil hack
  238. # used to avoid Instance collector marker duplication
  239. if self._ALLOW_MARKERS:
  240. self.own_markers.extend(get_unpacked_marks(self.obj))
  241. return obj
  242. def fset(self, value):
  243. self._obj = value
  244. return property(fget, fset, None, "underlying python object")
  245. obj = obj()
  246. def _getobj(self):
  247. return getattr(self.parent.obj, self.name)
  248. def getmodpath(self, stopatmodule=True, includemodule=False):
  249. """ return python path relative to the containing module. """
  250. chain = self.listchain()
  251. chain.reverse()
  252. parts = []
  253. for node in chain:
  254. if isinstance(node, Instance):
  255. continue
  256. name = node.name
  257. if isinstance(node, Module):
  258. name = os.path.splitext(name)[0]
  259. if stopatmodule:
  260. if includemodule:
  261. parts.append(name)
  262. break
  263. parts.append(name)
  264. parts.reverse()
  265. s = ".".join(parts)
  266. return s.replace(".[", "[")
  267. def _getfslineno(self):
  268. return getfslineno(self.obj)
  269. def reportinfo(self):
  270. # XXX caching?
  271. obj = self.obj
  272. compat_co_firstlineno = getattr(obj, "compat_co_firstlineno", None)
  273. if isinstance(compat_co_firstlineno, int):
  274. # nose compatibility
  275. fspath = sys.modules[obj.__module__].__file__
  276. if fspath.endswith(".pyc"):
  277. fspath = fspath[:-1]
  278. lineno = compat_co_firstlineno
  279. else:
  280. fspath, lineno = getfslineno(obj)
  281. modpath = self.getmodpath()
  282. assert isinstance(lineno, int)
  283. return fspath, lineno, modpath
  284. class PyCollector(PyobjMixin, nodes.Collector):
  285. def funcnamefilter(self, name):
  286. return self._matches_prefix_or_glob_option("python_functions", name)
  287. def isnosetest(self, obj):
  288. """ Look for the __test__ attribute, which is applied by the
  289. @nose.tools.istest decorator
  290. """
  291. # We explicitly check for "is True" here to not mistakenly treat
  292. # classes with a custom __getattr__ returning something truthy (like a
  293. # function) as test classes.
  294. return safe_getattr(obj, "__test__", False) is True
  295. def classnamefilter(self, name):
  296. return self._matches_prefix_or_glob_option("python_classes", name)
  297. def istestfunction(self, obj, name):
  298. if self.funcnamefilter(name) or self.isnosetest(obj):
  299. if isinstance(obj, staticmethod):
  300. # static methods need to be unwrapped
  301. obj = safe_getattr(obj, "__func__", False)
  302. if obj is False:
  303. # Python 2.6 wraps in a different way that we won't try to handle
  304. msg = "cannot collect static method %r because it is not a function"
  305. self.warn(code="C2", message=msg % name)
  306. return False
  307. return (
  308. safe_getattr(obj, "__call__", False)
  309. and fixtures.getfixturemarker(obj) is None
  310. )
  311. else:
  312. return False
  313. def istestclass(self, obj, name):
  314. return self.classnamefilter(name) or self.isnosetest(obj)
  315. def _matches_prefix_or_glob_option(self, option_name, name):
  316. """
  317. checks if the given name matches the prefix or glob-pattern defined
  318. in ini configuration.
  319. """
  320. for option in self.config.getini(option_name):
  321. if name.startswith(option):
  322. return True
  323. # check that name looks like a glob-string before calling fnmatch
  324. # because this is called for every name in each collected module,
  325. # and fnmatch is somewhat expensive to call
  326. elif ("*" in option or "?" in option or "[" in option) and fnmatch.fnmatch(
  327. name, option
  328. ):
  329. return True
  330. return False
  331. def collect(self):
  332. if not getattr(self.obj, "__test__", True):
  333. return []
  334. # NB. we avoid random getattrs and peek in the __dict__ instead
  335. # (XXX originally introduced from a PyPy need, still true?)
  336. dicts = [getattr(self.obj, "__dict__", {})]
  337. for basecls in inspect.getmro(self.obj.__class__):
  338. dicts.append(basecls.__dict__)
  339. seen = {}
  340. values = []
  341. for dic in dicts:
  342. for name, obj in list(dic.items()):
  343. if name in seen:
  344. continue
  345. seen[name] = True
  346. res = self._makeitem(name, obj)
  347. if res is None:
  348. continue
  349. if not isinstance(res, list):
  350. res = [res]
  351. values.extend(res)
  352. values.sort(key=lambda item: item.reportinfo()[:2])
  353. return values
  354. def makeitem(self, name, obj):
  355. warnings.warn(deprecated.COLLECTOR_MAKEITEM, stacklevel=2)
  356. self._makeitem(name, obj)
  357. def _makeitem(self, name, obj):
  358. # assert self.ihook.fspath == self.fspath, self
  359. return self.ihook.pytest_pycollect_makeitem(collector=self, name=name, obj=obj)
  360. def _genfunctions(self, name, funcobj):
  361. module = self.getparent(Module).obj
  362. clscol = self.getparent(Class)
  363. cls = clscol and clscol.obj or None
  364. transfer_markers(funcobj, cls, module)
  365. fm = self.session._fixturemanager
  366. definition = FunctionDefinition(name=name, parent=self, callobj=funcobj)
  367. fixtureinfo = fm.getfixtureinfo(definition, funcobj, cls)
  368. metafunc = Metafunc(
  369. definition, fixtureinfo, self.config, cls=cls, module=module
  370. )
  371. methods = []
  372. if hasattr(module, "pytest_generate_tests"):
  373. methods.append(module.pytest_generate_tests)
  374. if hasattr(cls, "pytest_generate_tests"):
  375. methods.append(cls().pytest_generate_tests)
  376. if methods:
  377. self.ihook.pytest_generate_tests.call_extra(
  378. methods, dict(metafunc=metafunc)
  379. )
  380. else:
  381. self.ihook.pytest_generate_tests(metafunc=metafunc)
  382. Function = self._getcustomclass("Function")
  383. if not metafunc._calls:
  384. yield Function(name, parent=self, fixtureinfo=fixtureinfo)
  385. else:
  386. # add funcargs() as fixturedefs to fixtureinfo.arg2fixturedefs
  387. fixtures.add_funcarg_pseudo_fixture_def(self, metafunc, fm)
  388. # add_funcarg_pseudo_fixture_def may have shadowed some fixtures
  389. # with direct parametrization, so make sure we update what the
  390. # function really needs.
  391. fixtureinfo.prune_dependency_tree()
  392. for callspec in metafunc._calls:
  393. subname = "%s[%s]" % (name, callspec.id)
  394. yield Function(
  395. name=subname,
  396. parent=self,
  397. callspec=callspec,
  398. callobj=funcobj,
  399. fixtureinfo=fixtureinfo,
  400. keywords={callspec.id: True},
  401. originalname=name,
  402. )
  403. class Module(nodes.File, PyCollector):
  404. """ Collector for test classes and functions. """
  405. def _getobj(self):
  406. return self._importtestmodule()
  407. def collect(self):
  408. self.session._fixturemanager.parsefactories(self)
  409. return super(Module, self).collect()
  410. def _importtestmodule(self):
  411. # we assume we are only called once per module
  412. importmode = self.config.getoption("--import-mode")
  413. try:
  414. mod = self.fspath.pyimport(ensuresyspath=importmode)
  415. except SyntaxError:
  416. raise self.CollectError(
  417. _pytest._code.ExceptionInfo().getrepr(style="short")
  418. )
  419. except self.fspath.ImportMismatchError:
  420. e = sys.exc_info()[1]
  421. raise self.CollectError(
  422. "import file mismatch:\n"
  423. "imported module %r has this __file__ attribute:\n"
  424. " %s\n"
  425. "which is not the same as the test file we want to collect:\n"
  426. " %s\n"
  427. "HINT: remove __pycache__ / .pyc files and/or use a "
  428. "unique basename for your test file modules" % e.args
  429. )
  430. except ImportError:
  431. from _pytest._code.code import ExceptionInfo
  432. exc_info = ExceptionInfo()
  433. if self.config.getoption("verbose") < 2:
  434. exc_info.traceback = exc_info.traceback.filter(filter_traceback)
  435. exc_repr = (
  436. exc_info.getrepr(style="short")
  437. if exc_info.traceback
  438. else exc_info.exconly()
  439. )
  440. formatted_tb = safe_str(exc_repr)
  441. raise self.CollectError(
  442. "ImportError while importing test module '{fspath}'.\n"
  443. "Hint: make sure your test modules/packages have valid Python names.\n"
  444. "Traceback:\n"
  445. "{traceback}".format(fspath=self.fspath, traceback=formatted_tb)
  446. )
  447. except _pytest.runner.Skipped as e:
  448. if e.allow_module_level:
  449. raise
  450. raise self.CollectError(
  451. "Using pytest.skip outside of a test is not allowed. "
  452. "To decorate a test function, use the @pytest.mark.skip "
  453. "or @pytest.mark.skipif decorators instead, and to skip a "
  454. "module use `pytestmark = pytest.mark.{skip,skipif}."
  455. )
  456. self.config.pluginmanager.consider_module(mod)
  457. return mod
  458. def setup(self):
  459. setup_module = _get_xunit_setup_teardown(self.obj, "setUpModule")
  460. if setup_module is None:
  461. setup_module = _get_xunit_setup_teardown(self.obj, "setup_module")
  462. if setup_module is not None:
  463. setup_module()
  464. teardown_module = _get_xunit_setup_teardown(self.obj, "tearDownModule")
  465. if teardown_module is None:
  466. teardown_module = _get_xunit_setup_teardown(self.obj, "teardown_module")
  467. if teardown_module is not None:
  468. self.addfinalizer(teardown_module)
  469. class Package(Module):
  470. def __init__(self, fspath, parent=None, config=None, session=None, nodeid=None):
  471. session = parent.session
  472. nodes.FSCollector.__init__(
  473. self, fspath, parent=parent, config=config, session=session, nodeid=nodeid
  474. )
  475. self.name = fspath.dirname
  476. self.trace = session.trace
  477. self._norecursepatterns = session._norecursepatterns
  478. self.fspath = fspath
  479. def _recurse(self, path):
  480. ihook = self.gethookproxy(path.dirpath())
  481. if ihook.pytest_ignore_collect(path=path, config=self.config):
  482. return False
  483. for pat in self._norecursepatterns:
  484. if path.check(fnmatch=pat):
  485. return False
  486. ihook = self.gethookproxy(path)
  487. ihook.pytest_collect_directory(path=path, parent=self)
  488. return True
  489. def gethookproxy(self, fspath):
  490. # check if we have the common case of running
  491. # hooks with all conftest.py filesall conftest.py
  492. pm = self.config.pluginmanager
  493. my_conftestmodules = pm._getconftestmodules(fspath)
  494. remove_mods = pm._conftest_plugins.difference(my_conftestmodules)
  495. if remove_mods:
  496. # one or more conftests are not in use at this fspath
  497. proxy = FSHookProxy(fspath, pm, remove_mods)
  498. else:
  499. # all plugis are active for this fspath
  500. proxy = self.config.hook
  501. return proxy
  502. def _collectfile(self, path):
  503. ihook = self.gethookproxy(path)
  504. if not self.isinitpath(path):
  505. if ihook.pytest_ignore_collect(path=path, config=self.config):
  506. return ()
  507. return ihook.pytest_collect_file(path=path, parent=self)
  508. def isinitpath(self, path):
  509. return path in self.session._initialpaths
  510. def collect(self):
  511. # XXX: HACK!
  512. # Before starting to collect any files from this package we need
  513. # to cleanup the duplicate paths added by the session's collect().
  514. # Proper fix is to not track these as duplicates in the first place.
  515. for path in list(self.session.config.pluginmanager._duplicatepaths):
  516. # if path.parts()[:len(self.fspath.dirpath().parts())] == self.fspath.dirpath().parts():
  517. if path.dirname.startswith(self.name):
  518. self.session.config.pluginmanager._duplicatepaths.remove(path)
  519. this_path = self.fspath.dirpath()
  520. init_module = this_path.join("__init__.py")
  521. if init_module.check(file=1) and path_matches_patterns(
  522. init_module, self.config.getini("python_files")
  523. ):
  524. yield Module(init_module, self)
  525. pkg_prefixes = set()
  526. for path in this_path.visit(rec=self._recurse, bf=True, sort=True):
  527. # we will visit our own __init__.py file, in which case we skip it
  528. skip = False
  529. if path.basename == "__init__.py" and path.dirpath() == this_path:
  530. continue
  531. for pkg_prefix in pkg_prefixes:
  532. if (
  533. pkg_prefix in path.parts()
  534. and pkg_prefix.join("__init__.py") != path
  535. ):
  536. skip = True
  537. if skip:
  538. continue
  539. if path.isdir() and path.join("__init__.py").check(file=1):
  540. pkg_prefixes.add(path)
  541. for x in self._collectfile(path):
  542. yield x
  543. def _get_xunit_setup_teardown(holder, attr_name, param_obj=None):
  544. """
  545. Return a callable to perform xunit-style setup or teardown if
  546. the function exists in the ``holder`` object.
  547. The ``param_obj`` parameter is the parameter which will be passed to the function
  548. when the callable is called without arguments, defaults to the ``holder`` object.
  549. Return ``None`` if a suitable callable is not found.
  550. """
  551. param_obj = param_obj if param_obj is not None else holder
  552. result = _get_xunit_func(holder, attr_name)
  553. if result is not None:
  554. arg_count = result.__code__.co_argcount
  555. if inspect.ismethod(result):
  556. arg_count -= 1
  557. if arg_count:
  558. return lambda: result(param_obj)
  559. else:
  560. return result
  561. def _get_xunit_func(obj, name):
  562. """Return the attribute from the given object to be used as a setup/teardown
  563. xunit-style function, but only if not marked as a fixture to
  564. avoid calling it twice.
  565. """
  566. meth = getattr(obj, name, None)
  567. if fixtures.getfixturemarker(meth) is None:
  568. return meth
  569. class Class(PyCollector):
  570. """ Collector for test methods. """
  571. def collect(self):
  572. if not safe_getattr(self.obj, "__test__", True):
  573. return []
  574. if hasinit(self.obj):
  575. self.warn(
  576. "C1",
  577. "cannot collect test class %r because it has a "
  578. "__init__ constructor" % self.obj.__name__,
  579. )
  580. return []
  581. elif hasnew(self.obj):
  582. self.warn(
  583. "C1",
  584. "cannot collect test class %r because it has a "
  585. "__new__ constructor" % self.obj.__name__,
  586. )
  587. return []
  588. return [self._getcustomclass("Instance")(name="()", parent=self)]
  589. def setup(self):
  590. setup_class = _get_xunit_func(self.obj, "setup_class")
  591. if setup_class is not None:
  592. setup_class = getattr(setup_class, "im_func", setup_class)
  593. setup_class = getattr(setup_class, "__func__", setup_class)
  594. setup_class(self.obj)
  595. fin_class = getattr(self.obj, "teardown_class", None)
  596. if fin_class is not None:
  597. fin_class = getattr(fin_class, "im_func", fin_class)
  598. fin_class = getattr(fin_class, "__func__", fin_class)
  599. self.addfinalizer(lambda: fin_class(self.obj))
  600. class Instance(PyCollector):
  601. _ALLOW_MARKERS = False # hack, destroy later
  602. # instances share the object with their parents in a way
  603. # that duplicates markers instances if not taken out
  604. # can be removed at node strucutre reorganization time
  605. def _getobj(self):
  606. return self.parent.obj()
  607. def collect(self):
  608. self.session._fixturemanager.parsefactories(self)
  609. return super(Instance, self).collect()
  610. def newinstance(self):
  611. self.obj = self._getobj()
  612. return self.obj
  613. class FunctionMixin(PyobjMixin):
  614. """ mixin for the code common to Function and Generator.
  615. """
  616. def setup(self):
  617. """ perform setup for this test function. """
  618. if hasattr(self, "_preservedparent"):
  619. obj = self._preservedparent
  620. elif isinstance(self.parent, Instance):
  621. obj = self.parent.newinstance()
  622. self.obj = self._getobj()
  623. else:
  624. obj = self.parent.obj
  625. if inspect.ismethod(self.obj):
  626. setup_name = "setup_method"
  627. teardown_name = "teardown_method"
  628. else:
  629. setup_name = "setup_function"
  630. teardown_name = "teardown_function"
  631. setup_func_or_method = _get_xunit_setup_teardown(
  632. obj, setup_name, param_obj=self.obj
  633. )
  634. if setup_func_or_method is not None:
  635. setup_func_or_method()
  636. teardown_func_or_method = _get_xunit_setup_teardown(
  637. obj, teardown_name, param_obj=self.obj
  638. )
  639. if teardown_func_or_method is not None:
  640. self.addfinalizer(teardown_func_or_method)
  641. def _prunetraceback(self, excinfo):
  642. if hasattr(self, "_obj") and not self.config.option.fulltrace:
  643. code = _pytest._code.Code(get_real_func(self.obj))
  644. path, firstlineno = code.path, code.firstlineno
  645. traceback = excinfo.traceback
  646. ntraceback = traceback.cut(path=path, firstlineno=firstlineno)
  647. if ntraceback == traceback:
  648. ntraceback = ntraceback.cut(path=path)
  649. if ntraceback == traceback:
  650. ntraceback = ntraceback.filter(filter_traceback)
  651. if not ntraceback:
  652. ntraceback = traceback
  653. excinfo.traceback = ntraceback.filter()
  654. # issue364: mark all but first and last frames to
  655. # only show a single-line message for each frame
  656. if self.config.option.tbstyle == "auto":
  657. if len(excinfo.traceback) > 2:
  658. for entry in excinfo.traceback[1:-1]:
  659. entry.set_repr_style("short")
  660. def _repr_failure_py(self, excinfo, style="long"):
  661. if excinfo.errisinstance(fail.Exception):
  662. if not excinfo.value.pytrace:
  663. return six.text_type(excinfo.value)
  664. return super(FunctionMixin, self)._repr_failure_py(excinfo, style=style)
  665. def repr_failure(self, excinfo, outerr=None):
  666. assert outerr is None, "XXX outerr usage is deprecated"
  667. style = self.config.option.tbstyle
  668. if style == "auto":
  669. style = "long"
  670. return self._repr_failure_py(excinfo, style=style)
  671. class Generator(FunctionMixin, PyCollector):
  672. def collect(self):
  673. # test generators are seen as collectors but they also
  674. # invoke setup/teardown on popular request
  675. # (induced by the common "test_*" naming shared with normal tests)
  676. from _pytest import deprecated
  677. self.session._setupstate.prepare(self)
  678. # see FunctionMixin.setup and test_setupstate_is_preserved_134
  679. self._preservedparent = self.parent.obj
  680. values = []
  681. seen = {}
  682. for i, x in enumerate(self.obj()):
  683. name, call, args = self.getcallargs(x)
  684. if not callable(call):
  685. raise TypeError("%r yielded non callable test %r" % (self.obj, call))
  686. if name is None:
  687. name = "[%d]" % i
  688. else:
  689. name = "['%s']" % name
  690. if name in seen:
  691. raise ValueError(
  692. "%r generated tests with non-unique name %r" % (self, name)
  693. )
  694. seen[name] = True
  695. values.append(self.Function(name, self, args=args, callobj=call))
  696. self.warn("C1", deprecated.YIELD_TESTS)
  697. return values
  698. def getcallargs(self, obj):
  699. if not isinstance(obj, (tuple, list)):
  700. obj = (obj,)
  701. # explicit naming
  702. if isinstance(obj[0], six.string_types):
  703. name = obj[0]
  704. obj = obj[1:]
  705. else:
  706. name = None
  707. call, args = obj[0], obj[1:]
  708. return name, call, args
  709. def hasinit(obj):
  710. init = getattr(obj, "__init__", None)
  711. if init:
  712. return init != object.__init__
  713. def hasnew(obj):
  714. new = getattr(obj, "__new__", None)
  715. if new:
  716. return new != object.__new__
  717. class CallSpec2(object):
  718. def __init__(self, metafunc):
  719. self.metafunc = metafunc
  720. self.funcargs = {}
  721. self._idlist = []
  722. self.params = {}
  723. self._globalid = NOTSET
  724. self._globalparam = NOTSET
  725. self._arg2scopenum = {} # used for sorting parametrized resources
  726. self.marks = []
  727. self.indices = {}
  728. def copy(self):
  729. cs = CallSpec2(self.metafunc)
  730. cs.funcargs.update(self.funcargs)
  731. cs.params.update(self.params)
  732. cs.marks.extend(self.marks)
  733. cs.indices.update(self.indices)
  734. cs._arg2scopenum.update(self._arg2scopenum)
  735. cs._idlist = list(self._idlist)
  736. cs._globalid = self._globalid
  737. cs._globalparam = self._globalparam
  738. return cs
  739. def _checkargnotcontained(self, arg):
  740. if arg in self.params or arg in self.funcargs:
  741. raise ValueError("duplicate %r" % (arg,))
  742. def getparam(self, name):
  743. try:
  744. return self.params[name]
  745. except KeyError:
  746. if self._globalparam is NOTSET:
  747. raise ValueError(name)
  748. return self._globalparam
  749. @property
  750. def id(self):
  751. return "-".join(map(str, filter(None, self._idlist)))
  752. def setmulti2(self, valtypes, argnames, valset, id, marks, scopenum, param_index):
  753. for arg, val in zip(argnames, valset):
  754. self._checkargnotcontained(arg)
  755. valtype_for_arg = valtypes[arg]
  756. getattr(self, valtype_for_arg)[arg] = val
  757. self.indices[arg] = param_index
  758. self._arg2scopenum[arg] = scopenum
  759. self._idlist.append(id)
  760. self.marks.extend(normalize_mark_list(marks))
  761. def setall(self, funcargs, id, param):
  762. for x in funcargs:
  763. self._checkargnotcontained(x)
  764. self.funcargs.update(funcargs)
  765. if id is not NOTSET:
  766. self._idlist.append(id)
  767. if param is not NOTSET:
  768. assert self._globalparam is NOTSET
  769. self._globalparam = param
  770. for arg in funcargs:
  771. self._arg2scopenum[arg] = fixtures.scopenum_function
  772. class Metafunc(fixtures.FuncargnamesCompatAttr):
  773. """
  774. Metafunc objects are passed to the :func:`pytest_generate_tests <_pytest.hookspec.pytest_generate_tests>` hook.
  775. They help to inspect a test function and to generate tests according to
  776. test configuration or values specified in the class or module where a
  777. test function is defined.
  778. """
  779. def __init__(self, definition, fixtureinfo, config, cls=None, module=None):
  780. assert (
  781. isinstance(definition, FunctionDefinition)
  782. or type(definition).__name__ == "DefinitionMock"
  783. )
  784. self.definition = definition
  785. #: access to the :class:`_pytest.config.Config` object for the test session
  786. self.config = config
  787. #: the module object where the test function is defined in.
  788. self.module = module
  789. #: underlying python test function
  790. self.function = definition.obj
  791. #: set of fixture names required by the test function
  792. self.fixturenames = fixtureinfo.names_closure
  793. #: class object where the test function is defined in or ``None``.
  794. self.cls = cls
  795. self._calls = []
  796. self._ids = set()
  797. self._arg2fixturedefs = fixtureinfo.name2fixturedefs
  798. def parametrize(self, argnames, argvalues, indirect=False, ids=None, scope=None):
  799. """ Add new invocations to the underlying test function using the list
  800. of argvalues for the given argnames. Parametrization is performed
  801. during the collection phase. If you need to setup expensive resources
  802. see about setting indirect to do it rather at test setup time.
  803. :arg argnames: a comma-separated string denoting one or more argument
  804. names, or a list/tuple of argument strings.
  805. :arg argvalues: The list of argvalues determines how often a
  806. test is invoked with different argument values. If only one
  807. argname was specified argvalues is a list of values. If N
  808. argnames were specified, argvalues must be a list of N-tuples,
  809. where each tuple-element specifies a value for its respective
  810. argname.
  811. :arg indirect: The list of argnames or boolean. A list of arguments'
  812. names (subset of argnames). If True the list contains all names from
  813. the argnames. Each argvalue corresponding to an argname in this list will
  814. be passed as request.param to its respective argname fixture
  815. function so that it can perform more expensive setups during the
  816. setup phase of a test rather than at collection time.
  817. :arg ids: list of string ids, or a callable.
  818. If strings, each is corresponding to the argvalues so that they are
  819. part of the test id. If None is given as id of specific test, the
  820. automatically generated id for that argument will be used.
  821. If callable, it should take one argument (a single argvalue) and return
  822. a string or return None. If None, the automatically generated id for that
  823. argument will be used.
  824. If no ids are provided they will be generated automatically from
  825. the argvalues.
  826. :arg scope: if specified it denotes the scope of the parameters.
  827. The scope is used for grouping tests by parameter instances.
  828. It will also override any fixture-function defined scope, allowing
  829. to set a dynamic scope using test context or configuration.
  830. """
  831. from _pytest.fixtures import scope2index
  832. from _pytest.mark import ParameterSet
  833. argnames, parameters = ParameterSet._for_parametrize(
  834. argnames, argvalues, self.function, self.config
  835. )
  836. del argvalues
  837. if scope is None:
  838. scope = _find_parametrized_scope(argnames, self._arg2fixturedefs, indirect)
  839. self._validate_if_using_arg_names(argnames, indirect)
  840. arg_values_types = self._resolve_arg_value_types(argnames, indirect)
  841. ids = self._resolve_arg_ids(argnames, ids, parameters)
  842. scopenum = scope2index(scope, descr="call to {}".format(self.parametrize))
  843. # create the new calls: if we are parametrize() multiple times (by applying the decorator
  844. # more than once) then we accumulate those calls generating the cartesian product
  845. # of all calls
  846. newcalls = []
  847. for callspec in self._calls or [CallSpec2(self)]:
  848. for param_index, (param_id, param_set) in enumerate(zip(ids, parameters)):
  849. newcallspec = callspec.copy()
  850. newcallspec.setmulti2(
  851. arg_values_types,
  852. argnames,
  853. param_set.values,
  854. param_id,
  855. param_set.marks,
  856. scopenum,
  857. param_index,
  858. )
  859. newcalls.append(newcallspec)
  860. self._calls = newcalls
  861. def _resolve_arg_ids(self, argnames, ids, parameters):
  862. """Resolves the actual ids for the given argnames, based on the ``ids`` parameter given
  863. to ``parametrize``.
  864. :param List[str] argnames: list of argument names passed to ``parametrize()``.
  865. :param ids: the ids parameter of the parametrized call (see docs).
  866. :param List[ParameterSet] parameters: the list of parameter values, same size as ``argnames``.
  867. :rtype: List[str]
  868. :return: the list of ids for each argname given
  869. """
  870. from py.io import saferepr
  871. idfn = None
  872. if callable(ids):
  873. idfn = ids
  874. ids = None
  875. if ids:
  876. if len(ids) != len(parameters):
  877. raise ValueError(
  878. "%d tests specified with %d ids" % (len(parameters), len(ids))
  879. )
  880. for id_value in ids:
  881. if id_value is not None and not isinstance(id_value, six.string_types):
  882. msg = "ids must be list of strings, found: %s (type: %s)"
  883. raise ValueError(
  884. msg % (saferepr(id_value), type(id_value).__name__)
  885. )
  886. ids = idmaker(argnames, parameters, idfn, ids, self.config)
  887. return ids
  888. def _resolve_arg_value_types(self, argnames, indirect):
  889. """Resolves if each parametrized argument must be considered a parameter to a fixture or a "funcarg"
  890. to the function, based on the ``indirect`` parameter of the parametrized() call.
  891. :param List[str] argnames: list of argument names passed to ``parametrize()``.
  892. :param indirect: same ``indirect`` parameter of ``parametrize()``.
  893. :rtype: Dict[str, str]
  894. A dict mapping each arg name to either:
  895. * "params" if the argname should be the parameter of a fixture of the same name.
  896. * "funcargs" if the argname should be a parameter to the parametrized test function.
  897. """
  898. valtypes = {}
  899. if indirect is True:
  900. valtypes = dict.fromkeys(argnames, "params")
  901. elif indirect is False:
  902. valtypes = dict.fromkeys(argnames, "funcargs")
  903. elif isinstance(indirect, (tuple, list)):
  904. valtypes = dict.fromkeys(argnames, "funcargs")
  905. for arg in indirect:
  906. if arg not in argnames:
  907. raise ValueError(
  908. "indirect given to %r: fixture %r doesn't exist"
  909. % (self.function, arg)
  910. )
  911. valtypes[arg] = "params"
  912. return valtypes
  913. def _validate_if_using_arg_names(self, argnames, indirect):
  914. """
  915. Check if all argnames are being used, by default values, or directly/indirectly.
  916. :param List[str] argnames: list of argument names passed to ``parametrize()``.
  917. :param indirect: same ``indirect`` parameter of ``parametrize()``.
  918. :raise ValueError: if validation fails.
  919. """
  920. default_arg_names = set(get_default_arg_names(self.function))
  921. for arg in argnames:
  922. if arg not in self.fixturenames:
  923. if arg in default_arg_names:
  924. raise ValueError(
  925. "%r already takes an argument %r with a default value"
  926. % (self.function, arg)
  927. )
  928. else:
  929. if isinstance(indirect, (tuple, list)):
  930. name = "fixture" if arg in indirect else "argument"
  931. else:
  932. name = "fixture" if indirect else "argument"
  933. raise ValueError("%r uses no %s %r" % (self.function, name, arg))
  934. def addcall(self, funcargs=None, id=NOTSET, param=NOTSET):
  935. """ Add a new call to the underlying test function during the collection phase of a test run.
  936. .. deprecated:: 3.3
  937. Use :meth:`parametrize` instead.
  938. Note that request.addcall() is called during the test collection phase prior and
  939. independently to actual test execution. You should only use addcall()
  940. if you need to specify multiple arguments of a test function.
  941. :arg funcargs: argument keyword dictionary used when invoking
  942. the test function.
  943. :arg id: used for reporting and identification purposes. If you
  944. don't supply an `id` an automatic unique id will be generated.
  945. :arg param: a parameter which will be exposed to a later fixture function
  946. invocation through the ``request.param`` attribute.
  947. """
  948. if self.config:
  949. self.config.warn(
  950. "C1", message=deprecated.METAFUNC_ADD_CALL, fslocation=None
  951. )
  952. assert funcargs is None or isinstance(funcargs, dict)
  953. if funcargs is not None:
  954. for name in funcargs:
  955. if name not in self.fixturenames:
  956. fail("funcarg %r not used in this function." % name)
  957. else:
  958. funcargs = {}
  959. if id is None:
  960. raise ValueError("id=None not allowed")
  961. if id is NOTSET:
  962. id = len(self._calls)
  963. id = str(id)
  964. if id in self._ids:
  965. raise ValueError("duplicate id %r" % id)
  966. self._ids.add(id)
  967. cs = CallSpec2(self)
  968. cs.setall(funcargs, id, param)
  969. self._calls.append(cs)
  970. def _find_parametrized_scope(argnames, arg2fixturedefs, indirect):
  971. """Find the most appropriate scope for a parametrized call based on its arguments.
  972. When there's at least one direct argument, always use "function" scope.
  973. When a test function is parametrized and all its arguments are indirect
  974. (e.g. fixtures), return the most narrow scope based on the fixtures used.
  975. Related to issue #1832, based on code posted by @Kingdread.
  976. """
  977. from _pytest.fixtures import scopes
  978. indirect_as_list = isinstance(indirect, (list, tuple))
  979. all_arguments_are_fixtures = (
  980. indirect is True or indirect_as_list and len(indirect) == argnames
  981. )
  982. if all_arguments_are_fixtures:
  983. fixturedefs = arg2fixturedefs or {}
  984. used_scopes = [fixturedef[0].scope for name, fixturedef in fixturedefs.items()]
  985. if used_scopes:
  986. # Takes the most narrow scope from used fixtures
  987. for scope in reversed(scopes):
  988. if scope in used_scopes:
  989. return scope
  990. return "function"
  991. def _idval(val, argname, idx, idfn, config=None):
  992. if idfn:
  993. s = None
  994. try:
  995. s = idfn(val)
  996. except Exception:
  997. # See issue https://github.com/pytest-dev/pytest/issues/2169
  998. import warnings
  999. msg = (
  1000. "Raised while trying to determine id of parameter %s at position %d."
  1001. % (argname, idx)
  1002. )
  1003. msg += "\nUpdate your code as this will raise an error in pytest-4.0."
  1004. warnings.warn(msg, DeprecationWarning)
  1005. if s:
  1006. return ascii_escaped(s)
  1007. if config:
  1008. hook_id = config.hook.pytest_make_parametrize_id(
  1009. config=config, val=val, argname=argname
  1010. )
  1011. if hook_id:
  1012. return hook_id
  1013. if isinstance(val, STRING_TYPES):
  1014. return ascii_escaped(val)
  1015. elif isinstance(val, (float, int, bool, NoneType)):
  1016. return str(val)
  1017. elif isinstance(val, REGEX_TYPE):
  1018. return ascii_escaped(val.pattern)
  1019. elif enum is not None and isinstance(val, enum.Enum):
  1020. return str(val)
  1021. elif (isclass(val) or isfunction(val)) and hasattr(val, "__name__"):
  1022. return val.__name__
  1023. return str(argname) + str(idx)
  1024. def _idvalset(idx, parameterset, argnames, idfn, ids, config=None):
  1025. if parameterset.id is not None:
  1026. return parameterset.id
  1027. if ids is None or (idx >= len(ids) or ids[idx] is None):
  1028. this_id = [
  1029. _idval(val, argname, idx, idfn, config)
  1030. for val, argname in zip(parameterset.values, argnames)
  1031. ]
  1032. return "-".join(this_id)
  1033. else:
  1034. return ascii_escaped(ids[idx])
  1035. def idmaker(argnames, parametersets, idfn=None, ids=None, config=None):
  1036. ids = [
  1037. _idvalset(valindex, parameterset, argnames, idfn, ids, config)
  1038. for valindex, parameterset in enumerate(parametersets)
  1039. ]
  1040. if len(set(ids)) != len(ids):
  1041. # The ids are not unique
  1042. duplicates = [testid for testid in ids if ids.count(testid) > 1]
  1043. counters = collections.defaultdict(lambda: 0)
  1044. for index, testid in enumerate(ids):
  1045. if testid in duplicates:
  1046. ids[index] = testid + str(counters[testid])
  1047. counters[testid] += 1
  1048. return ids
  1049. def show_fixtures_per_test(config):
  1050. from _pytest.main import wrap_session
  1051. return wrap_session(config, _show_fixtures_per_test)
  1052. def _show_fixtures_per_test(config, session):
  1053. import _pytest.config
  1054. session.perform_collect()
  1055. curdir = py.path.local()
  1056. tw = _pytest.config.create_terminal_writer(config)
  1057. verbose = config.getvalue("verbose")
  1058. def get_best_relpath(func):
  1059. loc = getlocation(func, curdir)
  1060. return curdir.bestrelpath(loc)
  1061. def write_fixture(fixture_def):
  1062. argname = fixture_def.argname
  1063. if verbose <= 0 and argname.startswith("_"):
  1064. return
  1065. if verbose > 0:
  1066. bestrel = get_best_relpath(fixture_def.func)
  1067. funcargspec = "{} -- {}".format(argname, bestrel)
  1068. else:
  1069. funcargspec = argname
  1070. tw.line(funcargspec, green=True)
  1071. fixture_doc = fixture_def.func.__doc__
  1072. if fixture_doc:
  1073. write_docstring(tw, fixture_doc)
  1074. else:
  1075. tw.line(" no docstring available", red=True)
  1076. def write_item(item):
  1077. try:
  1078. info = item._fixtureinfo
  1079. except AttributeError:
  1080. # doctests items have no _fixtureinfo attribute
  1081. return
  1082. if not info.name2fixturedefs:
  1083. # this test item does not use any fixtures
  1084. return
  1085. tw.line()
  1086. tw.sep("-", "fixtures used by {}".format(item.name))
  1087. tw.sep("-", "({})".format(get_best_relpath(item.function)))
  1088. # dict key not used in loop but needed for sorting
  1089. for _, fixturedefs in sorted(info.name2fixturedefs.items()):
  1090. assert fixturedefs is not None
  1091. if not fixturedefs:
  1092. continue
  1093. # last item is expected to be the one used by the test item
  1094. write_fixture(fixturedefs[-1])
  1095. for session_item in session.items:
  1096. write_item(session_item)
  1097. def showfixtures(config):
  1098. from _pytest.main import wrap_session
  1099. return wrap_session(config, _showfixtures_main)
  1100. def _showfixtures_main(config, session):
  1101. import _pytest.config
  1102. session.perform_collect()
  1103. curdir = py.path.local()
  1104. tw = _pytest.config.create_terminal_writer(config)
  1105. verbose = config.getvalue("verbose")
  1106. fm = session._fixturemanager
  1107. available = []
  1108. seen = set()
  1109. for argname, fixturedefs in fm._arg2fixturedefs.items():
  1110. assert fixturedefs is not None
  1111. if not fixturedefs:
  1112. continue
  1113. for fixturedef in fixturedefs:
  1114. loc = getlocation(fixturedef.func, curdir)
  1115. if (fixturedef.argname, loc) in seen:
  1116. continue
  1117. seen.add((fixturedef.argname, loc))
  1118. available.append(
  1119. (
  1120. len(fixturedef.baseid),
  1121. fixturedef.func.__module__,
  1122. curdir.bestrelpath(loc),
  1123. fixturedef.argname,
  1124. fixturedef,
  1125. )
  1126. )
  1127. available.sort()
  1128. currentmodule = None
  1129. for baseid, module, bestrel, argname, fixturedef in available:
  1130. if currentmodule != module:
  1131. if not module.startswith("_pytest."):
  1132. tw.line()
  1133. tw.sep("-", "fixtures defined from %s" % (module,))
  1134. currentmodule = module
  1135. if verbose <= 0 and argname[0] == "_":
  1136. continue
  1137. if verbose > 0:
  1138. funcargspec = "%s -- %s" % (argname, bestrel)
  1139. else:
  1140. funcargspec = argname
  1141. tw.line(funcargspec, green=True)
  1142. loc = getlocation(fixturedef.func, curdir)
  1143. doc = fixturedef.func.__doc__ or ""
  1144. if doc:
  1145. write_docstring(tw, doc)
  1146. else:
  1147. tw.line(" %s: no docstring available" % (loc,), red=True)
  1148. def write_docstring(tw, doc):
  1149. INDENT = " "
  1150. doc = doc.rstrip()
  1151. if "\n" in doc:
  1152. firstline, rest = doc.split("\n", 1)
  1153. else:
  1154. firstline, rest = doc, ""
  1155. if firstline.strip():
  1156. tw.line(INDENT + firstline.strip())
  1157. if rest:
  1158. for line in dedent(rest).split("\n"):
  1159. tw.write(INDENT + line + "\n")
  1160. class Function(FunctionMixin, nodes.Item, fixtures.FuncargnamesCompatAttr):
  1161. """ a Function Item is responsible for setting up and executing a
  1162. Python test function.
  1163. """
  1164. _genid = None
  1165. # disable since functions handle it themselfes
  1166. _ALLOW_MARKERS = False
  1167. def __init__(
  1168. self,
  1169. name,
  1170. parent,
  1171. args=None,
  1172. config=None,
  1173. callspec=None,
  1174. callobj=NOTSET,
  1175. keywords=None,
  1176. session=None,
  1177. fixtureinfo=None,
  1178. originalname=None,
  1179. ):
  1180. super(Function, self).__init__(name, parent, config=config, session=session)
  1181. self._args = args
  1182. if callobj is not NOTSET:
  1183. self.obj = callobj
  1184. self.keywords.update(self.obj.__dict__)
  1185. self.own_markers.extend(get_unpacked_marks(self.obj))
  1186. if callspec:
  1187. self.callspec = callspec
  1188. # this is total hostile and a mess
  1189. # keywords are broken by design by now
  1190. # this will be redeemed later
  1191. for mark in callspec.marks:
  1192. # feel free to cry, this was broken for years before
  1193. # and keywords cant fix it per design
  1194. self.keywords[mark.name] = mark
  1195. self.own_markers.extend(normalize_mark_list(callspec.marks))
  1196. if keywords:
  1197. self.keywords.update(keywords)
  1198. if fixtureinfo is None:
  1199. fixtureinfo = self.session._fixturemanager.getfixtureinfo(
  1200. self, self.obj, self.cls, funcargs=not self._isyieldedfunction()
  1201. )
  1202. self._fixtureinfo = fixtureinfo
  1203. self.fixturenames = fixtureinfo.names_closure
  1204. self._initrequest()
  1205. #: original function name, without any decorations (for example
  1206. #: parametrization adds a ``"[...]"`` suffix to function names).
  1207. #:
  1208. #: .. versionadded:: 3.0
  1209. self.originalname = originalname
  1210. def _initrequest(self):
  1211. self.funcargs = {}
  1212. if self._isyieldedfunction():
  1213. assert not hasattr(
  1214. self, "callspec"
  1215. ), "yielded functions (deprecated) cannot have funcargs"
  1216. else:
  1217. if hasattr(self, "callspec"):
  1218. callspec = self.callspec
  1219. assert not callspec.funcargs
  1220. self._genid = callspec.id
  1221. if hasattr(callspec, "param"):
  1222. self.param = callspec.param
  1223. self._request = fixtures.FixtureRequest(self)
  1224. @property
  1225. def function(self):
  1226. "underlying python 'function' object"
  1227. return getattr(self.obj, "im_func", self.obj)
  1228. def _getobj(self):
  1229. name = self.name
  1230. i = name.find("[") # parametrization
  1231. if i != -1:
  1232. name = name[:i]
  1233. return getattr(self.parent.obj, name)
  1234. @property
  1235. def _pyfuncitem(self):
  1236. "(compatonly) for code expecting pytest-2.2 style request objects"
  1237. return self
  1238. def _isyieldedfunction(self):
  1239. return getattr(self, "_args", None) is not None
  1240. def runtest(self):
  1241. """ execute the underlying test function. """
  1242. self.ihook.pytest_pyfunc_call(pyfuncitem=self)
  1243. def setup(self):
  1244. super(Function, self).setup()
  1245. fixtures.fillfixtures(self)
  1246. class FunctionDefinition(Function):
  1247. """
  1248. internal hack until we get actual definition nodes instead of the
  1249. crappy metafunc hack
  1250. """
  1251. def runtest(self):
  1252. raise RuntimeError("function definitions are not supposed to be used")
  1253. setup = runtest