PageRenderTime 56ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/_pytest/main.py

https://bitbucket.org/kkris/pypy
Python | 576 lines | 489 code | 52 blank | 35 comment | 48 complexity | 3756d21fddd07d510ee4b513c55f171f MD5 | raw file
  1. """ core implementation of testing process: init, session, runtest loop. """
  2. import py
  3. import pytest, _pytest
  4. import os, sys, imp
  5. tracebackcutdir = py.path.local(_pytest.__file__).dirpath()
  6. # exitcodes for the command line
  7. EXIT_OK = 0
  8. EXIT_TESTSFAILED = 1
  9. EXIT_INTERRUPTED = 2
  10. EXIT_INTERNALERROR = 3
  11. name_re = py.std.re.compile("^[a-zA-Z_]\w*$")
  12. def pytest_addoption(parser):
  13. parser.addini("norecursedirs", "directory patterns to avoid for recursion",
  14. type="args", default=('.*', 'CVS', '_darcs', '{arch}'))
  15. #parser.addini("dirpatterns",
  16. # "patterns specifying possible locations of test files",
  17. # type="linelist", default=["**/test_*.txt",
  18. # "**/test_*.py", "**/*_test.py"]
  19. #)
  20. group = parser.getgroup("general", "running and selection options")
  21. group._addoption('-x', '--exitfirst', action="store_true", default=False,
  22. dest="exitfirst",
  23. help="exit instantly on first error or failed test."),
  24. group._addoption('--maxfail', metavar="num",
  25. action="store", type="int", dest="maxfail", default=0,
  26. help="exit after first num failures or errors.")
  27. group._addoption('--strict', action="store_true",
  28. help="run pytest in strict mode, warnings become errors.")
  29. group = parser.getgroup("collect", "collection")
  30. group.addoption('--collectonly',
  31. action="store_true", dest="collectonly",
  32. help="only collect tests, don't execute them."),
  33. group.addoption('--pyargs', action="store_true",
  34. help="try to interpret all arguments as python packages.")
  35. group.addoption("--ignore", action="append", metavar="path",
  36. help="ignore path during collection (multi-allowed).")
  37. group.addoption('--confcutdir', dest="confcutdir", default=None,
  38. metavar="dir",
  39. help="only load conftest.py's relative to specified dir.")
  40. group = parser.getgroup("debugconfig",
  41. "test session debugging and configuration")
  42. group.addoption('--basetemp', dest="basetemp", default=None, metavar="dir",
  43. help="base temporary directory for this test run.")
  44. def pytest_namespace():
  45. collect = dict(Item=Item, Collector=Collector, File=File, Session=Session)
  46. return dict(collect=collect)
  47. def pytest_configure(config):
  48. py.test.config = config # compatibiltiy
  49. if config.option.exitfirst:
  50. config.option.maxfail = 1
  51. def wrap_session(config, doit):
  52. """Skeleton command line program"""
  53. session = Session(config)
  54. session.exitstatus = EXIT_OK
  55. initstate = 0
  56. try:
  57. config.pluginmanager.do_configure(config)
  58. initstate = 1
  59. config.hook.pytest_sessionstart(session=session)
  60. initstate = 2
  61. doit(config, session)
  62. except pytest.UsageError:
  63. raise
  64. except KeyboardInterrupt:
  65. excinfo = py.code.ExceptionInfo()
  66. config.hook.pytest_keyboard_interrupt(excinfo=excinfo)
  67. session.exitstatus = EXIT_INTERRUPTED
  68. except:
  69. excinfo = py.code.ExceptionInfo()
  70. config.pluginmanager.notify_exception(excinfo, config.option)
  71. session.exitstatus = EXIT_INTERNALERROR
  72. if excinfo.errisinstance(SystemExit):
  73. sys.stderr.write("mainloop: caught Spurious SystemExit!\n")
  74. if initstate >= 2:
  75. config.hook.pytest_sessionfinish(session=session,
  76. exitstatus=session.exitstatus or (session._testsfailed and 1))
  77. if not session.exitstatus and session._testsfailed:
  78. session.exitstatus = EXIT_TESTSFAILED
  79. if initstate >= 1:
  80. config.pluginmanager.do_unconfigure(config)
  81. return session.exitstatus
  82. def pytest_cmdline_main(config):
  83. return wrap_session(config, _main)
  84. def _main(config, session):
  85. """ default command line protocol for initialization, session,
  86. running tests and reporting. """
  87. config.hook.pytest_collection(session=session)
  88. config.hook.pytest_runtestloop(session=session)
  89. def pytest_collection(session):
  90. return session.perform_collect()
  91. def pytest_runtestloop(session):
  92. if session.config.option.collectonly:
  93. return True
  94. for i, item in enumerate(session.items):
  95. try:
  96. nextitem = session.items[i+1]
  97. except IndexError:
  98. nextitem = None
  99. item.config.hook.pytest_runtest_protocol(item=item, nextitem=nextitem)
  100. if session.shouldstop:
  101. raise session.Interrupted(session.shouldstop)
  102. return True
  103. def pytest_ignore_collect(path, config):
  104. p = path.dirpath()
  105. ignore_paths = config._getconftest_pathlist("collect_ignore", path=p)
  106. ignore_paths = ignore_paths or []
  107. excludeopt = config.getvalue("ignore")
  108. if excludeopt:
  109. ignore_paths.extend([py.path.local(x) for x in excludeopt])
  110. return path in ignore_paths
  111. class HookProxy:
  112. def __init__(self, fspath, config):
  113. self.fspath = fspath
  114. self.config = config
  115. def __getattr__(self, name):
  116. hookmethod = getattr(self.config.hook, name)
  117. def call_matching_hooks(**kwargs):
  118. plugins = self.config._getmatchingplugins(self.fspath)
  119. return hookmethod.pcall(plugins, **kwargs)
  120. return call_matching_hooks
  121. def compatproperty(name):
  122. def fget(self):
  123. return getattr(pytest, name)
  124. return property(fget, None, None,
  125. "deprecated attribute %r, use pytest.%s" % (name,name))
  126. class Node(object):
  127. """ base class for all Nodes in the collection tree.
  128. Collector subclasses have children, Items are terminal nodes."""
  129. def __init__(self, name, parent=None, config=None, session=None):
  130. #: a unique name with the scope of the parent
  131. self.name = name
  132. #: the parent collector node.
  133. self.parent = parent
  134. #: the test config object
  135. self.config = config or parent.config
  136. #: the collection this node is part of
  137. self.session = session or parent.session
  138. #: filesystem path where this node was collected from
  139. self.fspath = getattr(parent, 'fspath', None)
  140. self.ihook = self.session.gethookproxy(self.fspath)
  141. self.keywords = {self.name: True}
  142. Module = compatproperty("Module")
  143. Class = compatproperty("Class")
  144. Instance = compatproperty("Instance")
  145. Function = compatproperty("Function")
  146. File = compatproperty("File")
  147. Item = compatproperty("Item")
  148. def _getcustomclass(self, name):
  149. cls = getattr(self, name)
  150. if cls != getattr(pytest, name):
  151. py.log._apiwarn("2.0", "use of node.%s is deprecated, "
  152. "use pytest_pycollect_makeitem(...) to create custom "
  153. "collection nodes" % name)
  154. return cls
  155. def __repr__(self):
  156. return "<%s %r>" %(self.__class__.__name__, getattr(self, 'name', None))
  157. # methods for ordering nodes
  158. @property
  159. def nodeid(self):
  160. try:
  161. return self._nodeid
  162. except AttributeError:
  163. self._nodeid = x = self._makeid()
  164. return x
  165. def _makeid(self):
  166. return self.parent.nodeid + "::" + self.name
  167. def __eq__(self, other):
  168. if not isinstance(other, Node):
  169. return False
  170. return self.__class__ == other.__class__ and \
  171. self.name == other.name and self.parent == other.parent
  172. def __ne__(self, other):
  173. return not self == other
  174. def __hash__(self):
  175. return hash((self.name, self.parent))
  176. def setup(self):
  177. pass
  178. def teardown(self):
  179. pass
  180. def _memoizedcall(self, attrname, function):
  181. exattrname = "_ex_" + attrname
  182. failure = getattr(self, exattrname, None)
  183. if failure is not None:
  184. py.builtin._reraise(failure[0], failure[1], failure[2])
  185. if hasattr(self, attrname):
  186. return getattr(self, attrname)
  187. try:
  188. res = function()
  189. except py.builtin._sysex:
  190. raise
  191. except:
  192. failure = py.std.sys.exc_info()
  193. setattr(self, exattrname, failure)
  194. raise
  195. setattr(self, attrname, res)
  196. return res
  197. def listchain(self):
  198. """ return list of all parent collectors up to self,
  199. starting from root of collection tree. """
  200. chain = []
  201. item = self
  202. while item is not None:
  203. chain.append(item)
  204. item = item.parent
  205. chain.reverse()
  206. return chain
  207. def listnames(self):
  208. return [x.name for x in self.listchain()]
  209. def getplugins(self):
  210. return self.config._getmatchingplugins(self.fspath)
  211. def getparent(self, cls):
  212. current = self
  213. while current and not isinstance(current, cls):
  214. current = current.parent
  215. return current
  216. def _prunetraceback(self, excinfo):
  217. pass
  218. def _repr_failure_py(self, excinfo, style=None):
  219. if self.config.option.fulltrace:
  220. style="long"
  221. else:
  222. self._prunetraceback(excinfo)
  223. # XXX should excinfo.getrepr record all data and toterminal()
  224. # process it?
  225. if style is None:
  226. if self.config.option.tbstyle == "short":
  227. style = "short"
  228. else:
  229. style = "long"
  230. return excinfo.getrepr(funcargs=True,
  231. showlocals=self.config.option.showlocals,
  232. style=style)
  233. repr_failure = _repr_failure_py
  234. class Collector(Node):
  235. """ Collector instances create children through collect()
  236. and thus iteratively build a tree.
  237. """
  238. class CollectError(Exception):
  239. """ an error during collection, contains a custom message. """
  240. def collect(self):
  241. """ returns a list of children (items and collectors)
  242. for this collection node.
  243. """
  244. raise NotImplementedError("abstract")
  245. def repr_failure(self, excinfo):
  246. """ represent a collection failure. """
  247. if excinfo.errisinstance(self.CollectError):
  248. exc = excinfo.value
  249. return str(exc.args[0])
  250. return self._repr_failure_py(excinfo, style="short")
  251. def _memocollect(self):
  252. """ internal helper method to cache results of calling collect(). """
  253. return self._memoizedcall('_collected', lambda: list(self.collect()))
  254. def _prunetraceback(self, excinfo):
  255. if hasattr(self, 'fspath'):
  256. path = self.fspath
  257. traceback = excinfo.traceback
  258. ntraceback = traceback.cut(path=self.fspath)
  259. if ntraceback == traceback:
  260. ntraceback = ntraceback.cut(excludepath=tracebackcutdir)
  261. excinfo.traceback = ntraceback.filter()
  262. class FSCollector(Collector):
  263. def __init__(self, fspath, parent=None, config=None, session=None):
  264. fspath = py.path.local(fspath) # xxx only for test_resultlog.py?
  265. name = fspath.basename
  266. if parent is not None:
  267. rel = fspath.relto(parent.fspath)
  268. if rel:
  269. name = rel
  270. name = name.replace(os.sep, "/")
  271. super(FSCollector, self).__init__(name, parent, config, session)
  272. self.fspath = fspath
  273. def _makeid(self):
  274. if self == self.session:
  275. return "."
  276. relpath = self.session.fspath.bestrelpath(self.fspath)
  277. if os.sep != "/":
  278. relpath = relpath.replace(os.sep, "/")
  279. return relpath
  280. class File(FSCollector):
  281. """ base class for collecting tests from a file. """
  282. class Item(Node):
  283. """ a basic test invocation item. Note that for a single function
  284. there might be multiple test invocation items.
  285. """
  286. nextitem = None
  287. def reportinfo(self):
  288. return self.fspath, None, ""
  289. @property
  290. def location(self):
  291. try:
  292. return self._location
  293. except AttributeError:
  294. location = self.reportinfo()
  295. # bestrelpath is a quite slow function
  296. cache = self.config.__dict__.setdefault("_bestrelpathcache", {})
  297. try:
  298. fspath = cache[location[0]]
  299. except KeyError:
  300. fspath = self.session.fspath.bestrelpath(location[0])
  301. cache[location[0]] = fspath
  302. location = (fspath, location[1], str(location[2]))
  303. self._location = location
  304. return location
  305. class NoMatch(Exception):
  306. """ raised if matching cannot locate a matching names. """
  307. class Session(FSCollector):
  308. class Interrupted(KeyboardInterrupt):
  309. """ signals an interrupted test run. """
  310. __module__ = 'builtins' # for py3
  311. def __init__(self, config):
  312. super(Session, self).__init__(py.path.local(), parent=None,
  313. config=config, session=self)
  314. assert self.config.pluginmanager.register(self, name="session", prepend=True)
  315. self._testsfailed = 0
  316. self.shouldstop = False
  317. self.trace = config.trace.root.get("collection")
  318. self._norecursepatterns = config.getini("norecursedirs")
  319. def pytest_collectstart(self):
  320. if self.shouldstop:
  321. raise self.Interrupted(self.shouldstop)
  322. def pytest_runtest_logreport(self, report):
  323. if report.failed and 'xfail' not in getattr(report, 'keywords', []):
  324. self._testsfailed += 1
  325. maxfail = self.config.getvalue("maxfail")
  326. if maxfail and self._testsfailed >= maxfail:
  327. self.shouldstop = "stopping after %d failures" % (
  328. self._testsfailed)
  329. pytest_collectreport = pytest_runtest_logreport
  330. def isinitpath(self, path):
  331. return path in self._initialpaths
  332. def gethookproxy(self, fspath):
  333. return HookProxy(fspath, self.config)
  334. def perform_collect(self, args=None, genitems=True):
  335. hook = self.config.hook
  336. try:
  337. items = self._perform_collect(args, genitems)
  338. hook.pytest_collection_modifyitems(session=self,
  339. config=self.config, items=items)
  340. finally:
  341. hook.pytest_collection_finish(session=self)
  342. return items
  343. def _perform_collect(self, args, genitems):
  344. if args is None:
  345. args = self.config.args
  346. self.trace("perform_collect", self, args)
  347. self.trace.root.indent += 1
  348. self._notfound = []
  349. self._initialpaths = set()
  350. self._initialparts = []
  351. self.items = items = []
  352. for arg in args:
  353. parts = self._parsearg(arg)
  354. self._initialparts.append(parts)
  355. self._initialpaths.add(parts[0])
  356. self.ihook.pytest_collectstart(collector=self)
  357. rep = self.ihook.pytest_make_collect_report(collector=self)
  358. self.ihook.pytest_collectreport(report=rep)
  359. self.trace.root.indent -= 1
  360. if self._notfound:
  361. for arg, exc in self._notfound:
  362. line = "(no name %r in any of %r)" % (arg, exc.args[0])
  363. raise pytest.UsageError("not found: %s\n%s" %(arg, line))
  364. if not genitems:
  365. return rep.result
  366. else:
  367. if rep.passed:
  368. for node in rep.result:
  369. self.items.extend(self.genitems(node))
  370. return items
  371. def collect(self):
  372. for parts in self._initialparts:
  373. arg = "::".join(map(str, parts))
  374. self.trace("processing argument", arg)
  375. self.trace.root.indent += 1
  376. try:
  377. for x in self._collect(arg):
  378. yield x
  379. except NoMatch:
  380. # we are inside a make_report hook so
  381. # we cannot directly pass through the exception
  382. self._notfound.append((arg, sys.exc_info()[1]))
  383. self.trace.root.indent -= 1
  384. break
  385. self.trace.root.indent -= 1
  386. def _collect(self, arg):
  387. names = self._parsearg(arg)
  388. path = names.pop(0)
  389. if path.check(dir=1):
  390. assert not names, "invalid arg %r" %(arg,)
  391. for path in path.visit(fil=lambda x: x.check(file=1),
  392. rec=self._recurse, bf=True, sort=True):
  393. for x in self._collectfile(path):
  394. yield x
  395. else:
  396. assert path.check(file=1)
  397. for x in self.matchnodes(self._collectfile(path), names):
  398. yield x
  399. def _collectfile(self, path):
  400. ihook = self.gethookproxy(path)
  401. if not self.isinitpath(path):
  402. if ihook.pytest_ignore_collect(path=path, config=self.config):
  403. return ()
  404. return ihook.pytest_collect_file(path=path, parent=self)
  405. def _recurse(self, path):
  406. ihook = self.gethookproxy(path.dirpath())
  407. if ihook.pytest_ignore_collect(path=path, config=self.config):
  408. return
  409. for pat in self._norecursepatterns:
  410. if path.check(fnmatch=pat):
  411. return False
  412. ihook = self.gethookproxy(path)
  413. ihook.pytest_collect_directory(path=path, parent=self)
  414. return True
  415. def _tryconvertpyarg(self, x):
  416. mod = None
  417. path = [os.path.abspath('.')] + sys.path
  418. for name in x.split('.'):
  419. # ignore anything that's not a proper name here
  420. # else something like --pyargs will mess up '.'
  421. # since imp.find_module will actually sometimes work for it
  422. # but it's supposed to be considered a filesystem path
  423. # not a package
  424. if name_re.match(name) is None:
  425. return x
  426. try:
  427. fd, mod, type_ = imp.find_module(name, path)
  428. except ImportError:
  429. return x
  430. else:
  431. if fd is not None:
  432. fd.close()
  433. if type_[2] != imp.PKG_DIRECTORY:
  434. path = [os.path.dirname(mod)]
  435. else:
  436. path = [mod]
  437. return mod
  438. def _parsearg(self, arg):
  439. """ return (fspath, names) tuple after checking the file exists. """
  440. arg = str(arg)
  441. if self.config.option.pyargs:
  442. arg = self._tryconvertpyarg(arg)
  443. parts = str(arg).split("::")
  444. relpath = parts[0].replace("/", os.sep)
  445. path = self.fspath.join(relpath, abs=True)
  446. if not path.check():
  447. if self.config.option.pyargs:
  448. msg = "file or package not found: "
  449. else:
  450. msg = "file not found: "
  451. raise pytest.UsageError(msg + arg)
  452. parts[0] = path
  453. return parts
  454. def matchnodes(self, matching, names):
  455. self.trace("matchnodes", matching, names)
  456. self.trace.root.indent += 1
  457. nodes = self._matchnodes(matching, names)
  458. num = len(nodes)
  459. self.trace("matchnodes finished -> ", num, "nodes")
  460. self.trace.root.indent -= 1
  461. if num == 0:
  462. raise NoMatch(matching, names[:1])
  463. return nodes
  464. def _matchnodes(self, matching, names):
  465. if not matching or not names:
  466. return matching
  467. name = names[0]
  468. assert name
  469. nextnames = names[1:]
  470. resultnodes = []
  471. for node in matching:
  472. if isinstance(node, pytest.Item):
  473. if not names:
  474. resultnodes.append(node)
  475. continue
  476. assert isinstance(node, pytest.Collector)
  477. node.ihook.pytest_collectstart(collector=node)
  478. rep = node.ihook.pytest_make_collect_report(collector=node)
  479. if rep.passed:
  480. has_matched = False
  481. for x in rep.result:
  482. if x.name == name:
  483. resultnodes.extend(self.matchnodes([x], nextnames))
  484. has_matched = True
  485. # XXX accept IDs that don't have "()" for class instances
  486. if not has_matched and len(rep.result) == 1 and x.name == "()":
  487. nextnames.insert(0, name)
  488. resultnodes.extend(self.matchnodes([x], nextnames))
  489. node.ihook.pytest_collectreport(report=rep)
  490. return resultnodes
  491. def genitems(self, node):
  492. self.trace("genitems", node)
  493. if isinstance(node, pytest.Item):
  494. node.ihook.pytest_itemcollected(item=node)
  495. yield node
  496. else:
  497. assert isinstance(node, pytest.Collector)
  498. node.ihook.pytest_collectstart(collector=node)
  499. rep = node.ihook.pytest_make_collect_report(collector=node)
  500. if rep.passed:
  501. for subnode in rep.result:
  502. for x in self.genitems(subnode):
  503. yield x
  504. node.ihook.pytest_collectreport(report=rep)