"""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.comments: dict[str, list[dict]] = {} # video_id -> pages self.disabled: set[str] = set() self.channel_names: dict[str, str] = {CHANNEL: "Ma chaîne", OTHER: "Utilisateur A"} 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}, } @staticmethod def thread(author: str, text: str, likes: int = 0, cid: str = "c"): return {"snippet": {"topLevelComment": {"id": cid, "snippet": { "authorChannelId": {"value": author}, "textOriginal": text, "textDisplay": text, "likeCount": likes, }}}} # -- 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 _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"] == "relevance" if vid in self.disabled: return self._error(403, "commentsDisabled") pages = self.comments.get(vid, [[]]) page = int(params.get("pageToken", "0")) body = {"items": pages[page]} if page + 1 < len(pages): body["nextPageToken"] = str(page + 1) return httpx.Response(200, json=body) return self._error(404, "notFound")