104 lines
5.2 KiB
Python
104 lines
5.2 KiB
Python
"""Faux serveur API YouTube (httpx.MockTransport) pour les tests."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
|
|
import httpx
|
|
|
|
CHANNEL = "UC" + "a" * 22
|
|
OTHER = "UC" + "b" * 22
|
|
|
|
|
|
class FakeYouTube:
|
|
def __init__(self):
|
|
self.playlist: dict[str, list[dict]] = {}
|
|
self.videos: dict[str, dict] = {}
|
|
self.threads: dict[str, list[dict]] = {} # video_id -> fils, du plus récent au plus ancien
|
|
self.replies: dict[str, list[dict]] = {} # fil -> toutes ses réponses
|
|
self.page_size = 100 # fils (ou réponses) par page
|
|
self.disabled: set[str] = set()
|
|
self.channel_names: dict[str, str] = {CHANNEL: "Ma chaîne", OTHER: "Autre chaîne"}
|
|
self.quota_exceeded = False
|
|
self.calls: list[tuple[str, dict]] = []
|
|
|
|
# -- construction des données --------------------------------------
|
|
def add_short(self, vid: str, published: str, title: str = "Short", views=1000, likes=50, comments=10,
|
|
duration="PT45S", channel=CHANNEL, listed=True):
|
|
if listed:
|
|
self.playlist.setdefault("UUSH" + channel[2:], []).insert(0, {
|
|
"snippet": {"title": title, "channelId": channel, "videoOwnerChannelId": channel},
|
|
"contentDetails": {"videoId": vid, "videoPublishedAt": published},
|
|
})
|
|
stats = {"viewCount": str(views), "commentCount": str(comments)}
|
|
if likes is not None:
|
|
stats["likeCount"] = str(likes)
|
|
self.videos[vid] = {
|
|
"id": vid,
|
|
"snippet": {"title": title, "channelId": channel, "publishedAt": published},
|
|
"statistics": stats,
|
|
"contentDetails": {"duration": duration},
|
|
}
|
|
|
|
def add_comment(self, vid: str, cid: str, text: str, published: str, replies=()):
|
|
"""Ajoute un fil en tête (le plus récent) ; replies : [(id, texte, date), ...]."""
|
|
reply_items = [{"id": f"{cid}.{rid}", "snippet": {
|
|
"parentId": cid, "textOriginal": t, "textDisplay": t, "publishedAt": p}} for rid, t, p in replies]
|
|
self.replies[cid] = reply_items
|
|
self.threads.setdefault(vid, []).insert(0, {"id": cid, "snippet": {
|
|
"topLevelComment": {"id": cid, "snippet": {"textOriginal": text, "textDisplay": text,
|
|
"publishedAt": published}},
|
|
"totalReplyCount": len(reply_items)}})
|
|
|
|
# -- transport -------------------------------------------------------
|
|
def transport(self) -> httpx.MockTransport:
|
|
return httpx.MockTransport(self._handle)
|
|
|
|
def _error(self, status: int, reason: str):
|
|
body = {"error": {"code": status, "message": reason, "errors": [{"reason": reason}]}}
|
|
return httpx.Response(status, content=json.dumps(body), headers={"content-type": "application/json"})
|
|
|
|
def _page(self, items: list, params: dict) -> dict:
|
|
"""Une page ; le jeton désigne le premier élément de la page suivante (comme un
|
|
curseur : un commentaire ajouté en tête ne décale pas la suite)."""
|
|
size = min(self.page_size, int(params["maxResults"]))
|
|
token = params.get("pageToken")
|
|
start = next(i for i, item in enumerate(items) if item["id"] == token) if token else 0
|
|
body = {"items": items[start:start + size]}
|
|
if start + size < len(items):
|
|
body["nextPageToken"] = items[start + size]["id"]
|
|
return body
|
|
|
|
def _handle(self, request: httpx.Request) -> httpx.Response:
|
|
params = dict(request.url.params)
|
|
path = request.url.path.rsplit("/", 1)[-1]
|
|
self.calls.append((path, params))
|
|
assert params.get("key") == "test-key"
|
|
if self.quota_exceeded:
|
|
return self._error(403, "quotaExceeded")
|
|
if path == "playlistItems":
|
|
items = self.playlist.get(params["playlistId"])
|
|
if items is None:
|
|
return self._error(404, "playlistNotFound")
|
|
return httpx.Response(200, json={"items": items[: int(params["maxResults"])]})
|
|
if path == "channels":
|
|
ids = params["id"].split(",")
|
|
items = [{"id": i, "snippet": {"title": self.channel_names[i]}} for i in ids if i in self.channel_names]
|
|
return httpx.Response(200, json={"items": items})
|
|
if path == "videos":
|
|
ids = params["id"].split(",")
|
|
return httpx.Response(200, json={"items": [self.videos[i] for i in ids if i in self.videos]})
|
|
if path == "commentThreads":
|
|
vid = params["videoId"]
|
|
assert params["order"] == "time" and params["textFormat"] == "plainText"
|
|
if vid in self.disabled:
|
|
return self._error(403, "commentsDisabled")
|
|
items = self.threads.get(vid, [])
|
|
body = self._page(items, params)
|
|
if "replies" in params["part"].split(","):
|
|
body["items"] = [{**t, "replies": {"comments": self.replies.get(t["id"], [])[:5]}}
|
|
if self.replies.get(t["id"]) else t for t in body["items"]]
|
|
return httpx.Response(200, json=body)
|
|
if path == "comments":
|
|
return httpx.Response(200, json=self._page(self.replies.get(params["parentId"], []), params))
|
|
return self._error(404, "notFound")
|