unit.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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. //! Unit tests
  9. extern crate url;
  10. use std::borrow::Cow;
  11. use std::net::{Ipv4Addr, Ipv6Addr};
  12. use std::path::{Path, PathBuf};
  13. use url::{Host, Url, form_urlencoded};
  14. #[test]
  15. fn size() {
  16. use std::mem::size_of;
  17. assert_eq!(size_of::<Url>(), size_of::<Option<Url>>());
  18. }
  19. macro_rules! assert_from_file_path {
  20. ($path: expr) => { assert_from_file_path!($path, $path) };
  21. ($path: expr, $url_path: expr) => {{
  22. let url = Url::from_file_path(Path::new($path)).unwrap();
  23. assert_eq!(url.host(), None);
  24. assert_eq!(url.path(), $url_path);
  25. assert_eq!(url.to_file_path(), Ok(PathBuf::from($path)));
  26. }};
  27. }
  28. #[test]
  29. fn new_file_paths() {
  30. if cfg!(unix) {
  31. assert_eq!(Url::from_file_path(Path::new("relative")), Err(()));
  32. assert_eq!(Url::from_file_path(Path::new("../relative")), Err(()));
  33. }
  34. if cfg!(windows) {
  35. assert_eq!(Url::from_file_path(Path::new("relative")), Err(()));
  36. assert_eq!(Url::from_file_path(Path::new(r"..\relative")), Err(()));
  37. assert_eq!(Url::from_file_path(Path::new(r"\drive-relative")), Err(()));
  38. assert_eq!(Url::from_file_path(Path::new(r"\\ucn\")), Err(()));
  39. }
  40. if cfg!(unix) {
  41. assert_from_file_path!("/foo/bar");
  42. assert_from_file_path!("/foo/ba\0r", "/foo/ba%00r");
  43. assert_from_file_path!("/foo/ba%00r", "/foo/ba%2500r");
  44. }
  45. }
  46. #[test]
  47. #[cfg(unix)]
  48. fn new_path_bad_utf8() {
  49. use std::ffi::OsStr;
  50. use std::os::unix::prelude::*;
  51. let url = Url::from_file_path(Path::new(OsStr::from_bytes(b"/foo/ba\x80r"))).unwrap();
  52. let os_str = OsStr::from_bytes(b"/foo/ba\x80r");
  53. assert_eq!(url.to_file_path(), Ok(PathBuf::from(os_str)));
  54. }
  55. #[test]
  56. fn new_path_windows_fun() {
  57. if cfg!(windows) {
  58. assert_from_file_path!(r"C:\foo\bar", "/C:/foo/bar");
  59. assert_from_file_path!("C:\\foo\\ba\0r", "/C:/foo/ba%00r");
  60. // Invalid UTF-8
  61. assert!(Url::parse("file:///C:/foo/ba%80r").unwrap().to_file_path().is_err());
  62. // test windows canonicalized path
  63. let path = PathBuf::from(r"\\?\C:\foo\bar");
  64. assert!(Url::from_file_path(path).is_ok());
  65. // Percent-encoded drive letter
  66. let url = Url::parse("file:///C%3A/foo/bar").unwrap();
  67. assert_eq!(url.to_file_path(), Ok(PathBuf::from(r"C:\foo\bar")));
  68. }
  69. }
  70. #[test]
  71. fn new_directory_paths() {
  72. if cfg!(unix) {
  73. assert_eq!(Url::from_directory_path(Path::new("relative")), Err(()));
  74. assert_eq!(Url::from_directory_path(Path::new("../relative")), Err(()));
  75. let url = Url::from_directory_path(Path::new("/foo/bar")).unwrap();
  76. assert_eq!(url.host(), None);
  77. assert_eq!(url.path(), "/foo/bar/");
  78. }
  79. if cfg!(windows) {
  80. assert_eq!(Url::from_directory_path(Path::new("relative")), Err(()));
  81. assert_eq!(Url::from_directory_path(Path::new(r"..\relative")), Err(()));
  82. assert_eq!(Url::from_directory_path(Path::new(r"\drive-relative")), Err(()));
  83. assert_eq!(Url::from_directory_path(Path::new(r"\\ucn\")), Err(()));
  84. let url = Url::from_directory_path(Path::new(r"C:\foo\bar")).unwrap();
  85. assert_eq!(url.host(), None);
  86. assert_eq!(url.path(), "/C:/foo/bar/");
  87. }
  88. }
  89. #[test]
  90. fn from_str() {
  91. assert!("http://testing.com/this".parse::<Url>().is_ok());
  92. }
  93. #[test]
  94. fn issue_124() {
  95. let url: Url = "file:a".parse().unwrap();
  96. assert_eq!(url.path(), "/a");
  97. let url: Url = "file:...".parse().unwrap();
  98. assert_eq!(url.path(), "/...");
  99. let url: Url = "file:..".parse().unwrap();
  100. assert_eq!(url.path(), "/");
  101. }
  102. #[test]
  103. fn test_equality() {
  104. use std::hash::{Hash, Hasher, SipHasher};
  105. fn check_eq(a: &Url, b: &Url) {
  106. assert_eq!(a, b);
  107. let mut h1 = SipHasher::new();
  108. a.hash(&mut h1);
  109. let mut h2 = SipHasher::new();
  110. b.hash(&mut h2);
  111. assert_eq!(h1.finish(), h2.finish());
  112. }
  113. fn url(s: &str) -> Url {
  114. let rv = s.parse().unwrap();
  115. check_eq(&rv, &rv);
  116. rv
  117. }
  118. // Doesn't care if default port is given.
  119. let a: Url = url("https://example.com/");
  120. let b: Url = url("https://example.com:443/");
  121. check_eq(&a, &b);
  122. // Different ports
  123. let a: Url = url("http://example.com/");
  124. let b: Url = url("http://example.com:8080/");
  125. assert!(a != b, "{:?} != {:?}", a, b);
  126. // Different scheme
  127. let a: Url = url("http://example.com/");
  128. let b: Url = url("https://example.com/");
  129. assert!(a != b);
  130. // Different host
  131. let a: Url = url("http://foo.com/");
  132. let b: Url = url("http://bar.com/");
  133. assert!(a != b);
  134. // Missing path, automatically substituted. Semantically the same.
  135. let a: Url = url("http://foo.com");
  136. let b: Url = url("http://foo.com/");
  137. check_eq(&a, &b);
  138. }
  139. #[test]
  140. fn host() {
  141. fn assert_host(input: &str, host: Host<&str>) {
  142. assert_eq!(Url::parse(input).unwrap().host(), Some(host));
  143. }
  144. assert_host("http://www.mozilla.org", Host::Domain("www.mozilla.org"));
  145. assert_host("http://1.35.33.49", Host::Ipv4(Ipv4Addr::new(1, 35, 33, 49)));
  146. assert_host("http://[2001:0db8:85a3:08d3:1319:8a2e:0370:7344]", Host::Ipv6(Ipv6Addr::new(
  147. 0x2001, 0x0db8, 0x85a3, 0x08d3, 0x1319, 0x8a2e, 0x0370, 0x7344)));
  148. assert_host("http://1.35.+33.49", Host::Domain("1.35.+33.49"));
  149. assert_host("http://[::]", Host::Ipv6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)));
  150. assert_host("http://[::1]", Host::Ipv6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)));
  151. assert_host("http://0x1.0X23.0x21.061", Host::Ipv4(Ipv4Addr::new(1, 35, 33, 49)));
  152. assert_host("http://0x1232131", Host::Ipv4(Ipv4Addr::new(1, 35, 33, 49)));
  153. assert_host("http://111", Host::Ipv4(Ipv4Addr::new(0, 0, 0, 111)));
  154. assert_host("http://2..2.3", Host::Domain("2..2.3"));
  155. assert!(Url::parse("http://42.0x1232131").is_err());
  156. assert!(Url::parse("http://192.168.0.257").is_err());
  157. }
  158. #[test]
  159. fn host_serialization() {
  160. // libstd’s `Display for Ipv6Addr` serializes 0:0:0:0:0:0:_:_ and 0:0:0:0:0:ffff:_:_
  161. // using IPv4-like syntax, as suggested in https://tools.ietf.org/html/rfc5952#section-4
  162. // but https://url.spec.whatwg.org/#concept-ipv6-serializer specifies not to.
  163. // Not [::0.0.0.2] / [::ffff:0.0.0.2]
  164. assert_eq!(Url::parse("http://[0::2]").unwrap().host_str(), Some("[::2]"));
  165. assert_eq!(Url::parse("http://[0::ffff:0:2]").unwrap().host_str(), Some("[::ffff:0:2]"));
  166. }
  167. #[test]
  168. fn test_idna() {
  169. assert!("http://goșu.ro".parse::<Url>().is_ok());
  170. assert_eq!(Url::parse("http://☃.net/").unwrap().host(), Some(Host::Domain("xn--n3h.net")));
  171. assert!("https://r2---sn-huoa-cvhl.googlevideo.com/crossdomain.xml".parse::<Url>().is_ok());
  172. }
  173. #[test]
  174. fn test_serialization() {
  175. let data = [
  176. ("http://example.com/", "http://example.com/"),
  177. ("http://addslash.com", "http://addslash.com/"),
  178. ("http://@emptyuser.com/", "http://emptyuser.com/"),
  179. ("http://:@emptypass.com/", "http://:@emptypass.com/"),
  180. ("http://user@user.com/", "http://user@user.com/"),
  181. ("http://user:pass@userpass.com/", "http://user:pass@userpass.com/"),
  182. ("http://slashquery.com/path/?q=something", "http://slashquery.com/path/?q=something"),
  183. ("http://noslashquery.com/path?q=something", "http://noslashquery.com/path?q=something")
  184. ];
  185. for &(input, result) in &data {
  186. let url = Url::parse(input).unwrap();
  187. assert_eq!(url.as_str(), result);
  188. }
  189. }
  190. #[test]
  191. fn test_form_urlencoded() {
  192. let pairs: &[(Cow<str>, Cow<str>)] = &[
  193. ("foo".into(), "é&".into()),
  194. ("bar".into(), "".into()),
  195. ("foo".into(), "#".into())
  196. ];
  197. let encoded = form_urlencoded::Serializer::new(String::new()).extend_pairs(pairs).finish();
  198. assert_eq!(encoded, "foo=%C3%A9%26&bar=&foo=%23");
  199. assert_eq!(form_urlencoded::parse(encoded.as_bytes()).collect::<Vec<_>>(), pairs.to_vec());
  200. }
  201. #[test]
  202. fn test_form_serialize() {
  203. let encoded = form_urlencoded::Serializer::new(String::new())
  204. .append_pair("foo", "é&")
  205. .append_pair("bar", "")
  206. .append_pair("foo", "#")
  207. .finish();
  208. assert_eq!(encoded, "foo=%C3%A9%26&bar=&foo=%23");
  209. }
  210. #[test]
  211. /// https://github.com/servo/rust-url/issues/25
  212. fn issue_25() {
  213. let filename = if cfg!(windows) { r"C:\run\pg.sock" } else { "/run/pg.sock" };
  214. let mut url = Url::from_file_path(filename).unwrap();
  215. url.assert_invariants();
  216. url.set_scheme("postgres").unwrap();
  217. url.assert_invariants();
  218. url.set_host(Some("")).unwrap();
  219. url.assert_invariants();
  220. url.set_username("me").unwrap();
  221. url.assert_invariants();
  222. let expected = format!("postgres://me@/{}run/pg.sock", if cfg!(windows) { "C:/" } else { "" });
  223. assert_eq!(url.as_str(), expected);
  224. }
  225. #[test]
  226. /// https://github.com/servo/rust-url/issues/61
  227. fn issue_61() {
  228. let mut url = Url::parse("http://mozilla.org").unwrap();
  229. url.set_scheme("https").unwrap();
  230. assert_eq!(url.port(), None);
  231. assert_eq!(url.port_or_known_default(), Some(443));
  232. url.assert_invariants();
  233. }
  234. #[test]
  235. #[cfg(not(windows))]
  236. /// https://github.com/servo/rust-url/issues/197
  237. fn issue_197() {
  238. let mut url = Url::from_file_path("/").expect("Failed to parse path");
  239. url.assert_invariants();
  240. assert_eq!(url, Url::parse("file:///").expect("Failed to parse path + protocol"));
  241. url.path_segments_mut().expect("path_segments_mut").pop_if_empty();
  242. }
  243. #[test]
  244. fn issue_241() {
  245. Url::parse("mailto:").unwrap().cannot_be_a_base();
  246. }
  247. #[test]
  248. /// https://github.com/servo/rust-url/issues/222
  249. fn append_trailing_slash() {
  250. let mut url: Url = "http://localhost:6767/foo/bar?a=b".parse().unwrap();
  251. url.assert_invariants();
  252. url.path_segments_mut().unwrap().push("");
  253. url.assert_invariants();
  254. assert_eq!(url.to_string(), "http://localhost:6767/foo/bar/?a=b");
  255. }
  256. #[test]
  257. /// https://github.com/servo/rust-url/issues/227
  258. fn extend_query_pairs_then_mutate() {
  259. let mut url: Url = "http://localhost:6767/foo/bar".parse().unwrap();
  260. url.query_pairs_mut().extend_pairs(vec![ ("auth", "my-token") ].into_iter());
  261. url.assert_invariants();
  262. assert_eq!(url.to_string(), "http://localhost:6767/foo/bar?auth=my-token");
  263. url.path_segments_mut().unwrap().push("some_other_path");
  264. url.assert_invariants();
  265. assert_eq!(url.to_string(), "http://localhost:6767/foo/bar/some_other_path?auth=my-token");
  266. }
  267. #[test]
  268. /// https://github.com/servo/rust-url/issues/222
  269. fn append_empty_segment_then_mutate() {
  270. let mut url: Url = "http://localhost:6767/foo/bar?a=b".parse().unwrap();
  271. url.assert_invariants();
  272. url.path_segments_mut().unwrap().push("").pop();
  273. url.assert_invariants();
  274. assert_eq!(url.to_string(), "http://localhost:6767/foo/bar?a=b");
  275. }