pytester.py 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310
  1. """(disabled by default) support for testing pytest and pytest plugins."""
  2. from __future__ import absolute_import, division, print_function
  3. import codecs
  4. import gc
  5. import os
  6. import platform
  7. import re
  8. import subprocess
  9. import six
  10. import sys
  11. import time
  12. import traceback
  13. from fnmatch import fnmatch
  14. from weakref import WeakKeyDictionary
  15. from _pytest.capture import MultiCapture, SysCapture
  16. from _pytest._code import Source
  17. import py
  18. import pytest
  19. from _pytest.main import Session, EXIT_OK
  20. from _pytest.assertion.rewrite import AssertionRewritingHook
  21. from _pytest.compat import Path
  22. from _pytest.compat import safe_str
  23. IGNORE_PAM = [ # filenames added when obtaining details about the current user
  24. u"/var/lib/sss/mc/passwd"
  25. ]
  26. def pytest_addoption(parser):
  27. parser.addoption(
  28. "--lsof",
  29. action="store_true",
  30. dest="lsof",
  31. default=False,
  32. help="run FD checks if lsof is available",
  33. )
  34. parser.addoption(
  35. "--runpytest",
  36. default="inprocess",
  37. dest="runpytest",
  38. choices=("inprocess", "subprocess"),
  39. help=(
  40. "run pytest sub runs in tests using an 'inprocess' "
  41. "or 'subprocess' (python -m main) method"
  42. ),
  43. )
  44. parser.addini(
  45. "pytester_example_dir", help="directory to take the pytester example files from"
  46. )
  47. def pytest_configure(config):
  48. if config.getvalue("lsof"):
  49. checker = LsofFdLeakChecker()
  50. if checker.matching_platform():
  51. config.pluginmanager.register(checker)
  52. class LsofFdLeakChecker(object):
  53. def get_open_files(self):
  54. out = self._exec_lsof()
  55. open_files = self._parse_lsof_output(out)
  56. return open_files
  57. def _exec_lsof(self):
  58. pid = os.getpid()
  59. return py.process.cmdexec("lsof -Ffn0 -p %d" % pid)
  60. def _parse_lsof_output(self, out):
  61. def isopen(line):
  62. return line.startswith("f") and (
  63. "deleted" not in line
  64. and "mem" not in line
  65. and "txt" not in line
  66. and "cwd" not in line
  67. )
  68. open_files = []
  69. for line in out.split("\n"):
  70. if isopen(line):
  71. fields = line.split("\0")
  72. fd = fields[0][1:]
  73. filename = fields[1][1:]
  74. if filename in IGNORE_PAM:
  75. continue
  76. if filename.startswith("/"):
  77. open_files.append((fd, filename))
  78. return open_files
  79. def matching_platform(self):
  80. try:
  81. py.process.cmdexec("lsof -v")
  82. except (py.process.cmdexec.Error, UnicodeDecodeError):
  83. # cmdexec may raise UnicodeDecodeError on Windows systems with
  84. # locale other than English:
  85. # https://bitbucket.org/pytest-dev/py/issues/66
  86. return False
  87. else:
  88. return True
  89. @pytest.hookimpl(hookwrapper=True, tryfirst=True)
  90. def pytest_runtest_protocol(self, item):
  91. lines1 = self.get_open_files()
  92. yield
  93. if hasattr(sys, "pypy_version_info"):
  94. gc.collect()
  95. lines2 = self.get_open_files()
  96. new_fds = {t[0] for t in lines2} - {t[0] for t in lines1}
  97. leaked_files = [t for t in lines2 if t[0] in new_fds]
  98. if leaked_files:
  99. error = []
  100. error.append("***** %s FD leakage detected" % len(leaked_files))
  101. error.extend([str(f) for f in leaked_files])
  102. error.append("*** Before:")
  103. error.extend([str(f) for f in lines1])
  104. error.append("*** After:")
  105. error.extend([str(f) for f in lines2])
  106. error.append(error[0])
  107. error.append("*** function %s:%s: %s " % item.location)
  108. error.append("See issue #2366")
  109. item.warn("", "\n".join(error))
  110. # XXX copied from execnet's conftest.py - needs to be merged
  111. winpymap = {
  112. "python2.7": r"C:\Python27\python.exe",
  113. "python3.4": r"C:\Python34\python.exe",
  114. "python3.5": r"C:\Python35\python.exe",
  115. "python3.6": r"C:\Python36\python.exe",
  116. }
  117. def getexecutable(name, cache={}):
  118. try:
  119. return cache[name]
  120. except KeyError:
  121. executable = py.path.local.sysfind(name)
  122. if executable:
  123. import subprocess
  124. popen = subprocess.Popen(
  125. [str(executable), "--version"],
  126. universal_newlines=True,
  127. stderr=subprocess.PIPE,
  128. )
  129. out, err = popen.communicate()
  130. if name == "jython":
  131. if not err or "2.5" not in err:
  132. executable = None
  133. if "2.5.2" in err:
  134. executable = None # http://bugs.jython.org/issue1790
  135. elif popen.returncode != 0:
  136. # handle pyenv's 127
  137. executable = None
  138. cache[name] = executable
  139. return executable
  140. @pytest.fixture(params=["python2.7", "python3.4", "pypy", "pypy3"])
  141. def anypython(request):
  142. name = request.param
  143. executable = getexecutable(name)
  144. if executable is None:
  145. if sys.platform == "win32":
  146. executable = winpymap.get(name, None)
  147. if executable:
  148. executable = py.path.local(executable)
  149. if executable.check():
  150. return executable
  151. pytest.skip("no suitable %s found" % (name,))
  152. return executable
  153. # used at least by pytest-xdist plugin
  154. @pytest.fixture
  155. def _pytest(request):
  156. """Return a helper which offers a gethookrecorder(hook) method which
  157. returns a HookRecorder instance which helps to make assertions about called
  158. hooks.
  159. """
  160. return PytestArg(request)
  161. class PytestArg(object):
  162. def __init__(self, request):
  163. self.request = request
  164. def gethookrecorder(self, hook):
  165. hookrecorder = HookRecorder(hook._pm)
  166. self.request.addfinalizer(hookrecorder.finish_recording)
  167. return hookrecorder
  168. def get_public_names(values):
  169. """Only return names from iterator values without a leading underscore."""
  170. return [x for x in values if x[0] != "_"]
  171. class ParsedCall(object):
  172. def __init__(self, name, kwargs):
  173. self.__dict__.update(kwargs)
  174. self._name = name
  175. def __repr__(self):
  176. d = self.__dict__.copy()
  177. del d["_name"]
  178. return "<ParsedCall %r(**%r)>" % (self._name, d)
  179. class HookRecorder(object):
  180. """Record all hooks called in a plugin manager.
  181. This wraps all the hook calls in the plugin manager, recording each call
  182. before propagating the normal calls.
  183. """
  184. def __init__(self, pluginmanager):
  185. self._pluginmanager = pluginmanager
  186. self.calls = []
  187. def before(hook_name, hook_impls, kwargs):
  188. self.calls.append(ParsedCall(hook_name, kwargs))
  189. def after(outcome, hook_name, hook_impls, kwargs):
  190. pass
  191. self._undo_wrapping = pluginmanager.add_hookcall_monitoring(before, after)
  192. def finish_recording(self):
  193. self._undo_wrapping()
  194. def getcalls(self, names):
  195. if isinstance(names, str):
  196. names = names.split()
  197. return [call for call in self.calls if call._name in names]
  198. def assert_contains(self, entries):
  199. __tracebackhide__ = True
  200. i = 0
  201. entries = list(entries)
  202. backlocals = sys._getframe(1).f_locals
  203. while entries:
  204. name, check = entries.pop(0)
  205. for ind, call in enumerate(self.calls[i:]):
  206. if call._name == name:
  207. print("NAMEMATCH", name, call)
  208. if eval(check, backlocals, call.__dict__):
  209. print("CHECKERMATCH", repr(check), "->", call)
  210. else:
  211. print("NOCHECKERMATCH", repr(check), "-", call)
  212. continue
  213. i += ind + 1
  214. break
  215. print("NONAMEMATCH", name, "with", call)
  216. else:
  217. pytest.fail("could not find %r check %r" % (name, check))
  218. def popcall(self, name):
  219. __tracebackhide__ = True
  220. for i, call in enumerate(self.calls):
  221. if call._name == name:
  222. del self.calls[i]
  223. return call
  224. lines = ["could not find call %r, in:" % (name,)]
  225. lines.extend([" %s" % x for x in self.calls])
  226. pytest.fail("\n".join(lines))
  227. def getcall(self, name):
  228. values = self.getcalls(name)
  229. assert len(values) == 1, (name, values)
  230. return values[0]
  231. # functionality for test reports
  232. def getreports(self, names="pytest_runtest_logreport pytest_collectreport"):
  233. return [x.report for x in self.getcalls(names)]
  234. def matchreport(
  235. self,
  236. inamepart="",
  237. names="pytest_runtest_logreport pytest_collectreport",
  238. when=None,
  239. ):
  240. """return a testreport whose dotted import path matches"""
  241. values = []
  242. for rep in self.getreports(names=names):
  243. try:
  244. if not when and rep.when != "call" and rep.passed:
  245. # setup/teardown passing reports - let's ignore those
  246. continue
  247. except AttributeError:
  248. pass
  249. if when and getattr(rep, "when", None) != when:
  250. continue
  251. if not inamepart or inamepart in rep.nodeid.split("::"):
  252. values.append(rep)
  253. if not values:
  254. raise ValueError(
  255. "could not find test report matching %r: "
  256. "no test reports at all!" % (inamepart,)
  257. )
  258. if len(values) > 1:
  259. raise ValueError(
  260. "found 2 or more testreports matching %r: %s" % (inamepart, values)
  261. )
  262. return values[0]
  263. def getfailures(self, names="pytest_runtest_logreport pytest_collectreport"):
  264. return [rep for rep in self.getreports(names) if rep.failed]
  265. def getfailedcollections(self):
  266. return self.getfailures("pytest_collectreport")
  267. def listoutcomes(self):
  268. passed = []
  269. skipped = []
  270. failed = []
  271. for rep in self.getreports("pytest_collectreport pytest_runtest_logreport"):
  272. if rep.passed:
  273. if getattr(rep, "when", None) == "call":
  274. passed.append(rep)
  275. elif rep.skipped:
  276. skipped.append(rep)
  277. elif rep.failed:
  278. failed.append(rep)
  279. return passed, skipped, failed
  280. def countoutcomes(self):
  281. return [len(x) for x in self.listoutcomes()]
  282. def assertoutcome(self, passed=0, skipped=0, failed=0):
  283. realpassed, realskipped, realfailed = self.listoutcomes()
  284. assert passed == len(realpassed)
  285. assert skipped == len(realskipped)
  286. assert failed == len(realfailed)
  287. def clear(self):
  288. self.calls[:] = []
  289. @pytest.fixture
  290. def linecomp(request):
  291. return LineComp()
  292. @pytest.fixture(name="LineMatcher")
  293. def LineMatcher_fixture(request):
  294. return LineMatcher
  295. @pytest.fixture
  296. def testdir(request, tmpdir_factory):
  297. return Testdir(request, tmpdir_factory)
  298. rex_outcome = re.compile(r"(\d+) ([\w-]+)")
  299. class RunResult(object):
  300. """The result of running a command.
  301. Attributes:
  302. :ret: the return value
  303. :outlines: list of lines captured from stdout
  304. :errlines: list of lines captures from stderr
  305. :stdout: :py:class:`LineMatcher` of stdout, use ``stdout.str()`` to
  306. reconstruct stdout or the commonly used ``stdout.fnmatch_lines()``
  307. method
  308. :stderr: :py:class:`LineMatcher` of stderr
  309. :duration: duration in seconds
  310. """
  311. def __init__(self, ret, outlines, errlines, duration):
  312. self.ret = ret
  313. self.outlines = outlines
  314. self.errlines = errlines
  315. self.stdout = LineMatcher(outlines)
  316. self.stderr = LineMatcher(errlines)
  317. self.duration = duration
  318. def parseoutcomes(self):
  319. """Return a dictionary of outcomestring->num from parsing the terminal
  320. output that the test process produced.
  321. """
  322. for line in reversed(self.outlines):
  323. if "seconds" in line:
  324. outcomes = rex_outcome.findall(line)
  325. if outcomes:
  326. d = {}
  327. for num, cat in outcomes:
  328. d[cat] = int(num)
  329. return d
  330. raise ValueError("Pytest terminal report not found")
  331. def assert_outcomes(self, passed=0, skipped=0, failed=0, error=0):
  332. """Assert that the specified outcomes appear with the respective
  333. numbers (0 means it didn't occur) in the text output from a test run.
  334. """
  335. d = self.parseoutcomes()
  336. obtained = {
  337. "passed": d.get("passed", 0),
  338. "skipped": d.get("skipped", 0),
  339. "failed": d.get("failed", 0),
  340. "error": d.get("error", 0),
  341. }
  342. assert obtained == dict(
  343. passed=passed, skipped=skipped, failed=failed, error=error
  344. )
  345. class CwdSnapshot(object):
  346. def __init__(self):
  347. self.__saved = os.getcwd()
  348. def restore(self):
  349. os.chdir(self.__saved)
  350. class SysModulesSnapshot(object):
  351. def __init__(self, preserve=None):
  352. self.__preserve = preserve
  353. self.__saved = dict(sys.modules)
  354. def restore(self):
  355. if self.__preserve:
  356. self.__saved.update(
  357. (k, m) for k, m in sys.modules.items() if self.__preserve(k)
  358. )
  359. sys.modules.clear()
  360. sys.modules.update(self.__saved)
  361. class SysPathsSnapshot(object):
  362. def __init__(self):
  363. self.__saved = list(sys.path), list(sys.meta_path)
  364. def restore(self):
  365. sys.path[:], sys.meta_path[:] = self.__saved
  366. class Testdir(object):
  367. """Temporary test directory with tools to test/run pytest itself.
  368. This is based on the ``tmpdir`` fixture but provides a number of methods
  369. which aid with testing pytest itself. Unless :py:meth:`chdir` is used all
  370. methods will use :py:attr:`tmpdir` as their current working directory.
  371. Attributes:
  372. :tmpdir: The :py:class:`py.path.local` instance of the temporary directory.
  373. :plugins: A list of plugins to use with :py:meth:`parseconfig` and
  374. :py:meth:`runpytest`. Initially this is an empty list but plugins can
  375. be added to the list. The type of items to add to the list depends on
  376. the method using them so refer to them for details.
  377. """
  378. def __init__(self, request, tmpdir_factory):
  379. self.request = request
  380. self._mod_collections = WeakKeyDictionary()
  381. name = request.function.__name__
  382. self.tmpdir = tmpdir_factory.mktemp(name, numbered=True)
  383. self.plugins = []
  384. self._cwd_snapshot = CwdSnapshot()
  385. self._sys_path_snapshot = SysPathsSnapshot()
  386. self._sys_modules_snapshot = self.__take_sys_modules_snapshot()
  387. self.chdir()
  388. self.request.addfinalizer(self.finalize)
  389. method = self.request.config.getoption("--runpytest")
  390. if method == "inprocess":
  391. self._runpytest_method = self.runpytest_inprocess
  392. elif method == "subprocess":
  393. self._runpytest_method = self.runpytest_subprocess
  394. def __repr__(self):
  395. return "<Testdir %r>" % (self.tmpdir,)
  396. def finalize(self):
  397. """Clean up global state artifacts.
  398. Some methods modify the global interpreter state and this tries to
  399. clean this up. It does not remove the temporary directory however so
  400. it can be looked at after the test run has finished.
  401. """
  402. self._sys_modules_snapshot.restore()
  403. self._sys_path_snapshot.restore()
  404. self._cwd_snapshot.restore()
  405. def __take_sys_modules_snapshot(self):
  406. # some zope modules used by twisted-related tests keep internal state
  407. # and can't be deleted; we had some trouble in the past with
  408. # `zope.interface` for example
  409. def preserve_module(name):
  410. return name.startswith("zope")
  411. return SysModulesSnapshot(preserve=preserve_module)
  412. def make_hook_recorder(self, pluginmanager):
  413. """Create a new :py:class:`HookRecorder` for a PluginManager."""
  414. assert not hasattr(pluginmanager, "reprec")
  415. pluginmanager.reprec = reprec = HookRecorder(pluginmanager)
  416. self.request.addfinalizer(reprec.finish_recording)
  417. return reprec
  418. def chdir(self):
  419. """Cd into the temporary directory.
  420. This is done automatically upon instantiation.
  421. """
  422. self.tmpdir.chdir()
  423. def _makefile(self, ext, args, kwargs, encoding="utf-8"):
  424. items = list(kwargs.items())
  425. def to_text(s):
  426. return s.decode(encoding) if isinstance(s, bytes) else six.text_type(s)
  427. if args:
  428. source = u"\n".join(to_text(x) for x in args)
  429. basename = self.request.function.__name__
  430. items.insert(0, (basename, source))
  431. ret = None
  432. for basename, value in items:
  433. p = self.tmpdir.join(basename).new(ext=ext)
  434. p.dirpath().ensure_dir()
  435. source = Source(value)
  436. source = u"\n".join(to_text(line) for line in source.lines)
  437. p.write(source.strip().encode(encoding), "wb")
  438. if ret is None:
  439. ret = p
  440. return ret
  441. def makefile(self, ext, *args, **kwargs):
  442. r"""Create new file(s) in the testdir.
  443. :param str ext: The extension the file(s) should use, including the dot, e.g. `.py`.
  444. :param list[str] args: All args will be treated as strings and joined using newlines.
  445. The result will be written as contents to the file. The name of the
  446. file will be based on the test function requesting this fixture.
  447. :param kwargs: Each keyword is the name of a file, while the value of it will
  448. be written as contents of the file.
  449. Examples:
  450. .. code-block:: python
  451. testdir.makefile(".txt", "line1", "line2")
  452. testdir.makefile(".ini", pytest="[pytest]\naddopts=-rs\n")
  453. """
  454. return self._makefile(ext, args, kwargs)
  455. def makeconftest(self, source):
  456. """Write a contest.py file with 'source' as contents."""
  457. return self.makepyfile(conftest=source)
  458. def makeini(self, source):
  459. """Write a tox.ini file with 'source' as contents."""
  460. return self.makefile(".ini", tox=source)
  461. def getinicfg(self, source):
  462. """Return the pytest section from the tox.ini config file."""
  463. p = self.makeini(source)
  464. return py.iniconfig.IniConfig(p)["pytest"]
  465. def makepyfile(self, *args, **kwargs):
  466. """Shortcut for .makefile() with a .py extension."""
  467. return self._makefile(".py", args, kwargs)
  468. def maketxtfile(self, *args, **kwargs):
  469. """Shortcut for .makefile() with a .txt extension."""
  470. return self._makefile(".txt", args, kwargs)
  471. def syspathinsert(self, path=None):
  472. """Prepend a directory to sys.path, defaults to :py:attr:`tmpdir`.
  473. This is undone automatically when this object dies at the end of each
  474. test.
  475. """
  476. if path is None:
  477. path = self.tmpdir
  478. sys.path.insert(0, str(path))
  479. # a call to syspathinsert() usually means that the caller wants to
  480. # import some dynamically created files, thus with python3 we
  481. # invalidate its import caches
  482. self._possibly_invalidate_import_caches()
  483. def _possibly_invalidate_import_caches(self):
  484. # invalidate caches if we can (py33 and above)
  485. try:
  486. import importlib
  487. except ImportError:
  488. pass
  489. else:
  490. if hasattr(importlib, "invalidate_caches"):
  491. importlib.invalidate_caches()
  492. def mkdir(self, name):
  493. """Create a new (sub)directory."""
  494. return self.tmpdir.mkdir(name)
  495. def mkpydir(self, name):
  496. """Create a new python package.
  497. This creates a (sub)directory with an empty ``__init__.py`` file so it
  498. gets recognised as a python package.
  499. """
  500. p = self.mkdir(name)
  501. p.ensure("__init__.py")
  502. return p
  503. def copy_example(self, name=None):
  504. from . import experiments
  505. import warnings
  506. warnings.warn(experiments.PYTESTER_COPY_EXAMPLE, stacklevel=2)
  507. example_dir = self.request.config.getini("pytester_example_dir")
  508. if example_dir is None:
  509. raise ValueError("pytester_example_dir is unset, can't copy examples")
  510. example_dir = self.request.config.rootdir.join(example_dir)
  511. for extra_element in self.request.node.iter_markers("pytester_example_path"):
  512. assert extra_element.args
  513. example_dir = example_dir.join(*extra_element.args)
  514. if name is None:
  515. func_name = self.request.function.__name__
  516. maybe_dir = example_dir / func_name
  517. maybe_file = example_dir / (func_name + ".py")
  518. if maybe_dir.isdir():
  519. example_path = maybe_dir
  520. elif maybe_file.isfile():
  521. example_path = maybe_file
  522. else:
  523. raise LookupError(
  524. "{} cant be found as module or package in {}".format(
  525. func_name, example_dir.bestrelpath(self.request.confg.rootdir)
  526. )
  527. )
  528. else:
  529. example_path = example_dir.join(name)
  530. if example_path.isdir() and not example_path.join("__init__.py").isfile():
  531. example_path.copy(self.tmpdir)
  532. return self.tmpdir
  533. elif example_path.isfile():
  534. result = self.tmpdir.join(example_path.basename)
  535. example_path.copy(result)
  536. return result
  537. else:
  538. raise LookupError(
  539. 'example "{}" is not found as a file or directory'.format(example_path)
  540. )
  541. Session = Session
  542. def getnode(self, config, arg):
  543. """Return the collection node of a file.
  544. :param config: :py:class:`_pytest.config.Config` instance, see
  545. :py:meth:`parseconfig` and :py:meth:`parseconfigure` to create the
  546. configuration
  547. :param arg: a :py:class:`py.path.local` instance of the file
  548. """
  549. session = Session(config)
  550. assert "::" not in str(arg)
  551. p = py.path.local(arg)
  552. config.hook.pytest_sessionstart(session=session)
  553. res = session.perform_collect([str(p)], genitems=False)[0]
  554. config.hook.pytest_sessionfinish(session=session, exitstatus=EXIT_OK)
  555. return res
  556. def getpathnode(self, path):
  557. """Return the collection node of a file.
  558. This is like :py:meth:`getnode` but uses :py:meth:`parseconfigure` to
  559. create the (configured) pytest Config instance.
  560. :param path: a :py:class:`py.path.local` instance of the file
  561. """
  562. config = self.parseconfigure(path)
  563. session = Session(config)
  564. x = session.fspath.bestrelpath(path)
  565. config.hook.pytest_sessionstart(session=session)
  566. res = session.perform_collect([x], genitems=False)[0]
  567. config.hook.pytest_sessionfinish(session=session, exitstatus=EXIT_OK)
  568. return res
  569. def genitems(self, colitems):
  570. """Generate all test items from a collection node.
  571. This recurses into the collection node and returns a list of all the
  572. test items contained within.
  573. """
  574. session = colitems[0].session
  575. result = []
  576. for colitem in colitems:
  577. result.extend(session.genitems(colitem))
  578. return result
  579. def runitem(self, source):
  580. """Run the "test_func" Item.
  581. The calling test instance (class containing the test method) must
  582. provide a ``.getrunner()`` method which should return a runner which
  583. can run the test protocol for a single item, e.g.
  584. :py:func:`_pytest.runner.runtestprotocol`.
  585. """
  586. # used from runner functional tests
  587. item = self.getitem(source)
  588. # the test class where we are called from wants to provide the runner
  589. testclassinstance = self.request.instance
  590. runner = testclassinstance.getrunner()
  591. return runner(item)
  592. def inline_runsource(self, source, *cmdlineargs):
  593. """Run a test module in process using ``pytest.main()``.
  594. This run writes "source" into a temporary file and runs
  595. ``pytest.main()`` on it, returning a :py:class:`HookRecorder` instance
  596. for the result.
  597. :param source: the source code of the test module
  598. :param cmdlineargs: any extra command line arguments to use
  599. :return: :py:class:`HookRecorder` instance of the result
  600. """
  601. p = self.makepyfile(source)
  602. values = list(cmdlineargs) + [p]
  603. return self.inline_run(*values)
  604. def inline_genitems(self, *args):
  605. """Run ``pytest.main(['--collectonly'])`` in-process.
  606. Runs the :py:func:`pytest.main` function to run all of pytest inside
  607. the test process itself like :py:meth:`inline_run`, but returns a
  608. tuple of the collected items and a :py:class:`HookRecorder` instance.
  609. """
  610. rec = self.inline_run("--collect-only", *args)
  611. items = [x.item for x in rec.getcalls("pytest_itemcollected")]
  612. return items, rec
  613. def inline_run(self, *args, **kwargs):
  614. """Run ``pytest.main()`` in-process, returning a HookRecorder.
  615. Runs the :py:func:`pytest.main` function to run all of pytest inside
  616. the test process itself. This means it can return a
  617. :py:class:`HookRecorder` instance which gives more detailed results
  618. from that run than can be done by matching stdout/stderr from
  619. :py:meth:`runpytest`.
  620. :param args: command line arguments to pass to :py:func:`pytest.main`
  621. :param plugin: (keyword-only) extra plugin instances the
  622. ``pytest.main()`` instance should use
  623. :return: a :py:class:`HookRecorder` instance
  624. """
  625. finalizers = []
  626. try:
  627. # When running pytest inline any plugins active in the main test
  628. # process are already imported. So this disables the warning which
  629. # will trigger to say they can no longer be rewritten, which is
  630. # fine as they have already been rewritten.
  631. orig_warn = AssertionRewritingHook._warn_already_imported
  632. def revert_warn_already_imported():
  633. AssertionRewritingHook._warn_already_imported = orig_warn
  634. finalizers.append(revert_warn_already_imported)
  635. AssertionRewritingHook._warn_already_imported = lambda *a: None
  636. # Any sys.module or sys.path changes done while running pytest
  637. # inline should be reverted after the test run completes to avoid
  638. # clashing with later inline tests run within the same pytest test,
  639. # e.g. just because they use matching test module names.
  640. finalizers.append(self.__take_sys_modules_snapshot().restore)
  641. finalizers.append(SysPathsSnapshot().restore)
  642. # Important note:
  643. # - our tests should not leave any other references/registrations
  644. # laying around other than possibly loaded test modules
  645. # referenced from sys.modules, as nothing will clean those up
  646. # automatically
  647. rec = []
  648. class Collect(object):
  649. def pytest_configure(x, config):
  650. rec.append(self.make_hook_recorder(config.pluginmanager))
  651. plugins = kwargs.get("plugins") or []
  652. plugins.append(Collect())
  653. ret = pytest.main(list(args), plugins=plugins)
  654. if len(rec) == 1:
  655. reprec = rec.pop()
  656. else:
  657. class reprec(object):
  658. pass
  659. reprec.ret = ret
  660. # typically we reraise keyboard interrupts from the child run
  661. # because it's our user requesting interruption of the testing
  662. if ret == 2 and not kwargs.get("no_reraise_ctrlc"):
  663. calls = reprec.getcalls("pytest_keyboard_interrupt")
  664. if calls and calls[-1].excinfo.type == KeyboardInterrupt:
  665. raise KeyboardInterrupt()
  666. return reprec
  667. finally:
  668. for finalizer in finalizers:
  669. finalizer()
  670. def runpytest_inprocess(self, *args, **kwargs):
  671. """Return result of running pytest in-process, providing a similar
  672. interface to what self.runpytest() provides.
  673. """
  674. if kwargs.get("syspathinsert"):
  675. self.syspathinsert()
  676. now = time.time()
  677. capture = MultiCapture(Capture=SysCapture)
  678. capture.start_capturing()
  679. try:
  680. try:
  681. reprec = self.inline_run(*args, **kwargs)
  682. except SystemExit as e:
  683. class reprec(object):
  684. ret = e.args[0]
  685. except Exception:
  686. traceback.print_exc()
  687. class reprec(object):
  688. ret = 3
  689. finally:
  690. out, err = capture.readouterr()
  691. capture.stop_capturing()
  692. sys.stdout.write(out)
  693. sys.stderr.write(err)
  694. res = RunResult(reprec.ret, out.split("\n"), err.split("\n"), time.time() - now)
  695. res.reprec = reprec
  696. return res
  697. def runpytest(self, *args, **kwargs):
  698. """Run pytest inline or in a subprocess, depending on the command line
  699. option "--runpytest" and return a :py:class:`RunResult`.
  700. """
  701. args = self._ensure_basetemp(args)
  702. return self._runpytest_method(*args, **kwargs)
  703. def _ensure_basetemp(self, args):
  704. args = list(args)
  705. for x in args:
  706. if safe_str(x).startswith("--basetemp"):
  707. break
  708. else:
  709. args.append("--basetemp=%s" % self.tmpdir.dirpath("basetemp"))
  710. return args
  711. def parseconfig(self, *args):
  712. """Return a new pytest Config instance from given commandline args.
  713. This invokes the pytest bootstrapping code in _pytest.config to create
  714. a new :py:class:`_pytest.core.PluginManager` and call the
  715. pytest_cmdline_parse hook to create a new
  716. :py:class:`_pytest.config.Config` instance.
  717. If :py:attr:`plugins` has been populated they should be plugin modules
  718. to be registered with the PluginManager.
  719. """
  720. args = self._ensure_basetemp(args)
  721. import _pytest.config
  722. config = _pytest.config._prepareconfig(args, self.plugins)
  723. # we don't know what the test will do with this half-setup config
  724. # object and thus we make sure it gets unconfigured properly in any
  725. # case (otherwise capturing could still be active, for example)
  726. self.request.addfinalizer(config._ensure_unconfigure)
  727. return config
  728. def parseconfigure(self, *args):
  729. """Return a new pytest configured Config instance.
  730. This returns a new :py:class:`_pytest.config.Config` instance like
  731. :py:meth:`parseconfig`, but also calls the pytest_configure hook.
  732. """
  733. config = self.parseconfig(*args)
  734. config._do_configure()
  735. self.request.addfinalizer(config._ensure_unconfigure)
  736. return config
  737. def getitem(self, source, funcname="test_func"):
  738. """Return the test item for a test function.
  739. This writes the source to a python file and runs pytest's collection on
  740. the resulting module, returning the test item for the requested
  741. function name.
  742. :param source: the module source
  743. :param funcname: the name of the test function for which to return a
  744. test item
  745. """
  746. items = self.getitems(source)
  747. for item in items:
  748. if item.name == funcname:
  749. return item
  750. assert 0, "%r item not found in module:\n%s\nitems: %s" % (
  751. funcname,
  752. source,
  753. items,
  754. )
  755. def getitems(self, source):
  756. """Return all test items collected from the module.
  757. This writes the source to a python file and runs pytest's collection on
  758. the resulting module, returning all test items contained within.
  759. """
  760. modcol = self.getmodulecol(source)
  761. return self.genitems([modcol])
  762. def getmodulecol(self, source, configargs=(), withinit=False):
  763. """Return the module collection node for ``source``.
  764. This writes ``source`` to a file using :py:meth:`makepyfile` and then
  765. runs the pytest collection on it, returning the collection node for the
  766. test module.
  767. :param source: the source code of the module to collect
  768. :param configargs: any extra arguments to pass to
  769. :py:meth:`parseconfigure`
  770. :param withinit: whether to also write an ``__init__.py`` file to the
  771. same directory to ensure it is a package
  772. """
  773. if isinstance(source, Path):
  774. path = self.tmpdir.join(str(source))
  775. assert not withinit, "not supported for paths"
  776. else:
  777. kw = {self.request.function.__name__: Source(source).strip()}
  778. path = self.makepyfile(**kw)
  779. if withinit:
  780. self.makepyfile(__init__="#")
  781. self.config = config = self.parseconfigure(path, *configargs)
  782. return self.getnode(config, path)
  783. def collect_by_name(self, modcol, name):
  784. """Return the collection node for name from the module collection.
  785. This will search a module collection node for a collection node
  786. matching the given name.
  787. :param modcol: a module collection node; see :py:meth:`getmodulecol`
  788. :param name: the name of the node to return
  789. """
  790. if modcol not in self._mod_collections:
  791. self._mod_collections[modcol] = list(modcol.collect())
  792. for colitem in self._mod_collections[modcol]:
  793. if colitem.name == name:
  794. return colitem
  795. def popen(self, cmdargs, stdout, stderr, **kw):
  796. """Invoke subprocess.Popen.
  797. This calls subprocess.Popen making sure the current working directory
  798. is in the PYTHONPATH.
  799. You probably want to use :py:meth:`run` instead.
  800. """
  801. env = os.environ.copy()
  802. env["PYTHONPATH"] = os.pathsep.join(
  803. filter(None, [os.getcwd(), env.get("PYTHONPATH", "")])
  804. )
  805. kw["env"] = env
  806. popen = subprocess.Popen(
  807. cmdargs, stdin=subprocess.PIPE, stdout=stdout, stderr=stderr, **kw
  808. )
  809. popen.stdin.close()
  810. return popen
  811. def run(self, *cmdargs):
  812. """Run a command with arguments.
  813. Run a process using subprocess.Popen saving the stdout and stderr.
  814. Returns a :py:class:`RunResult`.
  815. """
  816. cmdargs = [
  817. str(arg) if isinstance(arg, py.path.local) else arg for arg in cmdargs
  818. ]
  819. p1 = self.tmpdir.join("stdout")
  820. p2 = self.tmpdir.join("stderr")
  821. print("running:", *cmdargs)
  822. print(" in:", py.path.local())
  823. f1 = codecs.open(str(p1), "w", encoding="utf8")
  824. f2 = codecs.open(str(p2), "w", encoding="utf8")
  825. try:
  826. now = time.time()
  827. popen = self.popen(
  828. cmdargs, stdout=f1, stderr=f2, close_fds=(sys.platform != "win32")
  829. )
  830. ret = popen.wait()
  831. finally:
  832. f1.close()
  833. f2.close()
  834. f1 = codecs.open(str(p1), "r", encoding="utf8")
  835. f2 = codecs.open(str(p2), "r", encoding="utf8")
  836. try:
  837. out = f1.read().splitlines()
  838. err = f2.read().splitlines()
  839. finally:
  840. f1.close()
  841. f2.close()
  842. self._dump_lines(out, sys.stdout)
  843. self._dump_lines(err, sys.stderr)
  844. return RunResult(ret, out, err, time.time() - now)
  845. def _dump_lines(self, lines, fp):
  846. try:
  847. for line in lines:
  848. print(line, file=fp)
  849. except UnicodeEncodeError:
  850. print("couldn't print to %s because of encoding" % (fp,))
  851. def _getpytestargs(self):
  852. return sys.executable, "-mpytest"
  853. def runpython(self, script):
  854. """Run a python script using sys.executable as interpreter.
  855. Returns a :py:class:`RunResult`.
  856. """
  857. return self.run(sys.executable, script)
  858. def runpython_c(self, command):
  859. """Run python -c "command", return a :py:class:`RunResult`."""
  860. return self.run(sys.executable, "-c", command)
  861. def runpytest_subprocess(self, *args, **kwargs):
  862. """Run pytest as a subprocess with given arguments.
  863. Any plugins added to the :py:attr:`plugins` list will added using the
  864. ``-p`` command line option. Additionally ``--basetemp`` is used put
  865. any temporary files and directories in a numbered directory prefixed
  866. with "runpytest-" so they do not conflict with the normal numbered
  867. pytest location for temporary files and directories.
  868. Returns a :py:class:`RunResult`.
  869. """
  870. p = py.path.local.make_numbered_dir(
  871. prefix="runpytest-", keep=None, rootdir=self.tmpdir
  872. )
  873. args = ("--basetemp=%s" % p,) + args
  874. plugins = [x for x in self.plugins if isinstance(x, str)]
  875. if plugins:
  876. args = ("-p", plugins[0]) + args
  877. args = self._getpytestargs() + args
  878. return self.run(*args)
  879. def spawn_pytest(self, string, expect_timeout=10.0):
  880. """Run pytest using pexpect.
  881. This makes sure to use the right pytest and sets up the temporary
  882. directory locations.
  883. The pexpect child is returned.
  884. """
  885. basetemp = self.tmpdir.mkdir("temp-pexpect")
  886. invoke = " ".join(map(str, self._getpytestargs()))
  887. cmd = "%s --basetemp=%s %s" % (invoke, basetemp, string)
  888. return self.spawn(cmd, expect_timeout=expect_timeout)
  889. def spawn(self, cmd, expect_timeout=10.0):
  890. """Run a command using pexpect.
  891. The pexpect child is returned.
  892. """
  893. pexpect = pytest.importorskip("pexpect", "3.0")
  894. if hasattr(sys, "pypy_version_info") and "64" in platform.machine():
  895. pytest.skip("pypy-64 bit not supported")
  896. if sys.platform.startswith("freebsd"):
  897. pytest.xfail("pexpect does not work reliably on freebsd")
  898. logfile = self.tmpdir.join("spawn.out").open("wb")
  899. child = pexpect.spawn(cmd, logfile=logfile)
  900. self.request.addfinalizer(logfile.close)
  901. child.timeout = expect_timeout
  902. return child
  903. def getdecoded(out):
  904. try:
  905. return out.decode("utf-8")
  906. except UnicodeDecodeError:
  907. return "INTERNAL not-utf8-decodeable, truncated string:\n%s" % (
  908. py.io.saferepr(out),
  909. )
  910. class LineComp(object):
  911. def __init__(self):
  912. self.stringio = py.io.TextIO()
  913. def assert_contains_lines(self, lines2):
  914. """Assert that lines2 are contained (linearly) in lines1.
  915. Return a list of extralines found.
  916. """
  917. __tracebackhide__ = True
  918. val = self.stringio.getvalue()
  919. self.stringio.truncate(0)
  920. self.stringio.seek(0)
  921. lines1 = val.split("\n")
  922. return LineMatcher(lines1).fnmatch_lines(lines2)
  923. class LineMatcher(object):
  924. """Flexible matching of text.
  925. This is a convenience class to test large texts like the output of
  926. commands.
  927. The constructor takes a list of lines without their trailing newlines, i.e.
  928. ``text.splitlines()``.
  929. """
  930. def __init__(self, lines):
  931. self.lines = lines
  932. self._log_output = []
  933. def str(self):
  934. """Return the entire original text."""
  935. return "\n".join(self.lines)
  936. def _getlines(self, lines2):
  937. if isinstance(lines2, str):
  938. lines2 = Source(lines2)
  939. if isinstance(lines2, Source):
  940. lines2 = lines2.strip().lines
  941. return lines2
  942. def fnmatch_lines_random(self, lines2):
  943. """Check lines exist in the output using in any order.
  944. Lines are checked using ``fnmatch.fnmatch``. The argument is a list of
  945. lines which have to occur in the output, in any order.
  946. """
  947. self._match_lines_random(lines2, fnmatch)
  948. def re_match_lines_random(self, lines2):
  949. """Check lines exist in the output using ``re.match``, in any order.
  950. The argument is a list of lines which have to occur in the output, in
  951. any order.
  952. """
  953. self._match_lines_random(lines2, lambda name, pat: re.match(pat, name))
  954. def _match_lines_random(self, lines2, match_func):
  955. """Check lines exist in the output.
  956. The argument is a list of lines which have to occur in the output, in
  957. any order. Each line can contain glob whildcards.
  958. """
  959. lines2 = self._getlines(lines2)
  960. for line in lines2:
  961. for x in self.lines:
  962. if line == x or match_func(x, line):
  963. self._log("matched: ", repr(line))
  964. break
  965. else:
  966. self._log("line %r not found in output" % line)
  967. raise ValueError(self._log_text)
  968. def get_lines_after(self, fnline):
  969. """Return all lines following the given line in the text.
  970. The given line can contain glob wildcards.
  971. """
  972. for i, line in enumerate(self.lines):
  973. if fnline == line or fnmatch(line, fnline):
  974. return self.lines[i + 1 :]
  975. raise ValueError("line %r not found in output" % fnline)
  976. def _log(self, *args):
  977. self._log_output.append(" ".join((str(x) for x in args)))
  978. @property
  979. def _log_text(self):
  980. return "\n".join(self._log_output)
  981. def fnmatch_lines(self, lines2):
  982. """Search captured text for matching lines using ``fnmatch.fnmatch``.
  983. The argument is a list of lines which have to match and can use glob
  984. wildcards. If they do not match a pytest.fail() is called. The
  985. matches and non-matches are also printed on stdout.
  986. """
  987. self._match_lines(lines2, fnmatch, "fnmatch")
  988. def re_match_lines(self, lines2):
  989. """Search captured text for matching lines using ``re.match``.
  990. The argument is a list of lines which have to match using ``re.match``.
  991. If they do not match a pytest.fail() is called.
  992. The matches and non-matches are also printed on stdout.
  993. """
  994. self._match_lines(lines2, lambda name, pat: re.match(pat, name), "re.match")
  995. def _match_lines(self, lines2, match_func, match_nickname):
  996. """Underlying implementation of ``fnmatch_lines`` and ``re_match_lines``.
  997. :param list[str] lines2: list of string patterns to match. The actual
  998. format depends on ``match_func``
  999. :param match_func: a callable ``match_func(line, pattern)`` where line
  1000. is the captured line from stdout/stderr and pattern is the matching
  1001. pattern
  1002. :param str match_nickname: the nickname for the match function that
  1003. will be logged to stdout when a match occurs
  1004. """
  1005. lines2 = self._getlines(lines2)
  1006. lines1 = self.lines[:]
  1007. nextline = None
  1008. extralines = []
  1009. __tracebackhide__ = True
  1010. for line in lines2:
  1011. nomatchprinted = False
  1012. while lines1:
  1013. nextline = lines1.pop(0)
  1014. if line == nextline:
  1015. self._log("exact match:", repr(line))
  1016. break
  1017. elif match_func(nextline, line):
  1018. self._log("%s:" % match_nickname, repr(line))
  1019. self._log(" with:", repr(nextline))
  1020. break
  1021. else:
  1022. if not nomatchprinted:
  1023. self._log("nomatch:", repr(line))
  1024. nomatchprinted = True
  1025. self._log(" and:", repr(nextline))
  1026. extralines.append(nextline)
  1027. else:
  1028. self._log("remains unmatched: %r" % (line,))
  1029. pytest.fail(self._log_text)