Debian Codegraph @

debian/missing-sources/url/tests/wpt.rs

raw
1 // Copyright 2013-2014 The rust-url developers.
2 //
3 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6 // option. This file may not be copied, modified, or distributed
7 // except according to those terms.
8
9 //! Data-driven tests imported from web-platform-tests
10
11 use serde_json::Value;
12 use std::collections::HashMap;
13 use std::fmt::Write;
14 #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
15 use std::sync::Mutex;
16 use url::Url;
17
18 // https://rustwasm.github.io/wasm-bindgen/wasm-bindgen-test/usage.html
19 #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
20 use wasm_bindgen_test::{console_log, wasm_bindgen_test, wasm_bindgen_test_configure};
21 #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
22 wasm_bindgen_test_configure!(run_in_browser);
23
24 // wpt has its own test driver, but we shoe-horn this into wasm_bindgen_test
25 // which will discard stdout and stderr. So, we make println! go to
26 // console.log(), so we see failures that do not result in panics.
27
28 #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
29 static PRINT_BUF: Mutex<Option<String>> = Mutex::new(None);
30
31 #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
32 macro_rules! print {
33 ($($arg:tt)*) => {
34 let v = format!($($arg)*);
35 {
36 let mut buf = PRINT_BUF.lock().unwrap();
37 if let Some(buf) = buf.as_mut() {
38 buf.push_str(&v);
39 } else {
40 *buf = Some(v);
41 }
42 }
43 };
44 }
45
46 #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
47 macro_rules! println {
48 () => {
49 let buf = PRINT_BUF.lock().unwrap().take();
50 match buf {
51 Some(buf) => console_log!("{buf}"),
52 None => console_log!(""),
53 }
54 };
55 ($($arg:tt)*) => {
56 let buf = PRINT_BUF.lock().unwrap().take();
57 match buf {
58 Some(buf) => {
59 let v = format!($($arg)*);
60 console_log!("{buf}{v}");
61 },
62 None => console_log!($($arg)*),
63 }
64 }
65 }
66
67 #[derive(Debug, serde_derive::Deserialize)]
68 struct UrlTest {
69 input: String,
70 base: Option<String>,
71 #[serde(flatten)]
72 result: UrlTestResult,
73 }
74
75 #[derive(Debug, serde_derive::Deserialize)]
76 #[serde(untagged)]
77 #[allow(clippy::large_enum_variant)]
78 enum UrlTestResult {
79 Ok(UrlTestOk),
80 Fail(UrlTestFail),
81 }
82
83 #[derive(Debug, serde_derive::Deserialize)]
84 struct UrlTestOk {
85 href: String,
86 protocol: String,
87 username: String,
88 password: String,
89 host: String,
90 hostname: String,
91 port: String,
92 pathname: String,
93 search: String,
94 hash: String,
95 }
96
97 #[derive(Debug, serde_derive::Deserialize)]
98 struct UrlTestFail {
99 failure: bool,
100 }
101
102 #[derive(Debug, serde_derive::Deserialize)]
103 struct SetterTest {
104 href: String,
105 new_value: String,
106 expected: SetterTestExpected,
107 }
108
109 #[derive(Debug, serde_derive::Deserialize)]
110 struct SetterTestExpected {
111 href: Option<String>,
112 protocol: Option<String>,
113 username: Option<String>,
114 password: Option<String>,
115 host: Option<String>,
116 hostname: Option<String>,
117 port: Option<String>,
118 pathname: Option<String>,
119 search: Option<String>,
120 hash: Option<String>,
121 }
122
123 #[cfg_attr(all(target_arch = "wasm32", target_os = "unknown"), wasm_bindgen_test)]
124 fn main() {
125 let mut filter = None;
126 let mut args = std::env::args().skip(1);
127 while filter.is_none() {
128 if let Some(arg) = args.next() {
129 if arg == "--test-threads" {
130 args.next();
131 continue;
132 }
133 filter = Some(arg);
134 } else {
135 break;
136 }
137 }
138
139 let mut expected_failures = include_str!("expected_failures.txt")
140 .lines()
141 .collect::<Vec<_>>();
142
143 let mut errors = vec![];
144
145 // Copied from https://github.com/web-platform-tests/wpt/blob/master/url/
146 let url_json: Vec<Value> = serde_json::from_str(include_str!("urltestdata.json"))
147 .expect("JSON parse error in urltestdata.json");
148 let url_tests = url_json
149 .into_iter()
150 .filter(|val| val.is_object())
151 .map(|val| serde_json::from_value::<UrlTest>(val).expect("parsing failed"))
152 .collect::<Vec<_>>();
153
154 let setter_json: HashMap<String, Value> =
155 serde_json::from_str(include_str!("setters_tests.json"))
156 .expect("JSON parse error in setters_tests.json");
157 let setter_tests = setter_json
158 .into_iter()
159 .filter(|(k, _)| k != "comment")
160 .map(|(k, v)| {
161 let test = serde_json::from_value::<Vec<SetterTest>>(v).expect("parsing failed");
162 (k, test)
163 })
164 .collect::<HashMap<_, _>>();
165
166 for url_test in url_tests {
167 let mut name = format!("<{}>", url_test.input.escape_default());
168 if let Some(base) = &url_test.base {
169 write!(&mut name, " against <{}>", base.escape_default()).unwrap();
170 }
171 if should_skip(&name, filter.as_deref()) {
172 continue;
173 }
174 print!("{name} ... ");
175
176 let res = run_url_test(url_test);
177 report(name, res, &mut errors, &mut expected_failures);
178 }
179
180 for (kind, tests) in setter_tests {
181 for test in tests {
182 let name = format!(
183 "<{}> set {} to <{}>",
184 test.href.escape_default(),
185 kind,
186 test.new_value.escape_default()
187 );
188 if should_skip(&name, filter.as_deref()) {
189 continue;
190 }
191
192 print!("{name} ... ");
193
194 let res = run_setter_test(&kind, test);
195 report(name, res, &mut errors, &mut expected_failures);
196 }
197 }
198
199 println!();
200 println!("====================");
201 println!();
202
203 if !errors.is_empty() {
204 println!("errors:");
205 println!();
206
207 for (name, err) in errors {
208 println!(" name: {name}");
209 println!(" err: {err}");
210 println!();
211 }
212
213 std::process::exit(1);
214 } else {
215 println!("all tests passed");
216 }
217
218 if !expected_failures.is_empty() && filter.is_none() {
219 println!();
220 println!("====================");
221 println!();
222 println!("tests were expected to fail but did not run:");
223 println!();
224
225 for name in expected_failures {
226 println!(" {name}");
227 }
228
229 println!();
230 println!("if these tests were removed, update expected_failures.txt");
231 println!();
232
233 std::process::exit(1);
234 }
235 }
236
237 fn should_skip(name: &str, filter: Option<&str>) -> bool {
238 match filter {
239 Some(filter) => !name.contains(filter),
240 None => false,
241 }
242 }
243
244 fn report(
245 name: String,
246 res: Result<(), String>,
247 errors: &mut Vec<(String, String)>,
248 expected_failures: &mut Vec<&str>,
249 ) {
250 let expected_failure = expected_failures.contains(&&*name);
251 expected_failures.retain(|&s| s != &*name);
252 match res {
253 Ok(()) => {
254 if expected_failure {
255 println!("🟠 (unexpected success)");
256 errors.push((name, "unexpected success".to_string()));
257 } else {
258 println!("✅");
259 }
260 }
261 Err(err) => {
262 if expected_failure {
263 println!("✅ (expected fail)");
264 } else {
265 println!("❌");
266 errors.push((name, err));
267 }
268 }
269 }
270 }
271
272 fn run_url_test(
273 UrlTest {
274 base,
275 input,
276 result,
277 }: UrlTest,
278 ) -> Result<(), String> {
279 let base = match base {
280 Some(base) => {
281 let base = Url::parse(&base).map_err(|e| format!("errored while parsing base: {e}"))?;
282 Some(base)
283 }
284 None => None,
285 };
286
287 let res = Url::options()
288 .base_url(base.as_ref())
289 .parse(&input)
290 .map_err(|e| format!("errored while parsing input: {e}"));
291
292 match result {
293 UrlTestResult::Ok(ok) => check_url_ok(res, ok),
294 UrlTestResult::Fail(fail) => {
295 assert!(fail.failure);
296 if res.is_ok() {
297 return Err("expected failure, but parsed successfully".to_string());
298 }
299
300 Ok(())
301 }
302 }
303 }
304
305 fn check_url_ok(res: Result<Url, String>, ok: UrlTestOk) -> Result<(), String> {
306 let url = match res {
307 Ok(url) => url,
308 Err(err) => {
309 return Err(format!("expected success, but errored: {err:?}"));
310 }
311 };
312
313 let href = url::quirks::href(&url);
314 if href != ok.href {
315 return Err(format!("expected href {:?}, but got {:?}", ok.href, href));
316 }
317
318 let protocol = url::quirks::protocol(&url);
319 if protocol != ok.protocol {
320 return Err(format!(
321 "expected protocol {:?}, but got {:?}",
322 ok.protocol, protocol
323 ));
324 }
325
326 let username = url::quirks::username(&url);
327 if username != ok.username {
328 return Err(format!(
329 "expected username {:?}, but got {:?}",
330 ok.username, username
331 ));
332 }
333
334 let password = url::quirks::password(&url);
335 if password != ok.password {
336 return Err(format!(
337 "expected password {:?}, but got {:?}",
338 ok.password, password
339 ));
340 }
341
342 let host = url::quirks::host(&url);
343 if host != ok.host {
344 return Err(format!("expected host {:?}, but got {:?}", ok.host, host));
345 }
346
347 let hostname = url::quirks::hostname(&url);
348 if hostname != ok.hostname {
349 return Err(format!(
350 "expected hostname {:?}, but got {:?}",
351 ok.hostname, hostname
352 ));
353 }
354
355 let port = url::quirks::port(&url);
356 if port != ok.port {
357 return Err(format!("expected port {:?}, but got {:?}", ok.port, port));
358 }
359
360 let pathname = url::quirks::pathname(&url);
361 if pathname != ok.pathname {
362 return Err(format!(
363 "expected pathname {:?}, but got {:?}",
364 ok.pathname, pathname
365 ));
366 }
367
368 let search = url::quirks::search(&url);
369 if search != ok.search {
370 return Err(format!(
371 "expected search {:?}, but got {:?}",
372 ok.search, search
373 ));
374 }
375
376 let hash = url::quirks::hash(&url);
377 if hash != ok.hash {
378 return Err(format!("expected hash {:?}, but got {:?}", ok.hash, hash));
379 }
380
381 Ok(())
382 }
383
384 fn run_setter_test(
385 kind: &str,
386 SetterTest {
387 href,
388 new_value,
389 expected,
390 }: SetterTest,
391 ) -> Result<(), String> {
392 let mut url = Url::parse(&href).map_err(|e| format!("errored while parsing href: {e}"))?;
393
394 match kind {
395 "protocol" => {
396 url::quirks::set_protocol(&mut url, &new_value).ok();
397 }
398 "username" => {
399 url::quirks::set_username(&mut url, &new_value).ok();
400 }
401 "password" => {
402 url::quirks::set_password(&mut url, &new_value).ok();
403 }
404 "host" => {
405 url::quirks::set_host(&mut url, &new_value).ok();
406 }
407 "hostname" => {
408 url::quirks::set_hostname(&mut url, &new_value).ok();
409 }
410 "port" => {
411 url::quirks::set_port(&mut url, &new_value).ok();
412 }
413 "pathname" => url::quirks::set_pathname(&mut url, &new_value),
414 "search" => url::quirks::set_search(&mut url, &new_value),
415 "hash" => url::quirks::set_hash(&mut url, &new_value),
416 _ => {
417 return Err(format!("unknown setter kind: {kind:?}"));
418 }
419 }
420
421 if let Some(expected_href) = expected.href {
422 let href = url::quirks::href(&url);
423 if href != expected_href {
424 return Err(format!("expected href {expected_href:?}, but got {href:?}"));
425 }
426 }
427
428 if let Some(expected_protocol) = expected.protocol {
429 let protocol = url::quirks::protocol(&url);
430 if protocol != expected_protocol {
431 return Err(format!(
432 "expected protocol {expected_protocol:?}, but got {protocol:?}"
433 ));
434 }
435 }
436
437 if let Some(expected_username) = expected.username {
438 let username = url::quirks::username(&url);
439 if username != expected_username {
440 return Err(format!(
441 "expected username {expected_username:?}, but got {username:?}"
442 ));
443 }
444 }
445
446 if let Some(expected_password) = expected.password {
447 let password = url::quirks::password(&url);
448 if password != expected_password {
449 return Err(format!(
450 "expected password {expected_password:?}, but got {password:?}"
451 ));
452 }
453 }
454
455 if let Some(expected_host) = expected.host {
456 let host = url::quirks::host(&url);
457 if host != expected_host {
458 return Err(format!("expected host {expected_host:?}, but got {host:?}"));
459 }
460 }
461
462 if let Some(expected_hostname) = expected.hostname {
463 let hostname = url::quirks::hostname(&url);
464 if hostname != expected_hostname {
465 return Err(format!(
466 "expected hostname {expected_hostname:?}, but got {hostname:?}"
467 ));
468 }
469 }
470
471 if let Some(expected_port) = expected.port {
472 let port = url::quirks::port(&url);
473 if port != expected_port {
474 return Err(format!("expected port {expected_port:?}, but got {port:?}"));
475 }
476 }
477
478 if let Some(expected_pathname) = expected.pathname {
479 let pathname = url::quirks::pathname(&url);
480 if pathname != expected_pathname {
481 return Err(format!(
482 "expected pathname {expected_pathname:?}, but got {pathname:?}"
483 ));
484 }
485 }
486
487 if let Some(expected_search) = expected.search {
488 let search = url::quirks::search(&url);
489 if search != expected_search {
490 return Err(format!(
491 "expected search {expected_search:?}, but got {search:?}"
492 ));
493 }
494 }
495
496 if let Some(expected_hash) = expected.hash {
497 let hash = url::quirks::hash(&url);
498 if hash != expected_hash {
499 return Err(format!("expected hash {expected_hash:?}, but got {hash:?}"));
500 }
501 }
502
503 Ok(())
504 }