Render markdown in gist and project sidebar titles; add content visibility and GIF picker

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-05 17:59:21 +01:00
co-authored by Claude Sonnet 5.5
parent bc11475f29
commit 05d6633204
154 changed files with 6394 additions and 289 deletions
+1
View File
@@ -0,0 +1 @@
# retoor <retoor@molodetz.nl>
+190
View File
@@ -0,0 +1,190 @@
# retoor <retoor@molodetz.nl>
import httpx
import pytest
from tests.conftest import run_async
from devplacepy.services.giphy import client as client_module
from devplacepy.services.giphy.client import (
MAX_LIMIT,
GiphyClient,
GiphyError,
clear_cache,
normalize_gif,
)
from devplacepy.services.giphy.config import GiphyConfig
CONFIG = GiphyConfig(api_key="secret-key", base_url="https://api.giphy.test/v1/gifs", rating="pg")
def _item(gif_id="abc", title=" Happy dance "):
return {
"id": gif_id,
"title": title,
"url": f"https://giphy.test/gifs/{gif_id}",
"images": {
"fixed_width": {"url": "https://m.giphy.test/200.gif", "width": "200", "height": "150", "size": "9"},
"original": {"url": "https://m.giphy.test/o.gif", "width": "480", "height": "360", "size": "99"},
},
}
class _Recorder:
def __init__(self, handler):
self.calls = []
self.handler = handler
def factory(self, **kwargs):
def respond(request):
self.calls.append(request)
return self.handler(request)
return httpx.AsyncClient(transport=httpx.MockTransport(respond))
@pytest.fixture(autouse=True)
def _fresh_cache():
clear_cache()
yield
clear_cache()
def _patch(monkeypatch, handler):
recorder = _Recorder(handler)
monkeypatch.setattr(client_module.stealth, "stealth_async_client", recorder.factory)
return recorder
def test_normalize_gif_picks_preview_and_original():
gif = normalize_gif(_item())
assert gif["id"] == "abc"
assert gif["title"] == "Happy dance"
assert gif["preview"] == {"url": "https://m.giphy.test/200.gif", "width": 200, "height": 150, "size": 9}
assert gif["original"]["url"] == "https://m.giphy.test/o.gif"
def test_normalize_gif_survives_missing_images():
gif = normalize_gif({"id": 7})
assert gif == {"id": "7", "title": "", "url": "", "preview": {}, "original": {}}
def test_normalize_gif_falls_back_when_a_rendition_is_missing():
item = _item()
del item["images"]["fixed_width"]
assert normalize_gif(item)["preview"]["url"] == "https://m.giphy.test/o.gif"
def test_search_sends_key_rating_and_clamped_limit(monkeypatch):
async def body():
recorder = _patch(monkeypatch, lambda request: httpx.Response(200, json={"data": [_item()]}))
gifs = await GiphyClient(CONFIG).search("cat", limit=999)
assert [gif["id"] for gif in gifs] == ["abc"]
request = recorder.calls[0]
assert request.url.path == "/v1/gifs/search"
params = dict(request.url.params)
assert params["api_key"] == "secret-key"
assert params["rating"] == "pg"
assert params["q"] == "cat"
assert params["limit"] == str(MAX_LIMIT)
run_async(body())
def test_limit_has_a_floor_of_one(monkeypatch):
async def body():
recorder = _patch(monkeypatch, lambda request: httpx.Response(200, json={"data": []}))
await GiphyClient(CONFIG).trending(limit=-5)
assert dict(recorder.calls[0].url.params)["limit"] == "1"
run_async(body())
def test_identical_requests_hit_the_upstream_once(monkeypatch):
async def body():
recorder = _patch(monkeypatch, lambda request: httpx.Response(200, json={"data": [_item()]}))
client = GiphyClient(CONFIG)
for _ in range(5):
await client.search("cat")
assert len(recorder.calls) == 1
await client.search("dog")
assert len(recorder.calls) == 2
run_async(body())
def test_cache_is_shared_across_api_keys_but_not_across_ratings(monkeypatch):
async def body():
recorder = _patch(monkeypatch, lambda request: httpx.Response(200, json={"data": []}))
await GiphyClient(CONFIG).search("cat")
await GiphyClient(GiphyConfig("other-key", CONFIG.base_url, "pg")).search("cat")
assert len(recorder.calls) == 1
await GiphyClient(GiphyConfig("secret-key", CONFIG.base_url, "r")).search("cat")
assert len(recorder.calls) == 2
run_async(body())
def test_errors_are_not_cached(monkeypatch):
async def body():
answers = iter([httpx.Response(500, text="boom"), httpx.Response(200, json={"data": []})])
recorder = _patch(monkeypatch, lambda request: next(answers))
client = GiphyClient(CONFIG)
with pytest.raises(GiphyError) as caught:
await client.trending()
assert caught.value.status == 500
assert await client.trending() == []
assert len(recorder.calls) == 2
run_async(body())
def test_transport_failure_becomes_a_giphy_error(monkeypatch):
async def body():
def refuse(request):
raise httpx.ConnectError("no route", request=request)
_patch(monkeypatch, refuse)
with pytest.raises(GiphyError) as caught:
await GiphyClient(CONFIG).trending()
assert caught.value.status == 0
run_async(body())
def test_unconfigured_client_refuses_without_a_request(monkeypatch):
async def body():
recorder = _patch(monkeypatch, lambda request: httpx.Response(200, json={}))
client = GiphyClient(GiphyConfig("", CONFIG.base_url, "pg"))
for call in (client.trending(), client.search("cat"), client.get_gif("abc")):
with pytest.raises(GiphyError) as caught:
await call
assert caught.value.status == 503
assert recorder.calls == []
run_async(body())
def test_get_gif_not_found_and_empty_id(monkeypatch):
async def body():
_patch(monkeypatch, lambda request: httpx.Response(200, json={"data": {}}))
client = GiphyClient(CONFIG)
with pytest.raises(GiphyError) as missing:
await client.get_gif("nope")
assert missing.value.status == 404
with pytest.raises(GiphyError) as empty:
await client.get_gif("")
assert empty.value.status == 400
run_async(body())
def test_get_gif_returns_the_normalized_item(monkeypatch):
async def body():
recorder = _patch(monkeypatch, lambda request: httpx.Response(200, json={"data": _item("xyz")}))
gif = await GiphyClient(CONFIG).get_gif("xyz")
assert gif["id"] == "xyz"
assert recorder.calls[0].url.path == "/v1/gifs/xyz"
run_async(body())
+84
View File
@@ -0,0 +1,84 @@
# retoor <retoor@molodetz.nl>
from devplacepy.services.giphy import limits
from devplacepy.services.giphy.limits import TtlCache, UserRateLimiter
def test_cache_returns_what_was_stored():
cache = TtlCache()
cache.put("a", {"x": 1})
assert cache.get("a") == {"x": 1}
assert cache.get("missing") is None
def test_cache_expires_entries(monkeypatch):
clock = [1000.0]
monkeypatch.setattr(limits.time, "monotonic", lambda: clock[0])
cache = TtlCache(ttl_seconds=10)
cache.put("a", 1)
clock[0] += 9
assert cache.get("a") == 1
clock[0] += 2
assert cache.get("a") is None
assert len(cache) == 0
def test_cache_never_exceeds_its_entry_cap():
cache = TtlCache(max_entries=8)
for index in range(500):
cache.put(index, index)
assert len(cache) <= 8
assert cache.get(499) == 499
assert cache.get(0) is None
def test_cache_evicts_the_least_recently_used():
cache = TtlCache(max_entries=2)
cache.put("a", 1)
cache.put("b", 2)
assert cache.get("a") == 1
cache.put("c", 3)
assert cache.get("b") is None
assert cache.get("a") == 1
def test_limiter_allows_exactly_the_cap_then_refuses():
limiter = UserRateLimiter(max_calls=5, window_seconds=60)
results = [limiter.allow("u1") for _ in range(8)]
assert results == [True] * 5 + [False] * 3
def test_limiter_is_per_user():
limiter = UserRateLimiter(max_calls=1, window_seconds=60)
assert limiter.allow("u1") is True
assert limiter.allow("u1") is False
assert limiter.allow("u2") is True
def test_limiter_window_slides(monkeypatch):
clock = [0.0]
monkeypatch.setattr(limits.time, "monotonic", lambda: clock[0])
limiter = UserRateLimiter(max_calls=2, window_seconds=60)
assert limiter.allow("u") and limiter.allow("u")
assert limiter.allow("u") is False
clock[0] += 61
assert limiter.allow("u") is True
def test_limiter_bounds_the_number_of_tracked_users():
limiter = UserRateLimiter(max_calls=1, window_seconds=60, max_tracked=16)
for index in range(1000):
limiter.allow(f"user-{index}")
assert len(limiter._calls) <= 16
def test_refused_calls_do_not_extend_the_window(monkeypatch):
clock = [0.0]
monkeypatch.setattr(limits.time, "monotonic", lambda: clock[0])
limiter = UserRateLimiter(max_calls=1, window_seconds=60)
assert limiter.allow("u") is True
for _ in range(50):
clock[0] += 1
assert limiter.allow("u") is False
clock[0] += 11
assert limiter.allow("u") is True
+80
View File
@@ -0,0 +1,80 @@
# retoor <retoor@molodetz.nl>
import pytest
from tests.conftest import run_async
from devplacepy.database import set_setting
from devplacepy.services.giphy import runtime
from devplacepy.services.giphy.client import GiphyError
from devplacepy.services.giphy.config import CONFIG_FIELDS, giphy_config
from devplacepy.services.giphy.fake import FakeGiphyClient
from devplacepy.services.giphy.service import GiphyService
@pytest.fixture
def settings(local_db):
yield
for key in ("giphy_api_key", "giphy_base_url", "giphy_rating"):
set_setting(key, "")
runtime.set_client(None)
def test_config_fields_declare_the_secret_key_and_rating_choices():
fields = {field.key: field for field in CONFIG_FIELDS}
assert fields["giphy_api_key"].secret is True
assert fields["giphy_api_key"].default == ""
assert fields["giphy_rating"].options == ["g", "pg", "pg-13", "r"]
assert GiphyService.config_fields is CONFIG_FIELDS
assert GiphyService.default_enabled is False
def test_config_reads_settings_and_applies_defaults(settings):
assert giphy_config().is_configured is False
set_setting("giphy_api_key", "k")
set_setting("giphy_rating", "")
config = giphy_config()
assert config.is_configured is True
assert config.rating == "pg"
assert config.base_url.startswith("https://api.giphy.com")
def test_run_once_is_quiet_without_a_key(settings):
async def body():
service = GiphyService()
runtime.set_client(FakeGiphyClient())
await service.run_once()
run_async(body())
def test_run_once_probes_trending_when_configured(settings):
async def body():
set_setting("giphy_api_key", "k")
calls = []
class Probe(FakeGiphyClient):
async def trending(self, limit=24):
calls.append(limit)
return await super().trending(limit)
runtime.set_client(Probe())
await GiphyService().run_once()
assert calls == [1]
run_async(body())
def test_run_once_survives_an_upstream_failure(settings):
async def body():
set_setting("giphy_api_key", "k")
class Broken(FakeGiphyClient):
async def trending(self, limit=24):
raise GiphyError("down", status=502)
runtime.set_client(Broken())
await GiphyService().run_once()
run_async(body())