forked from retoor/devplacepy
191 lines
6.2 KiB
Python
191 lines
6.2 KiB
Python
# 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())
|
|
|