unit.rs 11 KB

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