data.rs 6.8 KB

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