tests.rs 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. // Copyright 2013-2014 Simon Sapin.
  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. use std::char;
  9. use std::u32;
  10. use std::path;
  11. use super::{UrlParser, Url, RelativeSchemeData, NonRelativeSchemeData, Domain};
  12. use super::UrlRelativeSchemeData;
  13. #[test]
  14. fn url_parsing() {
  15. for test in parse_test_data(include_str!("urltestdata.txt")).into_iter() {
  16. let Test {
  17. input: input,
  18. base: base,
  19. scheme: expected_scheme,
  20. username: expected_username,
  21. password: expected_password,
  22. host: expected_host,
  23. port: expected_port,
  24. path: expected_path,
  25. query: expected_query,
  26. fragment: expected_fragment,
  27. expected_failure: expected_failure,
  28. } = test;
  29. let base = match Url::parse(base.as_slice()) {
  30. Ok(base) => base,
  31. Err(message) => panic!("Error parsing base {}: {}", base, message)
  32. };
  33. let url = UrlParser::new().base_url(&base).parse(input.as_slice());
  34. if expected_scheme.is_none() {
  35. if url.is_ok() && !expected_failure {
  36. panic!("Expected a parse error for URL {}", input);
  37. }
  38. continue
  39. }
  40. let Url { scheme, scheme_data, query, fragment, .. } = match url {
  41. Ok(url) => url,
  42. Err(message) => {
  43. if expected_failure {
  44. continue
  45. } else {
  46. panic!("Error parsing URL {}: {}", input, message)
  47. }
  48. }
  49. };
  50. macro_rules! assert_eq {
  51. ($a: expr, $b: expr) => {
  52. {
  53. let a = $a;
  54. let b = $b;
  55. if a != b {
  56. if expected_failure {
  57. continue
  58. } else {
  59. panic!("{} != {}", a, b)
  60. }
  61. }
  62. }
  63. }
  64. }
  65. assert_eq!(Some(scheme), expected_scheme);
  66. match scheme_data {
  67. RelativeSchemeData(UrlRelativeSchemeData {
  68. username, password, host, port, default_port: _, path,
  69. }) => {
  70. assert_eq!(username, expected_username);
  71. assert_eq!(password, expected_password);
  72. let host = host.serialize();
  73. assert_eq!(host, expected_host)
  74. assert_eq!(port, expected_port);
  75. assert_eq!(Some(format!("/{}", path.connect("/"))), expected_path);
  76. },
  77. NonRelativeSchemeData(scheme_data) => {
  78. assert_eq!(Some(scheme_data), expected_path);
  79. assert_eq!(String::new(), expected_username);
  80. assert_eq!(None, expected_password);
  81. assert_eq!(String::new(), expected_host);
  82. assert_eq!(None, expected_port);
  83. },
  84. }
  85. fn opt_prepend(prefix: &str, opt_s: Option<String>) -> Option<String> {
  86. opt_s.map(|s| format!("{}{}", prefix, s))
  87. }
  88. assert_eq!(opt_prepend("?", query), expected_query);
  89. assert_eq!(opt_prepend("#", fragment), expected_fragment);
  90. assert!(!expected_failure, "Unexpected success for {}", input);
  91. }
  92. }
  93. struct Test {
  94. input: String,
  95. base: String,
  96. scheme: Option<String>,
  97. username: String,
  98. password: Option<String>,
  99. host: String,
  100. port: Option<u16>,
  101. path: Option<String>,
  102. query: Option<String>,
  103. fragment: Option<String>,
  104. expected_failure: bool,
  105. }
  106. fn parse_test_data(input: &str) -> Vec<Test> {
  107. let mut tests: Vec<Test> = Vec::new();
  108. for line in input.lines() {
  109. if line == "" || line.starts_with("#") {
  110. continue
  111. }
  112. let mut pieces = line.split(' ').collect::<Vec<&str>>();
  113. let expected_failure = pieces[0] == "XFAIL";
  114. if expected_failure {
  115. pieces.remove(0);
  116. }
  117. let input = unescape(pieces.remove(0).unwrap());
  118. let mut test = Test {
  119. input: input,
  120. base: if pieces.is_empty() || pieces[0] == "" {
  121. tests.last().unwrap().base.clone()
  122. } else {
  123. unescape(pieces.remove(0).unwrap())
  124. },
  125. scheme: None,
  126. username: String::new(),
  127. password: None,
  128. host: String::new(),
  129. port: None,
  130. path: None,
  131. query: None,
  132. fragment: None,
  133. expected_failure: expected_failure,
  134. };
  135. for piece in pieces.into_iter() {
  136. if piece == "" || piece.starts_with("#") {
  137. continue
  138. }
  139. let colon = piece.find(':').unwrap();
  140. let value = unescape(piece.slice_from(colon + 1));
  141. match piece.slice_to(colon) {
  142. "s" => test.scheme = Some(value),
  143. "u" => test.username = value,
  144. "pass" => test.password = Some(value),
  145. "h" => test.host = value,
  146. "port" => test.port = Some(from_str(value.as_slice()).unwrap()),
  147. "p" => test.path = Some(value),
  148. "q" => test.query = Some(value),
  149. "f" => test.fragment = Some(value),
  150. _ => panic!("Invalid token")
  151. }
  152. }
  153. tests.push(test)
  154. }
  155. tests
  156. }
  157. fn unescape(input: &str) -> String {
  158. let mut output = String::new();
  159. let mut chars = input.chars();
  160. loop {
  161. match chars.next() {
  162. None => return output,
  163. Some(c) => output.push(
  164. if c == '\\' {
  165. match chars.next().unwrap() {
  166. '\\' => '\\',
  167. 'n' => '\n',
  168. 'r' => '\r',
  169. 's' => ' ',
  170. 't' => '\t',
  171. 'f' => '\x0C',
  172. 'u' => {
  173. let mut hex = String::new();
  174. hex.push(chars.next().unwrap());
  175. hex.push(chars.next().unwrap());
  176. hex.push(chars.next().unwrap());
  177. hex.push(chars.next().unwrap());
  178. u32::parse_bytes(hex.as_bytes(), 16)
  179. .and_then(char::from_u32).unwrap()
  180. }
  181. _ => panic!("Invalid test data input"),
  182. }
  183. } else {
  184. c
  185. }
  186. )
  187. }
  188. }
  189. }
  190. #[test]
  191. fn file_paths() {
  192. assert_eq!(Url::from_file_path(&path::posix::Path::new("relative")), Err(()));
  193. assert_eq!(Url::from_file_path(&path::posix::Path::new("../relative")), Err(()));
  194. assert_eq!(Url::from_file_path(&path::windows::Path::new("relative")), Err(()));
  195. assert_eq!(Url::from_file_path(&path::windows::Path::new(r"..\relative")), Err(()));
  196. assert_eq!(Url::from_file_path(&path::windows::Path::new(r"\drive-relative")), Err(()));
  197. assert_eq!(Url::from_file_path(&path::windows::Path::new(r"\\ucn\")), Err(()));
  198. let mut url = Url::from_file_path(&path::posix::Path::new("/foo/bar")).unwrap();
  199. assert_eq!(url.host(), Some(&Domain("".to_string())));
  200. assert_eq!(url.path(), Some(["foo".to_string(), "bar".to_string()].as_slice()));
  201. assert!(url.to_file_path() == Ok(path::posix::Path::new("/foo/bar")));
  202. *url.path_mut().unwrap().get_mut(1) = "ba\0r".to_string();
  203. assert!(url.to_file_path::<path::posix::Path>() == Err(()));
  204. *url.path_mut().unwrap().get_mut(1) = "ba%00r".to_string();
  205. assert!(url.to_file_path::<path::posix::Path>() == Err(()));
  206. // Invalid UTF-8
  207. *url.path_mut().unwrap().get_mut(1) = "ba%80r".to_string();
  208. assert!(url.to_file_path() == Ok(path::posix::Path::new(
  209. /* note: byte string, invalid UTF-8 */ b"/foo/ba\x80r")));
  210. let mut url = Url::from_file_path(&path::windows::Path::new(r"C:\foo\bar")).unwrap();
  211. assert_eq!(url.host(), Some(&Domain("".to_string())));
  212. assert_eq!(url.path(), Some(["C:".to_string(), "foo".to_string(), "bar".to_string()].as_slice()));
  213. assert!(url.to_file_path::<path::windows::Path>()
  214. == Ok(path::windows::Path::new(r"C:\foo\bar")));
  215. *url.path_mut().unwrap().get_mut(2) = "ba\0r".to_string();
  216. assert!(url.to_file_path::<path::windows::Path>() == Err(()));
  217. *url.path_mut().unwrap().get_mut(2) = "ba%00r".to_string();
  218. assert!(url.to_file_path::<path::windows::Path>() == Err(()));
  219. // Invalid UTF-8
  220. *url.path_mut().unwrap().get_mut(2) = "ba%80r".to_string();
  221. assert!(url.to_file_path::<path::windows::Path>() == Err(()));
  222. }
  223. #[test]
  224. fn directory_paths() {
  225. assert_eq!(Url::from_directory_path(&path::posix::Path::new("relative")), Err(()));
  226. assert_eq!(Url::from_directory_path(&path::posix::Path::new("../relative")), Err(()));
  227. assert_eq!(Url::from_directory_path(&path::windows::Path::new("relative")), Err(()));
  228. assert_eq!(Url::from_directory_path(&path::windows::Path::new(r"..\relative")), Err(()));
  229. assert_eq!(Url::from_directory_path(&path::windows::Path::new(r"\drive-relative")), Err(()));
  230. assert_eq!(Url::from_directory_path(&path::windows::Path::new(r"\\ucn\")), Err(()));
  231. let url = Url::from_directory_path(&path::posix::Path::new("/foo/bar")).unwrap();
  232. assert_eq!(url.host(), Some(&Domain("".to_string())));
  233. assert_eq!(url.path(), Some(["foo".to_string(), "bar".to_string(), "".to_string()].as_slice()));
  234. let url = Url::from_directory_path(&path::windows::Path::new(r"C:\foo\bar")).unwrap();
  235. assert_eq!(url.host(), Some(&Domain("".to_string())));
  236. assert_eq!(url.path(), Some([
  237. "C:".to_string(), "foo".to_string(), "bar".to_string(), "".to_string()].as_slice()));
  238. }