Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / youpipe / src / main / rust / tests / coverage_browse.rs
coverage_browse.rs302 lines · 15.0 KiBRaw
| 1 | //! Coverage for browse.rs / browse_part1.rs via public API with a stub transport. |
| 2 | use serde_json::json; |
| 3 | use std::sync::{Mutex, MutexGuard}; |
| 4 | use youpipe_extractor::browse; |
| 5 | use youpipe_extractor::decoder::clear_caches; |
| 6 | use youpipe_extractor::http::{HttpClient, Request, Response, Result}; |
| 7 | use youpipe_extractor::innertube::reset_client_version; |
| 8 | use youpipe_extractor::model::SearchItem; |
| 9 | |
| 10 | static LOCK: Mutex<()> = Mutex::new(()); |
| 11 | fn lock() -> MutexGuard<'static, ()> { |
| 12 | let g = LOCK.lock().unwrap_or_else(|e| e.into_inner()); |
| 13 | reset_client_version(); |
| 14 | clear_caches(); |
| 15 | g |
| 16 | } |
| 17 | fn resp(url: &str, body: String) -> Response { |
| 18 | Response { |
| 19 | code: 200, |
| 20 | body: body.into_bytes(), |
| 21 | latest_url: url.to_string(), |
| 22 | headers: [("Content-Type".into(), vec!["application/json".into()])].into_iter().collect(), |
| 23 | } |
| 24 | } |
| 25 | |
| 26 | #[derive(Default, Clone)] |
| 27 | struct Client { |
| 28 | browse: String, |
| 29 | browse_cont: String, |
| 30 | next: String, |
| 31 | next_cont: String, |
| 32 | } |
| 33 | impl HttpClient for Client { |
| 34 | fn execute(&self, req: Request<'_>) -> Result<Response> { |
| 35 | if req.url.contains("sw.js") { |
| 36 | return Ok(resp( |
| 37 | &req.url, |
| 38 | r#"{"INNERTUBE_CONTEXT_CLIENT_VERSION":"2.20260120.01.00"}"#.into(), |
| 39 | )); |
| 40 | } |
| 41 | if req.url.contains("latest-player") { |
| 42 | return Ok(resp( |
| 43 | &req.url, |
| 44 | r#"{"player":"testplayer","signatureTimestamp":12345}"#.into(), |
| 45 | )); |
| 46 | } |
| 47 | let body = req.body.map(|b| String::from_utf8_lossy(b).into_owned()).unwrap_or_default(); |
| 48 | let is_cont = body.contains("\"continuation\""); |
| 49 | if req.url.contains("youtubei/v1/browse") { |
| 50 | return Ok(resp( |
| 51 | &req.url, |
| 52 | if is_cont { self.browse_cont.clone() } else { self.browse.clone() }, |
| 53 | )); |
| 54 | } |
| 55 | if req.url.contains("youtubei/v1/next") { |
| 56 | return Ok(resp( |
| 57 | &req.url, |
| 58 | if is_cont { self.next_cont.clone() } else { self.next.clone() }, |
| 59 | )); |
| 60 | } |
| 61 | Ok(resp(&req.url, "{}".into())) |
| 62 | } |
| 63 | } |
| 64 | fn vid(id: &str, title: &str) -> serde_json::Value { |
| 65 | json!({"videoRenderer":{"videoId":id,"title":{"simpleText":title},"lengthText":{"simpleText":"4:20"},"viewCountText":{"simpleText":"1,234 views"},"publishedTimeText":{"simpleText":"2 days ago"},"longBylineText":{"runs":[{"text":"Chan","navigationEndpoint":{"browseEndpoint":{"browseId":"UC12345678901234567890"}}}]},"thumbnail":{"thumbnails":[{"url":"//i.ytimg.com/a.jpg","width":120,"height":90}]},"ownerBadges":[{"metadataBadgeRenderer":{"style":"BADGE_STYLE_TYPE_VERIFIED"}}]}}) |
| 66 | } |
| 67 | |
| 68 | fn channel_fixture() -> String { |
| 69 | json!({ |
| 70 | "metadata":{"channelMetadataRenderer":{"externalId":"UC12345678901234567890","title":"My Channel","description":"desc","channelUrl":"https://www.youtube.com/@my","avatar":{"thumbnails":[{"url":"//i.ytimg.com/a.jpg","width":88,"height":88}]}}}, |
| 71 | "header":{"c4TabbedHeaderRenderer":{"title":{"simpleText":"My Channel"},"subscriberCountText":{"simpleText":"1.2M subscribers"},"banner":{"thumbnails":[{"url":"https://i.ytimg.com/b.jpg","width":100,"height":20}]},"badges":[{"metadataBadgeRenderer":{"style":"BADGE_STYLE_TYPE_VERIFIED"}}]}}, |
| 72 | "contents":{"twoColumnBrowseResultsRenderer":{"tabs":[ |
| 73 | {"tabRenderer":{"content":{"richGridRenderer":{"contents":[ |
| 74 | {"richItemRenderer":{"content": vid("aaaaaaaaaaa","Vid1")}}, |
| 75 | {"continuationItemRenderer":{"continuationEndpoint":{"continuationCommand":{"token":"CONT1"}}}} |
| 76 | ]}}}}, |
| 77 | {"tabRenderer":{"content":{"sectionListRenderer":{"contents":[ |
| 78 | {"itemSectionRenderer":{"contents":[ |
| 79 | {"shelfRenderer":{"content":{"verticalListRenderer":{"items":[vid("bbbbbbbbbbb","Vid2")]}}}}, |
| 80 | {"gridRenderer":{"items":[{"gridVideoRenderer":{"videoId":"ccccccccccc","title":{"simpleText":"Vid3"}}}]}}, |
| 81 | vid("ddddddddddd","Vid4"), |
| 82 | {"playlistVideoRenderer":{"videoId":"eeeeeeeeeee","title":{"runs":[{"text":"Vid5"}]},"lengthSeconds":"125"}} |
| 83 | ]}} |
| 84 | ]}}}} |
| 85 | ]}} |
| 86 | }).to_string() |
| 87 | } |
| 88 | |
| 89 | #[test] |
| 90 | fn channel_info_full() { |
| 91 | let _g = lock(); |
| 92 | let c = Client { browse: channel_fixture(), ..Default::default() }; |
| 93 | let info = browse::channel_info(&c, "UC12345678901234567890", "en", "US").unwrap(); |
| 94 | assert_eq!(info.id, "UC12345678901234567890"); |
| 95 | assert_eq!(info.name, "My Channel"); |
| 96 | assert_eq!(info.description.as_deref(), Some("desc")); |
| 97 | assert_eq!(info.subscriber_count, 1_200_000); |
| 98 | assert!(info.verified); |
| 99 | assert_eq!(info.avatars.len(), 1); |
| 100 | assert_eq!(info.banners.len(), 1); |
| 101 | assert_eq!(info.items.len(), 5, "items: {:?}", info.items); |
| 102 | assert_eq!(info.next_page_token.as_deref(), Some("CONT1")); |
| 103 | match &info.items[0] { |
| 104 | SearchItem::Stream(s) => { |
| 105 | assert_eq!(s.duration_seconds, Some(260)); |
| 106 | assert_eq!(s.view_count, 1234); |
| 107 | assert!(s.uploader_verified); |
| 108 | assert_eq!( |
| 109 | s.uploader_url.as_deref(), |
| 110 | Some("https://www.youtube.com/channel/UC12345678901234567890") |
| 111 | ); |
| 112 | } |
| 113 | _ => panic!("stream"), |
| 114 | } |
| 115 | } |
| 116 | |
| 117 | #[test] |
| 118 | fn channel_info_header_fallback_and_url_fallback() { |
| 119 | let _g = lock(); |
| 120 | // No metadata title/channelUrl, header is pageHeaderRenderer only |
| 121 | let fixture = json!({"metadata":{"channelMetadataRenderer":{"externalId":"UC99999999999999999999"}},"header":{"pageHeaderRenderer":{"title":{"simpleText":"Fallback Name"},"subscriberCountText":{"runs":[{"text":"15K subscribers"}]}}},"contents":{"twoColumnBrowseResultsRenderer":{"tabs":[]}}}).to_string(); |
| 122 | let c = Client { browse: fixture, ..Default::default() }; |
| 123 | let info = browse::channel_info(&c, "UC99999999999999999999", "en", "US").unwrap(); |
| 124 | assert_eq!(info.name, "Fallback Name"); |
| 125 | assert_eq!(info.subscriber_count, 15_000); |
| 126 | assert!(info.url.contains("UC99999999999999999999")); |
| 127 | assert!(info.items.is_empty()); |
| 128 | // carousel header variant |
| 129 | let fixture2 = json!({"header":{"carouselHeaderRenderer":{"title":{"simpleText":"Carousel"}}},"contents":{}}).to_string(); |
| 130 | let c2 = Client { browse: fixture2, ..Default::default() }; |
| 131 | let info2 = browse::channel_info(&c2, "@handle", "en", "US").unwrap(); |
| 132 | assert_eq!(info2.name, "Carousel"); |
| 133 | } |
| 134 | |
| 135 | #[test] |
| 136 | fn playlist_info_header_and_fallbacks() { |
| 137 | let _g = lock(); |
| 138 | let fixture = json!({ |
| 139 | "microformat":{"microformatDataRenderer":{"title":"Micro Title","description":"mdesc","thumbnail":{"thumbnails":[{"url":"https://i.ytimg.com/p.jpg","width":10,"height":10}]}}}, |
| 140 | "sidebar":{"playlistSidebarRenderer":{"items":[{"playlistSidebarPrimaryInfoRenderer":{"title":{"simpleText":"Sidebar Title"}}}]}}, |
| 141 | "header":{"playlistHeaderRenderer":{"title":{"runs":[{"text":"Header Title"}]},"numVideosText":{"simpleText":"42 videos"}}}, |
| 142 | "contents":{"twoColumnBrowseResultsRenderer":{"tabs":[{"tabRenderer":{"content":{"sectionListRenderer":{"contents":[{"itemSectionRenderer":{"contents":[{"playlistVideoListRenderer":{"contents":[vid("aaaaaaaaaaa","P1"), vid("bbbbbbbbbbb","P2")]}}]}}]}}}}]}} |
| 143 | }).to_string(); |
| 144 | let c = Client { browse: fixture, ..Default::default() }; |
| 145 | let info = browse::playlist_info(&c, "PLabc", "en", "US").unwrap(); |
| 146 | assert_eq!(info.name, "Header Title"); |
| 147 | assert_eq!(info.stream_count, 42); |
| 148 | assert_eq!(info.items.len(), 2); |
| 149 | assert_eq!(info.url, "https://www.youtube.com/playlist?list=PLabc"); |
| 150 | // sidebar fallback (no header title) |
| 151 | let fixture2 = json!({"microformat":{"microformatDataRenderer":{"title":"Micro Title"}},"sidebar":{"playlistSidebarRenderer":{"items":[{"playlistSidebarPrimaryInfoRenderer":{"title":{"simpleText":"Sidebar Title"}}}]}},"header":{"playlistHeaderRenderer":{}},"contents":{"twoColumnBrowseResultsRenderer":{"tabs":[]}}}).to_string(); |
| 152 | let info2 = browse::playlist_info( |
| 153 | &Client { browse: fixture2, ..Default::default() }, |
| 154 | "PLx", |
| 155 | "en", |
| 156 | "US", |
| 157 | ) |
| 158 | .unwrap(); |
| 159 | assert_eq!(info2.name, "Sidebar Title"); |
| 160 | // microformat fallback |
| 161 | let fixture3 = json!({"microformat":{"microformatDataRenderer":{"title":"Micro Title"}},"contents":{"twoColumnBrowseResultsRenderer":{"tabs":[]}}}).to_string(); |
| 162 | let info3 = browse::playlist_info( |
| 163 | &Client { browse: fixture3, ..Default::default() }, |
| 164 | "PLx", |
| 165 | "en", |
| 166 | "US", |
| 167 | ) |
| 168 | .unwrap(); |
| 169 | assert_eq!(info3.name, "Micro Title"); |
| 170 | assert_eq!(info3.stream_count, -1); |
| 171 | } |
| 172 | |
| 173 | #[test] |
| 174 | fn trending_and_browse_continuation() { |
| 175 | let _g = lock(); |
| 176 | let c = Client { browse: channel_fixture(), ..Default::default() }; |
| 177 | let page = browse::trending(&c, "en", "US").unwrap(); |
| 178 | assert_eq!(page.items.len(), 5); |
| 179 | // continuation: both actions + endpoints, richItem, direct, continuation token (button spelling) |
| 180 | let cont = json!({ |
| 181 | "onResponseReceivedActions":[{"appendContinuationItemsAction":{"continuationItems":[ |
| 182 | {"richItemRenderer":{"content": vid("aaaaaaaaaaa","C1")}}, |
| 183 | vid("bbbbbbbbbbb","C2"), |
| 184 | {"continuationItemRenderer":{"button":{"buttonRenderer":{"command":{"continuationCommand":{"token":"NEXTTOK"}}}}}} |
| 185 | ]}}], |
| 186 | "onResponseReceivedEndpoints":[{"appendContinuationItemsAction":{"continuationItems":[vid("ccccccccccc","C3")]}}] |
| 187 | }).to_string(); |
| 188 | let page2 = browse::browse_continuation( |
| 189 | &Client { browse_cont: cont, ..Default::default() }, |
| 190 | "tok", |
| 191 | "en", |
| 192 | "US", |
| 193 | ) |
| 194 | .unwrap(); |
| 195 | assert_eq!(page2.items.len(), 3); |
| 196 | assert_eq!(page2.next_page_token.as_deref(), Some("NEXTTOK")); |
| 197 | } |
| 198 | |
| 199 | #[test] |
| 200 | fn comments_viewmodel_and_legacy() { |
| 201 | let _g = lock(); |
| 202 | let next_primary = json!({"contents":{"twoColumnWatchNextResults":{"results":{"results":{"contents":[ |
| 203 | {"itemSectionRenderer":{"contents":[{"continuationItemRenderer":{"continuationEndpoint":{"continuationCommand":{"token":"CTOK"}}}}]}} |
| 204 | ]}}}}}).to_string(); |
| 205 | let comments_page = json!({ |
| 206 | "frameworkUpdates":{"entityBatchUpdate":{"mutations":[{"entityKey":"k1","payload":{"commentEntityPayload":{"properties":{"commentId":"c1","content":{"content":"hello vm"},"publishedTime":"3 days ago"},"author":{"displayName":"Alice","channelId":"UC12345678901234567890","isVerified":true,"avatarThumbnailUrl":{"thumbnails":[{"url":"https://i.ytimg.com/av.jpg","width":40,"height":40}]}},"toolbar":{"likeCountNotliked":"1.2K","replyCount":"5"}}}}]}}, |
| 207 | "onResponseReceivedEndpoints":[ |
| 208 | {"reloadContinuationItemsCommand":{"continuationItems":[ |
| 209 | {"commentThreadRenderer":{"commentViewModel":{"commentViewModel":{"commentKey":"k1"}}}}, |
| 210 | {"commentThreadRenderer":{"comment":{"commentRenderer":{"commentId":"c2","contentText":{"simpleText":"legacy hi"},"authorText":{"simpleText":"Bob"},"authorEndpoint":{"browseEndpoint":{"browseId":"UC12345678901234567890"}},"authorThumbnail":{"thumbnails":[{"url":"https://i.ytimg.com/b.jpg","width":40,"height":40}]},"authorCommentBadge":[{"metadataBadgeRenderer":{"style":"BADGE_STYLE_TYPE_VERIFIED"}}],"likeCount":42,"replyCount":3,"publishedTimeText":{"simpleText":"1 day ago"},"pinnedCommentBadge":{"x":1},"actionButtons":{"commentActionButtonsRenderer":{"creatorHeart":{"y":1}}}}}}}, |
| 211 | {"continuationItemRenderer":{"continuationEndpoint":{"continuationCommand":{"token":"NEXTC"}}}} |
| 212 | ]}}, |
| 213 | {"appendContinuationItemsAction":{"continuationItems":[ |
| 214 | {"commentThreadRenderer":{"comment":{"commentRenderer":{"commentId":"c3","contentText":{"runs":[{"text":"second legacy"}]}}}}} |
| 215 | ]}} |
| 216 | ] |
| 217 | }).to_string(); |
| 218 | let c = Client { next: next_primary, next_cont: comments_page.clone(), ..Default::default() }; |
| 219 | let page = browse::comments(&c, "aaaaaaaaaaa", "en", "US").unwrap(); |
| 220 | assert_eq!(page.comments.len(), 3, "{:?}", page.comments); |
| 221 | assert_eq!(page.next_page_token.as_deref(), Some("NEXTC")); |
| 222 | let vm = &page.comments[0]; |
| 223 | assert_eq!(vm.id, "c1"); |
| 224 | assert_eq!(vm.text, "hello vm"); |
| 225 | assert_eq!(vm.author_name.as_deref(), Some("Alice")); |
| 226 | assert!(vm.author_verified); |
| 227 | assert_eq!(vm.like_count, 1200); |
| 228 | assert_eq!(vm.reply_count, 5); |
| 229 | let legacy = &page.comments[1]; |
| 230 | assert_eq!(legacy.id, "c2"); |
| 231 | assert_eq!(legacy.text, "legacy hi"); |
| 232 | assert!(legacy.is_pinned); |
| 233 | assert!(legacy.is_hearted); |
| 234 | assert_eq!(legacy.like_count, 42); |
| 235 | // direct comments_page entry |
| 236 | let direct = browse::comments_page( |
| 237 | &Client { next_cont: comments_page, ..Default::default() }, |
| 238 | "tok", |
| 239 | "en", |
| 240 | "US", |
| 241 | ) |
| 242 | .unwrap(); |
| 243 | assert_eq!(direct.comments.len(), 3); |
| 244 | } |
| 245 | |
| 246 | #[test] |
| 247 | fn comments_disabled_returns_empty() { |
| 248 | let _g = lock(); |
| 249 | let next_primary = json!({"contents":{"twoColumnWatchNextResults":{"results":{"results":{"contents":[{"itemSectionRenderer":{"contents":[{"videoRenderer":{}}]}}]}}}}}).to_string(); |
| 250 | let c = Client { next: next_primary, ..Default::default() }; |
| 251 | let page = browse::comments(&c, "aaaaaaaaaaa", "en", "US").unwrap(); |
| 252 | assert!(page.comments.is_empty()); |
| 253 | // token found via second search path inside itemSection contents |
| 254 | let next2 = json!({"contents":{"twoColumnWatchNextResults":{"results":{"results":{"contents":[ |
| 255 | {"itemSectionRenderer":{"contents":[{"foo":1},{"continuationItemRenderer":{"continuationEndpoint":{"continuationCommand":{"token":"T2"}}}}]}} |
| 256 | ]}}}}}).to_string(); |
| 257 | let cont_page = json!({"onResponseReceivedActions":[{"appendContinuationItemsAction":{"continuationItems":[]}}]}).to_string(); |
| 258 | let page2 = browse::comments( |
| 259 | &Client { next: next2, next_cont: cont_page, ..Default::default() }, |
| 260 | "aaaaaaaaaaa", |
| 261 | "en", |
| 262 | "US", |
| 263 | ) |
| 264 | .unwrap(); |
| 265 | assert!(page2.comments.is_empty()); |
| 266 | } |
| 267 | |
| 268 | #[test] |
| 269 | fn browse_error_paths() { |
| 270 | let _g = lock(); |
| 271 | struct Code(u16, String); |
| 272 | impl HttpClient for Code { |
| 273 | fn execute(&self, req: Request<'_>) -> Result<Response> { |
| 274 | if req.url.contains("sw.js") { |
| 275 | return Ok(resp( |
| 276 | &req.url, |
| 277 | r#"{"INNERTUBE_CONTEXT_CLIENT_VERSION":"2.20260120.01.00"}"#.into(), |
| 278 | )); |
| 279 | } |
| 280 | Ok(Response { |
| 281 | code: self.0, |
| 282 | body: self.1.as_bytes().to_vec(), |
| 283 | latest_url: req.url.clone(), |
| 284 | headers: [("Content-Type".into(), vec!["application/json".into()])] |
| 285 | .into_iter() |
| 286 | .collect(), |
| 287 | }) |
| 288 | } |
| 289 | } |
| 290 | assert!(browse::channel_info(&Code(404, "x".repeat(100)), "UC", "en", "US").is_err()); |
| 291 | assert!(browse::channel_info(&Code(200, "{}".into()), "UC", "en", "US").is_err()); |
| 292 | // malformed list video reported as error, unknown skipped (via trending) |
| 293 | let fixture = json!({"contents":{"twoColumnBrowseResultsRenderer":{"tabs":[{"tabRenderer":{"content":{"richGridRenderer":{"contents":[ |
| 294 | {"richItemRenderer":{"content":{"videoRenderer":{"title":{"simpleText":"no id"}}}}}, |
| 295 | {"richItemRenderer":{"content":{"someFutureRenderer":{"x":1}}}}, |
| 296 | {"richItemRenderer":{"content": vid("aaaaaaaaaaa","Good")}} |
| 297 | ]}}}}]}}}).to_string(); |
| 298 | let page = |
| 299 | browse::trending(&Client { browse: fixture, ..Default::default() }, "en", "US").unwrap(); |
| 300 | assert_eq!(page.items.len(), 1); |
| 301 | assert_eq!(page.errors.len(), 1); |
| 302 | } |