tests.rs 9.9 KB

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