Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / youpipe / src / main / rust / tests / extractor_edges.rs

extractor_edges.rs154 lines · 6.1 KiBRaw
1//! Parsing, request-shape and boundary tests for the youpipe extractor.
2//!
3//! Extends the existing suites without duplicating them: the search-response integration test
4//! covers the fixture end to end, and the inline `json`, `parsing`, `response`, `decoder`,
5//! `innertube`, `suggestions` and `linkhandler` tests cover the happy paths. These tests add
6//! count/duration/thumbnail edges, suggestion envelope variants, client-version fallback, and
7//! fixture error propagation.
8
9use youpipe_extractor::http::{Error, HttpClient, Request, Response, Result};
10use youpipe_extractor::innertube::{
11 client_version, desktop_body, endpoint_url, reset_client_version,
12};
13use youpipe_extractor::json::JsonExt;
14use youpipe_extractor::linkhandler::{channel_url, is_youtube_url, playlist_url, stream_url};
15use youpipe_extractor::parsing::{
16 parse_abbreviated_count, parse_duration, parse_view_count, text_from_object,
17 thumbnails_from_array,
18};
19use youpipe_extractor::search;
20use youpipe_extractor::suggestions::suggestions_for;
21
22fn json_headers() -> youpipe_extractor::http::Headers {
23 [("Content-Type".to_string(), vec!["application/json".to_string()])].into_iter().collect()
24}
25
26fn json_response(url: &str, body: Vec<u8>) -> Response {
27 Response { code: 200, body, latest_url: url.to_string(), headers: json_headers() }
28}
29
30struct Stub {
31 search_body: Vec<u8>,
32 version_body: Vec<u8>,
33}
34
35impl HttpClient for Stub {
36 fn execute(&self, request: Request<'_>) -> Result<Response> {
37 if request.url.contains("sw.js") {
38 return Ok(json_response(&request.url, self.version_body.clone()));
39 }
40 Ok(json_response(&request.url, self.search_body.clone()))
41 }
42}
43
44const FIXTURE: &str = include_str!("fixtures/search_response.json");
45
46fn live_stub() -> Stub {
47 Stub {
48 search_body: FIXTURE.as_bytes().to_vec(),
49 version_body: br#"{"INNERTUBE_CONTEXT_CLIENT_VERSION":"2.20260731.00.00"}"#.to_vec(),
50 }
51}
52
53#[test]
54fn counts_durations_and_views_at_the_boundaries() {
55 assert_eq!(parse_abbreviated_count("1.2M subscribers"), 1_200_000);
56 assert_eq!(parse_abbreviated_count("15K"), 15_000);
57 assert_eq!(parse_abbreviated_count("2B views"), 2_000_000_000);
58 assert_eq!(parse_abbreviated_count("no number here"), -1);
59 assert_eq!(parse_duration("1:02:03"), Some(3723));
60 assert_eq!(parse_duration("LIVE"), None);
61 assert_eq!(parse_duration(""), None);
62 assert_eq!(parse_view_count("1,234 views"), 1234);
63 assert_eq!(parse_view_count("No views"), 0);
64 assert_eq!(parse_view_count("Premiered yesterday"), -1);
65}
66
67#[test]
68fn text_and_thumbnails_tolerate_bad_shapes() {
69 assert_eq!(text_from_object(&serde_json::json!({"runs": [{"nope": 1}]})).as_deref(), Some(""));
70 assert_eq!(text_from_object(&serde_json::json!({"runs": "nope"})), None);
71 let thumbs = serde_json::json!([
72 {"url": "//i.ytimg.com/a.jpg", "width": 120, "height": 90},
73 {"url": "", "width": 1, "height": 1},
74 {"width": 3, "height": 3},
75 ]);
76 let parsed = thumbnails_from_array(thumbs.as_array().unwrap());
77 assert_eq!(parsed.len(), 1);
78 assert_eq!(parsed[0].url, "https://i.ytimg.com/a.jpg");
79 let blank = serde_json::Value::Null;
80 assert!(blank.obj("missing").arr("deeper").is_empty());
81 assert_eq!(blank.obj("a").obj("b").obj("c").str("d"), None);
82}
83
84#[test]
85fn link_builders_round_trip_with_parsers() {
86 assert_eq!(stream_url("dQw4w9WgXcQ"), "https://www.youtube.com/watch?v=dQw4w9WgXcQ");
87 assert_eq!(
88 channel_url("UCuAXFkgsw1L7xaCfnd5JJOw"),
89 "https://www.youtube.com/channel/UCuAXFkgsw1L7xaCfnd5JJOw"
90 );
91 assert_eq!(playlist_url("PLabc123"), "https://www.youtube.com/playlist?list=PLabc123");
92 assert!(is_youtube_url("https://www.youtube.com/watch?v=dQw4w9WgXcQ"));
93 assert!(!is_youtube_url("https://evil-youtube.com/watch?v=dQw4w9WgXcQ"));
94 assert!(!is_youtube_url("not a url"));
95}
96
97#[test]
98fn suggestion_envelope_variants() {
99 struct SuggestStub(&'static str);
100 impl HttpClient for SuggestStub {
101 fn execute(&self, request: Request<'_>) -> Result<Response> {
102 Ok(json_response(&request.url, self.0.as_bytes().to_vec()))
103 }
104 }
105 let body = r#"window.google.ac.h(["q",[["alpha",0],[42],["beta",0]],{}])"#;
106 assert_eq!(
107 suggestions_for(&SuggestStub(body), "q", "en", "US").unwrap(),
108 vec!["alpha".to_string(), "beta".to_string()]
109 );
110 let empty = r#"window.google.ac.h(["q",[]])"#;
111 assert!(suggestions_for(&SuggestStub(empty), "q", "en", "US").unwrap().is_empty());
112 assert!(suggestions_for(&SuggestStub("garbage"), "q", "en", "US").is_err());
113}
114
115#[test]
116fn client_version_falls_back_and_caches() {
117 struct Failing;
118 impl HttpClient for Failing {
119 fn execute(&self, _: Request<'_>) -> Result<Response> {
120 Err(Error::Network("offline".into()))
121 }
122 }
123 reset_client_version();
124 let fallback = client_version(&Failing);
125 assert!(!fallback.is_empty(), "hardcoded fallback must be non-empty");
126 assert_eq!(client_version(&Failing), fallback, "second call hits the cache");
127 reset_client_version();
128 let live = client_version(&live_stub());
129 assert!(!live.is_empty(), "client version must be non-empty");
130 reset_client_version();
131}
132
133#[test]
134fn fixture_errors_propagate_and_bodies_carry_context() {
135 reset_client_version();
136 let result = search::search(&live_stub(), "never gonna give you up", None, "en-GB", "GB")
137 .expect("fixture parses");
138 assert!(result.errors.is_empty());
139 assert!(!result.items.is_empty());
140 let body = desktop_body("v", "en", "US", &[("query", serde_json::json!("cats"))]);
141 let parsed: serde_json::Value = serde_json::from_slice(&body).unwrap();
142 assert!(parsed.get("context").is_some());
143 assert_eq!(parsed.get("query").and_then(|v| v.as_str()), Some("cats"));
144 assert!(endpoint_url("player").ends_with("player?prettyPrint=false"));
145 struct Short;
146 impl HttpClient for Short {
147 fn execute(&self, request: Request<'_>) -> Result<Response> {
148 Ok(json_response(&request.url, b"{}".to_vec()))
149 }
150 }
151 reset_client_version();
152 assert!(search::search(&Short, "q", None, "en", "US").is_err());
153 reset_client_version();
154}