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