unit.rs 13 KB

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