cacheprovider.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. """
  2. merged implementation of the cache provider
  3. the name cache was not choosen to ensure pluggy automatically
  4. ignores the external pytest-cache
  5. """
  6. import py
  7. import pytest
  8. import json
  9. from os.path import sep as _sep, altsep as _altsep
  10. class Cache(object):
  11. def __init__(self, config):
  12. self.config = config
  13. self._cachedir = config.rootdir.join(".cache")
  14. self.trace = config.trace.root.get("cache")
  15. if config.getvalue("cacheclear"):
  16. self.trace("clearing cachedir")
  17. if self._cachedir.check():
  18. self._cachedir.remove()
  19. self._cachedir.mkdir()
  20. def makedir(self, name):
  21. """ return a directory path object with the given name. If the
  22. directory does not yet exist, it will be created. You can use it
  23. to manage files likes e. g. store/retrieve database
  24. dumps across test sessions.
  25. :param name: must be a string not containing a ``/`` separator.
  26. Make sure the name contains your plugin or application
  27. identifiers to prevent clashes with other cache users.
  28. """
  29. if _sep in name or _altsep is not None and _altsep in name:
  30. raise ValueError("name is not allowed to contain path separators")
  31. return self._cachedir.ensure_dir("d", name)
  32. def _getvaluepath(self, key):
  33. return self._cachedir.join('v', *key.split('/'))
  34. def get(self, key, default):
  35. """ return cached value for the given key. If no value
  36. was yet cached or the value cannot be read, the specified
  37. default is returned.
  38. :param key: must be a ``/`` separated value. Usually the first
  39. name is the name of your plugin or your application.
  40. :param default: must be provided in case of a cache-miss or
  41. invalid cache values.
  42. """
  43. path = self._getvaluepath(key)
  44. if path.check():
  45. try:
  46. with path.open("r") as f:
  47. return json.load(f)
  48. except ValueError:
  49. self.trace("cache-invalid at %s" % (path,))
  50. return default
  51. def set(self, key, value):
  52. """ save value for the given key.
  53. :param key: must be a ``/`` separated value. Usually the first
  54. name is the name of your plugin or your application.
  55. :param value: must be of any combination of basic
  56. python types, including nested types
  57. like e. g. lists of dictionaries.
  58. """
  59. path = self._getvaluepath(key)
  60. try:
  61. path.dirpath().ensure_dir()
  62. except (py.error.EEXIST, py.error.EACCES):
  63. self.config.warn(
  64. code='I9', message='could not create cache path %s' % (path,)
  65. )
  66. return
  67. try:
  68. f = path.open('w')
  69. except py.error.ENOTDIR:
  70. self.config.warn(
  71. code='I9', message='cache could not write path %s' % (path,))
  72. else:
  73. with f:
  74. self.trace("cache-write %s: %r" % (key, value,))
  75. json.dump(value, f, indent=2, sort_keys=True)
  76. class LFPlugin:
  77. """ Plugin which implements the --lf (run last-failing) option """
  78. def __init__(self, config):
  79. self.config = config
  80. active_keys = 'lf', 'failedfirst'
  81. self.active = any(config.getvalue(key) for key in active_keys)
  82. if self.active:
  83. self.lastfailed = config.cache.get("cache/lastfailed", {})
  84. else:
  85. self.lastfailed = {}
  86. def pytest_report_header(self):
  87. if self.active:
  88. if not self.lastfailed:
  89. mode = "run all (no recorded failures)"
  90. else:
  91. mode = "rerun last %d failures%s" % (
  92. len(self.lastfailed),
  93. " first" if self.config.getvalue("failedfirst") else "")
  94. return "run-last-failure: %s" % mode
  95. def pytest_runtest_logreport(self, report):
  96. if report.failed and "xfail" not in report.keywords:
  97. self.lastfailed[report.nodeid] = True
  98. elif not report.failed:
  99. if report.when == "call":
  100. self.lastfailed.pop(report.nodeid, None)
  101. def pytest_collectreport(self, report):
  102. passed = report.outcome in ('passed', 'skipped')
  103. if passed:
  104. if report.nodeid in self.lastfailed:
  105. self.lastfailed.pop(report.nodeid)
  106. self.lastfailed.update(
  107. (item.nodeid, True)
  108. for item in report.result)
  109. else:
  110. self.lastfailed[report.nodeid] = True
  111. def pytest_collection_modifyitems(self, session, config, items):
  112. if self.active and self.lastfailed:
  113. previously_failed = []
  114. previously_passed = []
  115. for item in items:
  116. if item.nodeid in self.lastfailed:
  117. previously_failed.append(item)
  118. else:
  119. previously_passed.append(item)
  120. if not previously_failed and previously_passed:
  121. # running a subset of all tests with recorded failures outside
  122. # of the set of tests currently executing
  123. pass
  124. elif self.config.getvalue("failedfirst"):
  125. items[:] = previously_failed + previously_passed
  126. else:
  127. items[:] = previously_failed
  128. config.hook.pytest_deselected(items=previously_passed)
  129. def pytest_sessionfinish(self, session):
  130. config = self.config
  131. if config.getvalue("cacheshow") or hasattr(config, "slaveinput"):
  132. return
  133. prev_failed = config.cache.get("cache/lastfailed", None) is not None
  134. if (session.testscollected and prev_failed) or self.lastfailed:
  135. config.cache.set("cache/lastfailed", self.lastfailed)
  136. def pytest_addoption(parser):
  137. group = parser.getgroup("general")
  138. group.addoption(
  139. '--lf', '--last-failed', action='store_true', dest="lf",
  140. help="rerun only the tests that failed "
  141. "at the last run (or all if none failed)")
  142. group.addoption(
  143. '--ff', '--failed-first', action='store_true', dest="failedfirst",
  144. help="run all tests but run the last failures first. "
  145. "This may re-order tests and thus lead to "
  146. "repeated fixture setup/teardown")
  147. group.addoption(
  148. '--cache-show', action='store_true', dest="cacheshow",
  149. help="show cache contents, don't perform collection or tests")
  150. group.addoption(
  151. '--cache-clear', action='store_true', dest="cacheclear",
  152. help="remove all cache contents at start of test run.")
  153. def pytest_cmdline_main(config):
  154. if config.option.cacheshow:
  155. from _pytest.main import wrap_session
  156. return wrap_session(config, cacheshow)
  157. @pytest.hookimpl(tryfirst=True)
  158. def pytest_configure(config):
  159. config.cache = Cache(config)
  160. config.pluginmanager.register(LFPlugin(config), "lfplugin")
  161. @pytest.fixture
  162. def cache(request):
  163. """
  164. Return a cache object that can persist state between testing sessions.
  165. cache.get(key, default)
  166. cache.set(key, value)
  167. Keys must be a ``/`` separated value, where the first part is usually the
  168. name of your plugin or application to avoid clashes with other cache users.
  169. Values can be any object handled by the json stdlib module.
  170. """
  171. return request.config.cache
  172. def pytest_report_header(config):
  173. if config.option.verbose:
  174. relpath = py.path.local().bestrelpath(config.cache._cachedir)
  175. return "cachedir: %s" % relpath
  176. def cacheshow(config, session):
  177. from pprint import pprint
  178. tw = py.io.TerminalWriter()
  179. tw.line("cachedir: " + str(config.cache._cachedir))
  180. if not config.cache._cachedir.check():
  181. tw.line("cache is empty")
  182. return 0
  183. dummy = object()
  184. basedir = config.cache._cachedir
  185. vdir = basedir.join("v")
  186. tw.sep("-", "cache values")
  187. for valpath in vdir.visit(lambda x: x.isfile()):
  188. key = valpath.relto(vdir).replace(valpath.sep, "/")
  189. val = config.cache.get(key, dummy)
  190. if val is dummy:
  191. tw.line("%s contains unreadable content, "
  192. "will be ignored" % key)
  193. else:
  194. tw.line("%s contains:" % key)
  195. stream = py.io.TextIO()
  196. pprint(val, stream=stream)
  197. for line in stream.getvalue().splitlines():
  198. tw.line(" " + line)
  199. ddir = basedir.join("d")
  200. if ddir.isdir() and ddir.listdir():
  201. tw.sep("-", "cache directories")
  202. for p in basedir.join("d").visit():
  203. #if p.check(dir=1):
  204. # print("%s/" % p.relto(basedir))
  205. if p.isfile():
  206. key = p.relto(basedir)
  207. tw.line("%s is a file of length %d" % (
  208. key, p.size()))
  209. return 0