Debian Codegraph @

third_party/rust/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::Deserialize)]
68 struct UrlTest {
69 input: String,
70 base: Option<String>,
71 #[serde(flatten)]
72 result: UrlTestResult,
73 }
74
75 #[derive(Debug, serde::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::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::Deserialize)]
98 struct UrlTestFail {
99 failure: bool,
100 }
101
102 #[derive(Debug, serde::Deserialize)]
103 struct SetterTest {
104 href: String,
105 new_value: String,
106 expected: SetterTestExpected,
107 }
108
109 #[derive(Debug, serde::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 =
282 Url::parse(&base).map_err(|e| format!("errored while parsing base: {}", e))?;
283 Some(base)
284 }
285 None => None,
286 };
287
288 let res = Url::options()
289 .base_url(base.as_ref())
290 .parse(&input)
291 .map_err(|e| format!("errored while parsing input: {}", e));
292
293 match result {
294 UrlTestResult::Ok(ok) => check_url_ok(res, ok),
295 UrlTestResult::Fail(fail) => {
296 assert!(fail.failure);
297 if res.is_ok() {
298 return Err("expected failure, but parsed successfully".to_string());
299 }
300
301 Ok(())
302 }
303 }
304 }
305
306 fn check_url_ok(res: Result<Url, String>, ok: UrlTestOk) -> Result<(), String> {
307 let url = match res {
308 Ok(url) => url,
309 Err(err) => {
310 return Err(format!("expected success, but errored: {:?}", err));
311 }
312 };
313
314 let href = url::quirks::href(&url);
315 if href != ok.href {
316 return Err(format!("expected href {:?}, but got {:?}", ok.href, href));
317 }
318
319 let protocol = url::quirks::protocol(&url);
320 if protocol != ok.protocol {
321 return Err(format!(
322 "expected protocol {:?}, but got {:?}",
323 ok.protocol, protocol
324 ));
325 }
326
327 let username = url::quirks::username(&url);
328 if username != ok.username {
329 return Err(format!(
330 "expected username {:?}, but got {:?}",
331 ok.username, username
332 ));
333 }
334
335 let password = url::quirks::password(&url);
336 if password != ok.password {
337 return Err(format!(
338 "expected password {:?}, but got {:?}",
339 ok.password, password
340 ));
341 }
342
343 let host = url::quirks::host(&url);
344 if host != ok.host {
345 return Err(format!("expected host {:?}, but got {:?}", ok.host, host));
346 }
347
348 let hostname = url::quirks::hostname(&url);
349 if hostname != ok.hostname {
350 return Err(format!(
351 "expected hostname {:?}, but got {:?}",
352 ok.hostname, hostname
353 ));
354 }
355
356 let port = url::quirks::port(&url);
357 if port != ok.port {
358 return Err(format!("expected port {:?}, but got {:?}", ok.port, port));
359 }
360
361 let pathname = url::quirks::pathname(&url);
362 if pathname != ok.pathname {
363 return Err(format!(
364 "expected pathname {:?}, but got {:?}",
365 ok.pathname, pathname
366 ));
367 }
368
369 let search = url::quirks::search(&url);
370 if search != ok.search {
371 return Err(format!(
372 "expected search {:?}, but got {:?}",
373 ok.search, search
374 ));
375 }
376
377 let hash = url::quirks::hash(&url);
378 if hash != ok.hash {
379 return Err(format!("expected hash {:?}, but got {:?}", ok.hash, hash));
380 }
381
382 Ok(())
383 }
384
385 fn run_setter_test(
386 kind: &str,
387 SetterTest {
388 href,
389 new_value,
390 expected,
391 }: SetterTest,
392 ) -> Result<(), String> {
393 let mut url = Url::parse(&href).map_err(|e| format!("errored while parsing href: {}", e))?;
394
395 match kind {
396 "protocol" => {
397 url::quirks::set_protocol(&mut url, &new_value).ok();
398 }
399 "username" => {
400 url::quirks::set_username(&mut url, &new_value).ok();
401 }
402 "password" => {
403 url::quirks::set_password(&mut url, &new_value).ok();
404 }
405 "host" => {
406 url::quirks::set_host(&mut url, &new_value).ok();
407 }
408 "hostname" => {
409 url::quirks::set_hostname(&mut url, &new_value).ok();
410 }
411 "port" => {
412 url::quirks::set_port(&mut url, &new_value).ok();
413 }
414 "pathname" => url::quirks::set_pathname(&mut url, &new_value),
415 "search" => url::quirks::set_search(&mut url, &new_value),
416 "hash" => url::quirks::set_hash(&mut url, &new_value),
417 _ => {
418 return Err(format!("unknown setter kind: {:?}", kind));
419 }
420 }
421
422 if let Some(expected_href) = expected.href {
423 let href = url::quirks::href(&url);
424 if href != expected_href {
425 return Err(format!(
426 "expected href {:?}, but got {:?}",
427 expected_href, href
428 ));
429 }
430 }
431
432 if let Some(expected_protocol) = expected.protocol {
433 let protocol = url::quirks::protocol(&url);
434 if protocol != expected_protocol {
435 return Err(format!(
436 "expected protocol {:?}, but got {:?}",
437 expected_protocol, protocol
438 ));
439 }
440 }
441
442 if let Some(expected_username) = expected.username {
443 let username = url::quirks::username(&url);
444 if username != expected_username {
445 return Err(format!(
446 "expected username {:?}, but got {:?}",
447 expected_username, username
448 ));
449 }
450 }
451
452 if let Some(expected_password) = expected.password {
453 let password = url::quirks::password(&url);
454 if password != expected_password {
455 return Err(format!(
456 "expected password {:?}, but got {:?}",
457 expected_password, password
458 ));
459 }
460 }
461
462 if let Some(expected_host) = expected.host {
463 let host = url::quirks::host(&url);
464 if host != expected_host {
465 return Err(format!(
466 "expected host {:?}, but got {:?}",
467 expected_host, host
468 ));
469 }
470 }
471
472 if let Some(expected_hostname) = expected.hostname {
473 let hostname = url::quirks::hostname(&url);
474 if hostname != expected_hostname {
475 return Err(format!(
476 "expected hostname {:?}, but got {:?}",
477 expected_hostname, hostname
478 ));
479 }
480 }
481
482 if let Some(expected_port) = expected.port {
483 let port = url::quirks::port(&url);
484 if port != expected_port {
485 return Err(format!(
486 "expected port {:?}, but got {:?}",
487 expected_port, port
488 ));
489 }
490 }
491
492 if let Some(expected_pathname) = expected.pathname {
493 let pathname = url::quirks::pathname(&url);
494 if pathname != expected_pathname {
495 return Err(format!(
496 "expected pathname {:?}, but got {:?}",
497 expected_pathname, pathname
498 ));
499 }
500 }
501
502 if let Some(expected_search) = expected.search {
503 let search = url::quirks::search(&url);
504 if search != expected_search {
505 return Err(format!(
506 "expected search {:?}, but got {:?}",
507 expected_search, search
508 ));
509 }
510 }
511
512 if let Some(expected_hash) = expected.hash {
513 let hash = url::quirks::hash(&url);
514 if hash != expected_hash {
515 return Err(format!(
516 "expected hash {:?}, but got {:?}",
517 expected_hash, hash
518 ));
519 }
520 }
521
522 Ok(())
523 }