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

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

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