data.rs 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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. //! Data-driven tests
  9. use rustc_test as test;
  10. use serde_json::Value;
  11. use std::str::FromStr;
  12. use url::{quirks, Url};
  13. fn check_invariants(url: &Url) {
  14. url.check_invariants().unwrap();
  15. #[cfg(feature = "serde")]
  16. {
  17. let bytes = serde_json::to_vec(url).unwrap();
  18. let new_url: Url = serde_json::from_slice(&bytes).unwrap();
  19. assert_eq!(url, &new_url);
  20. }
  21. }
  22. fn run_parsing(input: &str, base: &str, expected: Result<ExpectedAttributes, ()>) {
  23. let base = match Url::parse(&base) {
  24. Ok(base) => base,
  25. Err(_) if expected.is_err() => return,
  26. Err(message) => panic!("Error parsing base {:?}: {}", base, message),
  27. };
  28. let (url, expected) = match (base.join(&input), expected) {
  29. (Ok(url), Ok(expected)) => (url, expected),
  30. (Err(_), Err(())) => return,
  31. (Err(message), Ok(_)) => panic!("Error parsing URL {:?}: {}", input, message),
  32. (Ok(_), Err(())) => panic!("Expected a parse error for URL {:?}", input),
  33. };
  34. check_invariants(&url);
  35. macro_rules! assert_eq {
  36. ($expected: expr, $got: expr) => {{
  37. let expected = $expected;
  38. let got = $got;
  39. assert!(
  40. expected == got,
  41. "\n{:?}\n!= {}\n{:?}\nfor URL {:?}\n",
  42. got,
  43. stringify!($expected),
  44. expected,
  45. url
  46. );
  47. }};
  48. }
  49. macro_rules! assert_attributes {
  50. ($($attr: ident)+) => {
  51. {
  52. $(
  53. assert_eq!(expected.$attr, quirks::$attr(&url));
  54. )+
  55. }
  56. }
  57. }
  58. assert_attributes!(href protocol username password host hostname port pathname search hash);
  59. if let Some(expected_origin) = expected.origin {
  60. assert_eq!(expected_origin, quirks::origin(&url));
  61. }
  62. }
  63. struct ExpectedAttributes {
  64. href: String,
  65. origin: Option<String>,
  66. protocol: String,
  67. username: String,
  68. password: String,
  69. host: String,
  70. hostname: String,
  71. port: String,
  72. pathname: String,
  73. search: String,
  74. hash: String,
  75. }
  76. trait JsonExt {
  77. fn take_key(&mut self, key: &str) -> Option<Value>;
  78. fn string(self) -> String;
  79. fn take_string(&mut self, key: &str) -> String;
  80. }
  81. impl JsonExt for Value {
  82. fn take_key(&mut self, key: &str) -> Option<Value> {
  83. self.as_object_mut().unwrap().remove(key)
  84. }
  85. fn string(self) -> String {
  86. if let Value::String(s) = self {
  87. s
  88. } else {
  89. panic!("Not a Value::String")
  90. }
  91. }
  92. fn take_string(&mut self, key: &str) -> String {
  93. self.take_key(key).unwrap().string()
  94. }
  95. }
  96. fn collect_parsing<F: FnMut(String, test::TestFn)>(add_test: &mut F) {
  97. // Copied form https://github.com/w3c/web-platform-tests/blob/master/url/
  98. let mut json = Value::from_str(include_str!("urltestdata.json"))
  99. .expect("JSON parse error in urltestdata.json");
  100. for entry in json.as_array_mut().unwrap() {
  101. if entry.is_string() {
  102. continue; // ignore comments
  103. }
  104. let base = entry.take_string("base");
  105. let input = entry.take_string("input");
  106. let expected = if entry.take_key("failure").is_some() {
  107. Err(())
  108. } else {
  109. Ok(ExpectedAttributes {
  110. href: entry.take_string("href"),
  111. origin: entry.take_key("origin").map(|s| s.string()),
  112. protocol: entry.take_string("protocol"),
  113. username: entry.take_string("username"),
  114. password: entry.take_string("password"),
  115. host: entry.take_string("host"),
  116. hostname: entry.take_string("hostname"),
  117. port: entry.take_string("port"),
  118. pathname: entry.take_string("pathname"),
  119. search: entry.take_string("search"),
  120. hash: entry.take_string("hash"),
  121. })
  122. };
  123. add_test(
  124. format!("{:?} @ base {:?}", input, base),
  125. test::TestFn::dyn_test_fn(move || run_parsing(&input, &base, expected)),
  126. );
  127. }
  128. }
  129. fn collect_setters<F>(add_test: &mut F)
  130. where
  131. F: FnMut(String, test::TestFn),
  132. {
  133. let mut json = Value::from_str(include_str!("setters_tests.json"))
  134. .expect("JSON parse error in setters_tests.json");
  135. macro_rules! setter {
  136. ($attr: expr, $setter: ident) => {{
  137. let mut tests = json.take_key($attr).unwrap();
  138. for mut test in tests.as_array_mut().unwrap().drain(..) {
  139. let comment = test.take_key("comment")
  140. .map(|s| s.string())
  141. .unwrap_or(String::new());
  142. let href = test.take_string("href");
  143. let new_value = test.take_string("new_value");
  144. let name = format!("{:?}.{} = {:?} {}", href, $attr, new_value, comment);
  145. let mut expected = test.take_key("expected").unwrap();
  146. add_test(name, test::TestFn::dyn_test_fn(move || {
  147. let mut url = Url::parse(&href).unwrap();
  148. check_invariants(&url);
  149. let _ = quirks::$setter(&mut url, &new_value);
  150. assert_attributes!(url, expected,
  151. href protocol username password host hostname port pathname search hash);
  152. check_invariants(&url);
  153. }))
  154. }
  155. }}
  156. }
  157. macro_rules! assert_attributes {
  158. ($url: expr, $expected: expr, $($attr: ident)+) => {
  159. $(
  160. if let Some(value) = $expected.take_key(stringify!($attr)) {
  161. assert_eq!(quirks::$attr(&$url), value.string())
  162. }
  163. )+
  164. }
  165. }
  166. setter!("protocol", set_protocol);
  167. setter!("username", set_username);
  168. setter!("password", set_password);
  169. setter!("hostname", set_hostname);
  170. setter!("host", set_host);
  171. setter!("port", set_port);
  172. setter!("pathname", set_pathname);
  173. setter!("search", set_search);
  174. setter!("hash", set_hash);
  175. }
  176. fn main() {
  177. let mut tests = Vec::new();
  178. {
  179. let mut add_one = |name: String, run: test::TestFn| {
  180. tests.push(test::TestDescAndFn {
  181. desc: test::TestDesc::new(test::DynTestName(name)),
  182. testfn: run,
  183. })
  184. };
  185. collect_parsing(&mut add_one);
  186. collect_setters(&mut add_one);
  187. }
  188. test::test_main(&std::env::args().collect::<Vec<_>>(), tests)
  189. }