unit.rs 11 KB

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