unit.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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 parse_with_params() {
  95. let url = Url::parse_with_params("http://testing.com/this?dont=clobberme",
  96. &[("lang", "rust")]).unwrap();
  97. assert_eq!(url.as_str(), "http://testing.com/this?dont=clobberme&lang=rust");
  98. }
  99. #[test]
  100. fn issue_124() {
  101. let url: Url = "file:a".parse().unwrap();
  102. assert_eq!(url.path(), "/a");
  103. let url: Url = "file:...".parse().unwrap();
  104. assert_eq!(url.path(), "/...");
  105. let url: Url = "file:..".parse().unwrap();
  106. assert_eq!(url.path(), "/");
  107. }
  108. #[test]
  109. fn test_equality() {
  110. use std::hash::{Hash, Hasher};
  111. use std::collections::hash_map::DefaultHasher;
  112. fn check_eq(a: &Url, b: &Url) {
  113. assert_eq!(a, b);
  114. let mut h1 = DefaultHasher::new();
  115. a.hash(&mut h1);
  116. let mut h2 = DefaultHasher::new();
  117. b.hash(&mut h2);
  118. assert_eq!(h1.finish(), h2.finish());
  119. }
  120. fn url(s: &str) -> Url {
  121. let rv = s.parse().unwrap();
  122. check_eq(&rv, &rv);
  123. rv
  124. }
  125. // Doesn't care if default port is given.
  126. let a: Url = url("https://example.com/");
  127. let b: Url = url("https://example.com:443/");
  128. check_eq(&a, &b);
  129. // Different ports
  130. let a: Url = url("http://example.com/");
  131. let b: Url = url("http://example.com:8080/");
  132. assert!(a != b, "{:?} != {:?}", a, b);
  133. // Different scheme
  134. let a: Url = url("http://example.com/");
  135. let b: Url = url("https://example.com/");
  136. assert!(a != b);
  137. // Different host
  138. let a: Url = url("http://foo.com/");
  139. let b: Url = url("http://bar.com/");
  140. assert!(a != b);
  141. // Missing path, automatically substituted. Semantically the same.
  142. let a: Url = url("http://foo.com");
  143. let b: Url = url("http://foo.com/");
  144. check_eq(&a, &b);
  145. }
  146. #[test]
  147. fn host() {
  148. fn assert_host(input: &str, host: Host<&str>) {
  149. assert_eq!(Url::parse(input).unwrap().host(), Some(host));
  150. }
  151. assert_host("http://www.mozilla.org", Host::Domain("www.mozilla.org"));
  152. assert_host("http://1.35.33.49", Host::Ipv4(Ipv4Addr::new(1, 35, 33, 49)));
  153. assert_host("http://[2001:0db8:85a3:08d3:1319:8a2e:0370:7344]", Host::Ipv6(Ipv6Addr::new(
  154. 0x2001, 0x0db8, 0x85a3, 0x08d3, 0x1319, 0x8a2e, 0x0370, 0x7344)));
  155. assert_host("http://1.35.+33.49", Host::Domain("1.35.+33.49"));
  156. assert_host("http://[::]", Host::Ipv6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)));
  157. assert_host("http://[::1]", Host::Ipv6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)));
  158. assert_host("http://0x1.0X23.0x21.061", Host::Ipv4(Ipv4Addr::new(1, 35, 33, 49)));
  159. assert_host("http://0x1232131", Host::Ipv4(Ipv4Addr::new(1, 35, 33, 49)));
  160. assert_host("http://111", Host::Ipv4(Ipv4Addr::new(0, 0, 0, 111)));
  161. assert_host("http://2..2.3", Host::Domain("2..2.3"));
  162. assert!(Url::parse("http://42.0x1232131").is_err());
  163. assert!(Url::parse("http://192.168.0.257").is_err());
  164. }
  165. #[test]
  166. fn host_serialization() {
  167. // libstd’s `Display for Ipv6Addr` serializes 0:0:0:0:0:0:_:_ and 0:0:0:0:0:ffff:_:_
  168. // using IPv4-like syntax, as suggested in https://tools.ietf.org/html/rfc5952#section-4
  169. // but https://url.spec.whatwg.org/#concept-ipv6-serializer specifies not to.
  170. // Not [::0.0.0.2] / [::ffff:0.0.0.2]
  171. assert_eq!(Url::parse("http://[0::2]").unwrap().host_str(), Some("[::2]"));
  172. assert_eq!(Url::parse("http://[0::ffff:0:2]").unwrap().host_str(), Some("[::ffff:0:2]"));
  173. }
  174. #[test]
  175. fn test_idna() {
  176. assert!("http://goșu.ro".parse::<Url>().is_ok());
  177. assert_eq!(Url::parse("http://☃.net/").unwrap().host(), Some(Host::Domain("xn--n3h.net")));
  178. assert!("https://r2---sn-huoa-cvhl.googlevideo.com/crossdomain.xml".parse::<Url>().is_ok());
  179. }
  180. #[test]
  181. fn test_serialization() {
  182. let data = [
  183. ("http://example.com/", "http://example.com/"),
  184. ("http://addslash.com", "http://addslash.com/"),
  185. ("http://@emptyuser.com/", "http://emptyuser.com/"),
  186. ("http://:@emptypass.com/", "http://:@emptypass.com/"),
  187. ("http://user@user.com/", "http://user@user.com/"),
  188. ("http://user:pass@userpass.com/", "http://user:pass@userpass.com/"),
  189. ("http://slashquery.com/path/?q=something", "http://slashquery.com/path/?q=something"),
  190. ("http://noslashquery.com/path?q=something", "http://noslashquery.com/path?q=something")
  191. ];
  192. for &(input, result) in &data {
  193. let url = Url::parse(input).unwrap();
  194. assert_eq!(url.as_str(), result);
  195. }
  196. }
  197. #[test]
  198. fn test_form_urlencoded() {
  199. let pairs: &[(Cow<str>, Cow<str>)] = &[
  200. ("foo".into(), "é&".into()),
  201. ("bar".into(), "".into()),
  202. ("foo".into(), "#".into())
  203. ];
  204. let encoded = form_urlencoded::Serializer::new(String::new()).extend_pairs(pairs).finish();
  205. assert_eq!(encoded, "foo=%C3%A9%26&bar=&foo=%23");
  206. assert_eq!(form_urlencoded::parse(encoded.as_bytes()).collect::<Vec<_>>(), pairs.to_vec());
  207. }
  208. #[test]
  209. fn test_form_serialize() {
  210. let encoded = form_urlencoded::Serializer::new(String::new())
  211. .append_pair("foo", "é&")
  212. .append_pair("bar", "")
  213. .append_pair("foo", "#")
  214. .finish();
  215. assert_eq!(encoded, "foo=%C3%A9%26&bar=&foo=%23");
  216. }
  217. #[test]
  218. /// https://github.com/servo/rust-url/issues/25
  219. fn issue_25() {
  220. let filename = if cfg!(windows) { r"C:\run\pg.sock" } else { "/run/pg.sock" };
  221. let mut url = Url::from_file_path(filename).unwrap();
  222. url.assert_invariants();
  223. url.set_scheme("postgres").unwrap();
  224. url.assert_invariants();
  225. url.set_host(Some("")).unwrap();
  226. url.assert_invariants();
  227. url.set_username("me").unwrap();
  228. url.assert_invariants();
  229. let expected = format!("postgres://me@/{}run/pg.sock", if cfg!(windows) { "C:/" } else { "" });
  230. assert_eq!(url.as_str(), expected);
  231. }
  232. #[test]
  233. /// https://github.com/servo/rust-url/issues/61
  234. fn issue_61() {
  235. let mut url = Url::parse("http://mozilla.org").unwrap();
  236. url.set_scheme("https").unwrap();
  237. assert_eq!(url.port(), None);
  238. assert_eq!(url.port_or_known_default(), Some(443));
  239. url.assert_invariants();
  240. }
  241. #[test]
  242. #[cfg(not(windows))]
  243. /// https://github.com/servo/rust-url/issues/197
  244. fn issue_197() {
  245. let mut url = Url::from_file_path("/").expect("Failed to parse path");
  246. url.assert_invariants();
  247. assert_eq!(url, Url::parse("file:///").expect("Failed to parse path + protocol"));
  248. url.path_segments_mut().expect("path_segments_mut").pop_if_empty();
  249. }
  250. #[test]
  251. fn issue_241() {
  252. Url::parse("mailto:").unwrap().cannot_be_a_base();
  253. }
  254. #[test]
  255. /// https://github.com/servo/rust-url/issues/222
  256. fn append_trailing_slash() {
  257. let mut url: Url = "http://localhost:6767/foo/bar?a=b".parse().unwrap();
  258. url.assert_invariants();
  259. url.path_segments_mut().unwrap().push("");
  260. url.assert_invariants();
  261. assert_eq!(url.to_string(), "http://localhost:6767/foo/bar/?a=b");
  262. }
  263. #[test]
  264. /// https://github.com/servo/rust-url/issues/227
  265. fn extend_query_pairs_then_mutate() {
  266. let mut url: Url = "http://localhost:6767/foo/bar".parse().unwrap();
  267. url.query_pairs_mut().extend_pairs(vec![ ("auth", "my-token") ].into_iter());
  268. url.assert_invariants();
  269. assert_eq!(url.to_string(), "http://localhost:6767/foo/bar?auth=my-token");
  270. url.path_segments_mut().unwrap().push("some_other_path");
  271. url.assert_invariants();
  272. assert_eq!(url.to_string(), "http://localhost:6767/foo/bar/some_other_path?auth=my-token");
  273. }
  274. #[test]
  275. /// https://github.com/servo/rust-url/issues/222
  276. fn append_empty_segment_then_mutate() {
  277. let mut url: Url = "http://localhost:6767/foo/bar?a=b".parse().unwrap();
  278. url.assert_invariants();
  279. url.path_segments_mut().unwrap().push("").pop();
  280. url.assert_invariants();
  281. assert_eq!(url.to_string(), "http://localhost:6767/foo/bar?a=b");
  282. }
  283. #[test]
  284. /// https://github.com/servo/rust-url/issues/243
  285. fn test_set_host() {
  286. let mut url = Url::parse("https://example.net/hello").unwrap();
  287. url.set_host(Some("foo.com")).unwrap();
  288. assert_eq!(url.as_str(), "https://foo.com/hello");
  289. assert!(url.set_host(None).is_err());
  290. assert_eq!(url.as_str(), "https://foo.com/hello");
  291. assert!(url.set_host(Some("")).is_err());
  292. assert_eq!(url.as_str(), "https://foo.com/hello");
  293. let mut url = Url::parse("foobar://example.net/hello").unwrap();
  294. url.set_host(None).unwrap();
  295. assert_eq!(url.as_str(), "foobar:/hello");
  296. }