Files
devplacepy/tests/api/giphy.py
T
2026-11-05 17:59:21 +01:00

249 lines
8.5 KiB
Python

# retoor <retoor@molodetz.nl>
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import pytest
from starlette.testclient import TestClient
from devplacepy.database import get_table, init_db, set_setting
from devplacepy.routers import giphy as giphy_router
from devplacepy.services.giphy import runtime
from devplacepy.services.giphy.fake import FakeGiphyClient
from devplacepy.utils import create_session
JSON = {"Accept": "application/json"}
_seq = [0]
GIF_BYTES = (
b"GIF89a\x01\x00\x01\x00\x80\x00\x00\x00\x00\x00\xff\xff\xff"
b"\x21\xf9\x04\x01\x00\x00\x00\x00\x2c\x00\x00\x00\x00\x01\x00"
b"\x01\x00\x00\x02\x02\x44\x01\x00\x3b"
)
SETTINGS = {
"giphy_api_key": "test-giphy-key",
"giphy_base_url": "https://api.giphy.test/v1/gifs",
"giphy_rating": "pg",
"max_upload_size_mb": "10",
"allowed_file_types": "",
"max_attachments_per_resource": "10",
}
@pytest.fixture(autouse=True)
def _init_db_giphy():
init_db()
yield
@pytest.fixture
def giphy_env():
fake = FakeGiphyClient()
runtime.set_client(fake)
giphy_router.limiter.reset()
for key, value in SETTINGS.items():
set_setting(key, value)
yield fake
runtime.set_client(None)
for key in ("giphy_api_key", "giphy_base_url", "giphy_rating"):
set_setting(key, "")
@pytest.fixture
def remote_gif():
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-Type", "image/gif")
self.send_header("Content-Length", str(len(GIF_BYTES)))
self.end_headers()
self.wfile.write(GIF_BYTES)
def log_message(self, *args):
return
server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
yield f"http://127.0.0.1:{server.server_port}/giphy.gif"
server.shutdown()
server.server_close()
def _user():
_seq[0] += 1
uid = f"giphy-user-{_seq[0]}"
get_table("users").insert(
{
"uid": uid,
"username": f"giphytest{_seq[0]}",
"terms_version": "1",
"role": "member",
"xp": 0,
"level": 1,
"is_active": True,
}
)
return uid
def _client(uid=None):
import devplacepy.main as m
client = TestClient(m.app)
if uid:
client.cookies.set("session", create_session(uid))
return client
def test_status_requires_auth():
response = _client().get("/giphy/status", headers=JSON)
assert response.status_code == 401
def test_status_configured(giphy_env):
response = _client(_user()).get("/giphy/status", headers=JSON)
assert response.status_code == 200, response.text
assert response.json() == {"configured": True}
def test_status_unconfigured():
runtime.set_client(FakeGiphyClient(configured=False))
try:
set_setting("giphy_api_key", "")
client = _client(_user())
assert client.get("/giphy/status", headers=JSON).json() == {"configured": False}
assert client.get("/giphy/trending", headers=JSON).status_code == 503
assert (
client.get("/giphy/search", params={"q": "cat"}, headers=JSON).status_code == 503
)
finally:
runtime.set_client(None)
def test_search_and_trending(giphy_env):
client = _client(_user())
response = client.get("/giphy/trending", headers=JSON)
assert response.status_code == 200, response.text
assert [item["id"] for item in response.json()["results"]] == ["fake1", "fake2"]
response = client.get("/giphy/search", params={"q": "dance"}, headers=JSON)
assert response.status_code == 200, response.text
assert response.json()["query"] == "dance"
assert [item["id"] for item in response.json()["results"]] == ["fake2"]
assert giphy_env.queries == ["dance"]
response = client.get("/giphy/search", params={"q": " "}, headers=JSON)
assert response.status_code == 400
def test_attach(giphy_env, remote_gif, monkeypatch):
import devplacepy.attachments as attachments
import devplacepy.net_guard as net_guard
async def _no_guard(url, **kwargs):
return url
async def _no_host_guard(host):
return host
monkeypatch.setattr(attachments, "_guard_public_url", _no_guard)
monkeypatch.setattr(net_guard, "guard_public_url", _no_guard)
monkeypatch.setattr(net_guard, "guard_public_host", _no_host_guard)
giphy_env.gifs[0]["images"]["original"]["url"] = remote_gif
client = _client(_user())
response = client.post(
"/giphy/attach", json={"gif_id": "fake1", "title": "Fake happy"}, headers=JSON
)
assert response.status_code == 201, response.text
payload = response.json()
assert payload["uid"]
assert payload["mime_type"] == "image/gif"
assert payload["original_filename"] == "Fake happy.gif"
row = get_table("attachments").find_one(uid=payload["uid"])
assert row is not None
response = client.post("/giphy/attach", json={"gif_id": "missing"}, headers=JSON)
assert response.status_code == 404
response = client.post("/giphy/attach", json={"gif_id": ""}, headers=JSON)
assert response.status_code == 422
def test_every_route_requires_a_signed_in_user():
client = _client()
assert client.get("/giphy/search", params={"q": "cat"}, headers=JSON).status_code == 401
assert client.get("/giphy/trending", headers=JSON).status_code == 401
assert client.post("/giphy/attach", json={"gif_id": "fake1"}, headers=JSON).status_code == 401
def test_errors_use_the_shared_error_shape(giphy_env):
client = _client(_user())
response = client.get("/giphy/search", params={"q": " "}, headers=JSON)
assert response.status_code == 400
assert response.json() == {"error": {"status": 400, "message": "q is required"}}
response = client.post("/giphy/attach", json={"gif_id": "missing"}, headers=JSON)
assert response.status_code == 404
assert response.json()["error"]["message"] == "GIF not found"
def test_search_is_rate_limited_per_user(giphy_env):
limiter = giphy_router.limiter
first, second = _client(_user()), _client(_user())
statuses = [first.get("/giphy/trending", headers=JSON).status_code for _ in range(limiter.max_calls + 3)]
assert statuses == [200] * limiter.max_calls + [429] * 3
refused = first.get("/giphy/search", params={"q": "dance"}, headers=JSON)
assert refused.status_code == 429
assert refused.headers["Retry-After"] == str(int(limiter.window_seconds))
assert refused.json()["error"]["status"] == 429
assert second.get("/giphy/trending", headers=JSON).status_code == 200
def test_oversized_limit_is_clamped(giphy_env):
response = _client(_user()).get("/giphy/trending", params={"limit": 100000}, headers=JSON)
assert response.status_code == 200
def test_attach_refuses_when_gifs_are_not_an_allowed_type(giphy_env):
set_setting("allowed_file_types", ".png,.jpg")
try:
response = _client(_user()).post("/giphy/attach", json={"gif_id": "fake1"}, headers=JSON)
assert response.status_code == 415, response.text
finally:
set_setting("allowed_file_types", "")
def test_attach_is_audited_and_the_record_is_the_upload_shape(giphy_env, remote_gif, monkeypatch):
import devplacepy.attachments as attachments
async def _no_guard(url, **kwargs):
return url
monkeypatch.setattr(attachments, "_guard_public_url", _no_guard)
import devplacepy.net_guard as net_guard
monkeypatch.setattr(net_guard, "guard_public_url", _no_guard)
giphy_env.gifs[1]["images"]["original"]["url"] = remote_gif
owner = _user()
response = _client(owner).post("/giphy/attach", json={"gif_id": "fake2"}, headers=JSON)
assert response.status_code == 201, response.text
payload = response.json()
for key in ("uid", "url", "mime_type", "original_filename", "file_size", "is_image", "is_video"):
assert key in payload
assert payload["is_image"] is True
assert payload["url"].endswith(".gif")
event = get_table("audit_log").find_one(event_key="attachment.giphy", target_uid=payload["uid"])
assert event is not None
assert event["actor_uid"] == owner
def test_attach_surfaces_an_unreachable_gif_as_an_error(giphy_env):
giphy_env.gifs[0]["images"]["original"]["url"] = "http://127.0.0.1:9/never.gif"
giphy_env.gifs[0]["images"]["fixed_width"]["url"] = "http://127.0.0.1:9/never.gif"
response = _client(_user()).post("/giphy/attach", json={"gif_id": "fake1"}, headers=JSON)
assert response.status_code in (400, 502)
assert "message" in response.json()["error"]