Skip to content

Commit

Permalink
update tests
Browse files Browse the repository at this point in the history
  • Loading branch information
tlambert03 committed Sep 30, 2023
1 parent bc0113e commit 7e01999
Show file tree
Hide file tree
Showing 5 changed files with 44 additions and 23 deletions.
2 changes: 1 addition & 1 deletion src/pyconify/_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ def clear_cache() -> None:
def get_cache_directory(app_name: str = "pyconify") -> Path:
"""Return the pyconify svg cache directory."""
if PYCONIFY_CACHE:
return Path(PYCONIFY_CACHE).expanduser()
return Path(PYCONIFY_CACHE).expanduser().resolve()

if os.name == "posix":
return Path.home() / ".cache" / app_name
Expand Down
23 changes: 12 additions & 11 deletions src/pyconify/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@
import tempfile
import warnings
from contextlib import suppress
from pathlib import Path
from typing import TYPE_CHECKING, Iterable, Literal, overload

import requests

from ._cache import _SVGCache, cache_key, svg_cache

if TYPE_CHECKING:
from pathlib import Path
from typing import Callable, TypeVar

F = TypeVar("F", bound=Callable)
Expand Down Expand Up @@ -115,7 +115,7 @@ def last_modified(*prefixes: str) -> dict[str, int]:
query_params = {"prefixes": ",".join(prefixes)}
resp = requests.get(f"{ROOT}/last-modified", params=query_params)
resp.raise_for_status()
if "lastModified" not in (content := resp.json()):
if "lastModified" not in (content := resp.json()): # pragma: no cover
raise ValueError(
f"Unexpected response from API: {content}. Expected 'lastModified'."
)
Expand Down Expand Up @@ -213,7 +213,7 @@ def _svg_path(svg_cache_key: str) -> Path | None:
if isinstance(cache, _SVGCache):
if (path := cache.path_for(svg_cache_key)) and path.is_file():
return path
return None
return None # pragma: no cover


@lru_cache(maxsize=None)
Expand All @@ -225,18 +225,19 @@ def svg_path(
flip: Literal["horizontal", "vertical", "horizontal,vertical"] | None = None,
rotate: Rotation | None = None,
box: bool | None = None,
dir: str | None = None,
) -> str:
dir: str | Path | None = None,
) -> Path:
"""Similar to `svg` but returns a path to SVG file for `key`.
Arguments are the same as for `pyconfify.api.svg` except for `dir` which is the
directory to save the SVG file to (it will be passed to `tempfile.mkstemp`).
"""
# first look for SVG file in cache
*_, svg_cache_key = _svg_keys(key, locals())
if path := _svg_path(svg_cache_key):
# if it exists return that string
return str(path)
if dir is None:
*_, svg_cache_key = _svg_keys(key, locals())
if path := _svg_path(svg_cache_key):
# if it exists return that string
return path

# otherwise, we need to download it and save it to a temporary file
svg_bytes = svg(
Expand All @@ -245,7 +246,7 @@ def svg_path(

# make a temporary file
file_prefix = f"pyconify_{'-'.join(key)}".replace(":", "-")
fd, tmp_name = tempfile.mkstemp(prefix=file_prefix, suffix=".svg", dir=dir)
fd, tmp_name = tempfile.mkstemp(prefix=file_prefix, suffix=".svg", dir=str(dir))
with os.fdopen(fd, "wb") as f:
f.write(svg_bytes)

Expand All @@ -255,7 +256,7 @@ def _remove_tmp_svg() -> None:
with suppress(FileNotFoundError): # pragma: no cover
os.remove(tmp_name)

return tmp_name
return Path(tmp_name)


@lru_cache(maxsize=None)
Expand Down
19 changes: 13 additions & 6 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
# @pytest.fixture(autouse=True, scope="session")
# def no_cache() -> Iterator[None]:
# TEST_CACHE: dict = {}
# with patch.object(api, "svg_cache", lambda: TEST_CACHE):
# yield
# assert TEST_CACHE
from typing import Iterator
from unittest.mock import patch

import pytest
from pyconify import _cache, api


@pytest.fixture(autouse=True, scope="session")
def no_cache(tmp_path_factory: pytest.TempPathFactory) -> Iterator[None]:
tmp = tmp_path_factory.mktemp("pyconify")
TEST_CACHE = _cache._SVGCache(directory=tmp)
with patch.object(api, "svg_cache", lambda: TEST_CACHE):
yield
5 changes: 5 additions & 0 deletions tests/test_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,8 @@ def test_cache(tmp_path: Path) -> None:

with pytest.raises(KeyError):
cache["not a key"]


def test_cache_dir(monkeypatch):
monkeypatch.setattr(_cache, "PYCONIFY_CACHE", "/some/path")
assert get_cache_directory() == Path("/some/path")
18 changes: 13 additions & 5 deletions tests/test_pyconify.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from pathlib import Path

import pyconify
import pytest

Expand Down Expand Up @@ -36,11 +38,17 @@ def test_svg() -> None:
pyconify.svg("not", "found")


def test_tmp_svg() -> None:
result = pyconify.svg_path("bi", "alarm", rotate=90, box=True)
assert isinstance(result, str)
with open(result, "rb") as f:
assert f.read() == pyconify.svg("bi", "alarm", rotate=90, box=True)
def test_tmp_svg(tmp_path) -> None:
result1 = pyconify.svg_path("bi", "alarm", rotate=90, box=True)
assert isinstance(result1, Path)
assert result1.read_bytes() == pyconify.svg("bi", "alarm", rotate=90, box=True)

# this one shouldn't be in the cache at this point
result2 = pyconify.svg_path("bi", "alarm", rotate=90, box=True, dir=tmp_path)
assert isinstance(result2, Path)
assert result2.parent == tmp_path
assert result2 != result1
assert result2.read_bytes() == pyconify.svg("bi", "alarm", rotate=90, box=True)


def test_css() -> None:
Expand Down

0 comments on commit 7e01999

Please sign in to comment.