cacheprovider: add cache.mkdir() as a Path-returning replacement to makedir()

It is not possible to change a return type in a compatible way, so a new
method is added.
This commit is contained in:
Ran Benita 2021-03-14 21:58:37 +02:00
parent 2641761c1c
commit b26d1bb18f
3 changed files with 24 additions and 13 deletions

View File

@ -0,0 +1,2 @@
Added :meth:`cache.mkdir() <pytest.Cache.mkdir>`, which is similar to the existing :meth:`cache.makedir() <pytest.Cache.makedir>`,
but returns a :class:`pathlib.Path` instead of a legacy ``py.path.local``.

View File

@ -60,10 +60,10 @@ class Cache:
_cachedir = attr.ib(type=Path, repr=False) _cachedir = attr.ib(type=Path, repr=False)
_config = attr.ib(type=Config, repr=False) _config = attr.ib(type=Config, repr=False)
# sub-directory under cache-dir for directories created by "makedir" # Sub-directory under cache-dir for directories created by `mkdir()`.
_CACHE_PREFIX_DIRS = "d" _CACHE_PREFIX_DIRS = "d"
# sub-directory under cache-dir for values created by "set" # Sub-directory under cache-dir for values created by `set()`.
_CACHE_PREFIX_VALUES = "v" _CACHE_PREFIX_VALUES = "v"
def __init__( def __init__(
@ -121,13 +121,15 @@ class Cache:
stacklevel=3, stacklevel=3,
) )
def makedir(self, name: str) -> LEGACY_PATH: def mkdir(self, name: str) -> Path:
"""Return a directory path object with the given name. """Return a directory path object with the given name.
If the directory does not yet exist, it will be created. You can use If the directory does not yet exist, it will be created. You can use
it to manage files to e.g. store/retrieve database dumps across test it to manage files to e.g. store/retrieve database dumps across test
sessions. sessions.
.. versionadded:: 6.3
:param name: :param name:
Must be a string not containing a ``/`` separator. Must be a string not containing a ``/`` separator.
Make sure the name contains your plugin or application Make sure the name contains your plugin or application
@ -138,7 +140,14 @@ class Cache:
raise ValueError("name is not allowed to contain path separators") raise ValueError("name is not allowed to contain path separators")
res = self._cachedir.joinpath(self._CACHE_PREFIX_DIRS, path) res = self._cachedir.joinpath(self._CACHE_PREFIX_DIRS, path)
res.mkdir(exist_ok=True, parents=True) res.mkdir(exist_ok=True, parents=True)
return legacy_path(res) return res
def makedir(self, name: str) -> LEGACY_PATH:
"""Return a directory path object with the given name.
Same as :func:`mkdir`, but returns a legacy py path instance.
"""
return legacy_path(self.mkdir(name))
def _getvaluepath(self, key: str) -> Path: def _getvaluepath(self, key: str) -> Path:
return self._cachedir.joinpath(self._CACHE_PREFIX_VALUES, Path(key)) return self._cachedir.joinpath(self._CACHE_PREFIX_VALUES, Path(key))
@ -572,8 +581,8 @@ def cacheshow(config: Config, session: Session) -> int:
contents = sorted(ddir.rglob(glob)) contents = sorted(ddir.rglob(glob))
tw.sep("-", "cache directories for %r" % glob) tw.sep("-", "cache directories for %r" % glob)
for p in contents: for p in contents:
# if p.check(dir=1): # if p.is_dir():
# print("%s/" % p.relto(basedir)) # print("%s/" % p.relative_to(basedir))
if p.is_file(): if p.is_file():
key = str(p.relative_to(basedir)) key = str(p.relative_to(basedir))
tw.line(f"{key} is a file of length {p.stat().st_size:d}") tw.line(f"{key} is a file of length {p.stat().st_size:d}")

View File

@ -14,15 +14,15 @@ pytest_plugins = ("pytester",)
class TestNewAPI: class TestNewAPI:
def test_config_cache_makedir(self, pytester: Pytester) -> None: def test_config_cache_mkdir(self, pytester: Pytester) -> None:
pytester.makeini("[pytest]") pytester.makeini("[pytest]")
config = pytester.parseconfigure() config = pytester.parseconfigure()
assert config.cache is not None assert config.cache is not None
with pytest.raises(ValueError): with pytest.raises(ValueError):
config.cache.makedir("key/name") config.cache.mkdir("key/name")
p = config.cache.makedir("name") p = config.cache.mkdir("name")
assert p.check() assert p.is_dir()
def test_config_cache_dataerror(self, pytester: Pytester) -> None: def test_config_cache_dataerror(self, pytester: Pytester) -> None:
pytester.makeini("[pytest]") pytester.makeini("[pytest]")
@ -217,9 +217,9 @@ def test_cache_show(pytester: Pytester) -> None:
config.cache.set("my/name", [1,2,3]) config.cache.set("my/name", [1,2,3])
config.cache.set("my/hello", "world") config.cache.set("my/hello", "world")
config.cache.set("other/some", {1:2}) config.cache.set("other/some", {1:2})
dp = config.cache.makedir("mydb") dp = config.cache.mkdir("mydb")
dp.ensure("hello") dp.joinpath("hello").touch()
dp.ensure("world") dp.joinpath("world").touch()
""" """
) )
result = pytester.runpytest() result = pytester.runpytest()