unit.rs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  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 percent_encoding;
  10. extern crate url;
  11. use std::borrow::Cow;
  12. use std::cell::{Cell, RefCell};
  13. use std::net::{Ipv4Addr, Ipv6Addr};
  14. use std::path::{Path, PathBuf};
  15. use url::{form_urlencoded, Host, Url};
  16. #[test]
  17. fn size() {
  18. use std::mem::size_of;
  19. assert_eq!(size_of::<Url>(), size_of::<Option<Url>>());
  20. }
  21. macro_rules! assert_from_file_path {
  22. ($path: expr) => {
  23. assert_from_file_path!($path, $path)
  24. };
  25. ($path: expr, $url_path: expr) => {{
  26. let url = Url::from_file_path(Path::new($path)).unwrap();
  27. assert_eq!(url.host(), None);
  28. assert_eq!(url.path(), $url_path);
  29. assert_eq!(url.to_file_path(), Ok(PathBuf::from($path)));
  30. }};
  31. }
  32. #[test]
  33. fn new_file_paths() {
  34. if cfg!(unix) {
  35. assert_eq!(Url::from_file_path(Path::new("relative")), Err(()));
  36. assert_eq!(Url::from_file_path(Path::new("../relative")), Err(()));
  37. }
  38. if cfg!(windows) {
  39. assert_eq!(Url::from_file_path(Path::new("relative")), Err(()));
  40. assert_eq!(Url::from_file_path(Path::new(r"..\relative")), Err(()));
  41. assert_eq!(Url::from_file_path(Path::new(r"\drive-relative")), Err(()));
  42. assert_eq!(Url::from_file_path(Path::new(r"\\ucn\")), Err(()));
  43. }
  44. if cfg!(unix) {
  45. assert_from_file_path!("/foo/bar");
  46. assert_from_file_path!("/foo/ba\0r", "/foo/ba%00r");
  47. assert_from_file_path!("/foo/ba%00r", "/foo/ba%2500r");
  48. }
  49. }
  50. #[test]
  51. #[cfg(unix)]
  52. fn new_path_bad_utf8() {
  53. use std::ffi::OsStr;
  54. use std::os::unix::prelude::*;
  55. let url = Url::from_file_path(Path::new(OsStr::from_bytes(b"/foo/ba\x80r"))).unwrap();
  56. let os_str = OsStr::from_bytes(b"/foo/ba\x80r");
  57. assert_eq!(url.to_file_path(), Ok(PathBuf::from(os_str)));
  58. }
  59. #[test]
  60. fn new_path_windows_fun() {
  61. if cfg!(windows) {
  62. assert_from_file_path!(r"C:\foo\bar", "/C:/foo/bar");
  63. assert_from_file_path!("C:\\foo\\ba\0r", "/C:/foo/ba%00r");
  64. // Invalid UTF-8
  65. assert!(Url::parse("file:///C:/foo/ba%80r")
  66. .unwrap()
  67. .to_file_path()
  68. .is_err());
  69. // test windows canonicalized path
  70. let path = PathBuf::from(r"\\?\C:\foo\bar");
  71. assert!(Url::from_file_path(path).is_ok());
  72. // Percent-encoded drive letter
  73. let url = Url::parse("file:///C%3A/foo/bar").unwrap();
  74. assert_eq!(url.to_file_path(), Ok(PathBuf::from(r"C:\foo\bar")));
  75. }
  76. }
  77. #[test]
  78. fn new_directory_paths() {
  79. if cfg!(unix) {
  80. assert_eq!(Url::from_directory_path(Path::new("relative")), Err(()));
  81. assert_eq!(Url::from_directory_path(Path::new("../relative")), Err(()));
  82. let url = Url::from_directory_path(Path::new("/foo/bar")).unwrap();
  83. assert_eq!(url.host(), None);
  84. assert_eq!(url.path(), "/foo/bar/");
  85. }
  86. if cfg!(windows) {
  87. assert_eq!(Url::from_directory_path(Path::new("relative")), Err(()));
  88. assert_eq!(Url::from_directory_path(Path::new(r"..\relative")), Err(()));
  89. assert_eq!(
  90. Url::from_directory_path(Path::new(r"\drive-relative")),
  91. Err(())
  92. );
  93. assert_eq!(Url::from_directory_path(Path::new(r"\\ucn\")), Err(()));
  94. let url = Url::from_directory_path(Path::new(r"C:\foo\bar")).unwrap();
  95. assert_eq!(url.host(), None);
  96. assert_eq!(url.path(), "/C:/foo/bar/");
  97. }
  98. }
  99. #[test]
  100. fn path_backslash_fun() {
  101. let mut special_url = "http://foobar.com".parse::<Url>().unwrap();
  102. special_url.path_segments_mut().unwrap().push("foo\\bar");
  103. assert_eq!(special_url.as_str(), "http://foobar.com/foo%5Cbar");
  104. let mut nonspecial_url = "thing://foobar.com".parse::<Url>().unwrap();
  105. nonspecial_url.path_segments_mut().unwrap().push("foo\\bar");
  106. assert_eq!(nonspecial_url.as_str(), "thing://foobar.com/foo\\bar");
  107. }
  108. #[test]
  109. fn from_str() {
  110. assert!("http://testing.com/this".parse::<Url>().is_ok());
  111. }
  112. #[test]
  113. fn parse_with_params() {
  114. let url = Url::parse_with_params(
  115. "http://testing.com/this?dont=clobberme",
  116. &[("lang", "rust")],
  117. )
  118. .unwrap();
  119. assert_eq!(
  120. url.as_str(),
  121. "http://testing.com/this?dont=clobberme&lang=rust"
  122. );
  123. }
  124. #[test]
  125. fn issue_124() {
  126. let url: Url = "file:a".parse().unwrap();
  127. assert_eq!(url.path(), "/a");
  128. let url: Url = "file:...".parse().unwrap();
  129. assert_eq!(url.path(), "/...");
  130. let url: Url = "file:..".parse().unwrap();
  131. assert_eq!(url.path(), "/");
  132. }
  133. #[test]
  134. fn test_equality() {
  135. use std::collections::hash_map::DefaultHasher;
  136. use std::hash::{Hash, Hasher};
  137. fn check_eq(a: &Url, b: &Url) {
  138. assert_eq!(a, b);
  139. let mut h1 = DefaultHasher::new();
  140. a.hash(&mut h1);
  141. let mut h2 = DefaultHasher::new();
  142. b.hash(&mut h2);
  143. assert_eq!(h1.finish(), h2.finish());
  144. }
  145. fn url(s: &str) -> Url {
  146. let rv = s.parse().unwrap();
  147. check_eq(&rv, &rv);
  148. rv
  149. }
  150. // Doesn't care if default port is given.
  151. let a: Url = url("https://example.com/");
  152. let b: Url = url("https://example.com:443/");
  153. check_eq(&a, &b);
  154. // Different ports
  155. let a: Url = url("http://example.com/");
  156. let b: Url = url("http://example.com:8080/");
  157. assert!(a != b, "{:?} != {:?}", a, b);
  158. // Different scheme
  159. let a: Url = url("http://example.com/");
  160. let b: Url = url("https://example.com/");
  161. assert_ne!(a, b);
  162. // Different host
  163. let a: Url = url("http://foo.com/");
  164. let b: Url = url("http://bar.com/");
  165. assert_ne!(a, b);
  166. // Missing path, automatically substituted. Semantically the same.
  167. let a: Url = url("http://foo.com");
  168. let b: Url = url("http://foo.com/");
  169. check_eq(&a, &b);
  170. }
  171. #[test]
  172. fn host() {
  173. fn assert_host(input: &str, host: Host<&str>) {
  174. assert_eq!(Url::parse(input).unwrap().host(), Some(host));
  175. }
  176. assert_host("http://www.mozilla.org", Host::Domain("www.mozilla.org"));
  177. assert_host(
  178. "http://1.35.33.49",
  179. Host::Ipv4(Ipv4Addr::new(1, 35, 33, 49)),
  180. );
  181. assert_host(
  182. "http://[2001:0db8:85a3:08d3:1319:8a2e:0370:7344]",
  183. Host::Ipv6(Ipv6Addr::new(
  184. 0x2001, 0x0db8, 0x85a3, 0x08d3, 0x1319, 0x8a2e, 0x0370, 0x7344,
  185. )),
  186. );
  187. assert_host("http://1.35.+33.49", Host::Domain("1.35.+33.49"));
  188. assert_host(
  189. "http://[::]",
  190. Host::Ipv6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)),
  191. );
  192. assert_host(
  193. "http://[::1]",
  194. Host::Ipv6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)),
  195. );
  196. assert_host(
  197. "http://0x1.0X23.0x21.061",
  198. Host::Ipv4(Ipv4Addr::new(1, 35, 33, 49)),
  199. );
  200. assert_host("http://0x1232131", Host::Ipv4(Ipv4Addr::new(1, 35, 33, 49)));
  201. assert_host("http://111", Host::Ipv4(Ipv4Addr::new(0, 0, 0, 111)));
  202. assert_host("http://2..2.3", Host::Domain("2..2.3"));
  203. assert!(Url::parse("http://42.0x1232131").is_err());
  204. assert!(Url::parse("http://192.168.0.257").is_err());
  205. }
  206. #[test]
  207. fn host_serialization() {
  208. // libstd’s `Display for Ipv6Addr` serializes 0:0:0:0:0:0:_:_ and 0:0:0:0:0:ffff:_:_
  209. // using IPv4-like syntax, as suggested in https://tools.ietf.org/html/rfc5952#section-4
  210. // but https://url.spec.whatwg.org/#concept-ipv6-serializer specifies not to.
  211. // Not [::0.0.0.2] / [::ffff:0.0.0.2]
  212. assert_eq!(
  213. Url::parse("http://[0::2]").unwrap().host_str(),
  214. Some("[::2]")
  215. );
  216. assert_eq!(
  217. Url::parse("http://[0::ffff:0:2]").unwrap().host_str(),
  218. Some("[::ffff:0:2]")
  219. );
  220. }
  221. #[test]
  222. fn test_idna() {
  223. assert!("http://goșu.ro".parse::<Url>().is_ok());
  224. assert_eq!(
  225. Url::parse("http://☃.net/").unwrap().host(),
  226. Some(Host::Domain("xn--n3h.net"))
  227. );
  228. assert!("https://r2---sn-huoa-cvhl.googlevideo.com/crossdomain.xml"
  229. .parse::<Url>()
  230. .is_ok());
  231. }
  232. #[test]
  233. fn test_serialization() {
  234. let data = [
  235. ("http://example.com/", "http://example.com/"),
  236. ("http://addslash.com", "http://addslash.com/"),
  237. ("http://@emptyuser.com/", "http://emptyuser.com/"),
  238. ("http://:@emptypass.com/", "http://emptypass.com/"),
  239. ("http://user@user.com/", "http://user@user.com/"),
  240. (
  241. "http://user:pass@userpass.com/",
  242. "http://user:pass@userpass.com/",
  243. ),
  244. (
  245. "http://slashquery.com/path/?q=something",
  246. "http://slashquery.com/path/?q=something",
  247. ),
  248. (
  249. "http://noslashquery.com/path?q=something",
  250. "http://noslashquery.com/path?q=something",
  251. ),
  252. ];
  253. for &(input, result) in &data {
  254. let url = Url::parse(input).unwrap();
  255. assert_eq!(url.as_str(), result);
  256. }
  257. }
  258. #[test]
  259. fn test_form_urlencoded() {
  260. let pairs: &[(Cow<str>, Cow<str>)] = &[
  261. ("foo".into(), "é&".into()),
  262. ("bar".into(), "".into()),
  263. ("foo".into(), "#".into()),
  264. ];
  265. let encoded = form_urlencoded::Serializer::new(String::new())
  266. .extend_pairs(pairs)
  267. .finish();
  268. assert_eq!(encoded, "foo=%C3%A9%26&bar=&foo=%23");
  269. assert_eq!(
  270. form_urlencoded::parse(encoded.as_bytes()).collect::<Vec<_>>(),
  271. pairs.to_vec()
  272. );
  273. }
  274. #[test]
  275. fn test_form_serialize() {
  276. let encoded = form_urlencoded::Serializer::new(String::new())
  277. .append_pair("foo", "é&")
  278. .append_pair("bar", "")
  279. .append_pair("foo", "#")
  280. .finish();
  281. assert_eq!(encoded, "foo=%C3%A9%26&bar=&foo=%23");
  282. }
  283. #[test]
  284. fn form_urlencoded_encoding_override() {
  285. let encoded = form_urlencoded::Serializer::new(String::new())
  286. .encoding_override(Some(&|s| s.as_bytes().to_ascii_uppercase().into()))
  287. .append_pair("foo", "bar")
  288. .finish();
  289. assert_eq!(encoded, "FOO=BAR");
  290. }
  291. #[test]
  292. /// https://github.com/servo/rust-url/issues/61
  293. fn issue_61() {
  294. let mut url = Url::parse("http://mozilla.org").unwrap();
  295. url.set_scheme("https").unwrap();
  296. assert_eq!(url.port(), None);
  297. assert_eq!(url.port_or_known_default(), Some(443));
  298. url.check_invariants().unwrap();
  299. }
  300. #[test]
  301. #[cfg(not(windows))]
  302. /// https://github.com/servo/rust-url/issues/197
  303. fn issue_197() {
  304. let mut url = Url::from_file_path("/").expect("Failed to parse path");
  305. url.check_invariants().unwrap();
  306. assert_eq!(
  307. url,
  308. Url::parse("file:///").expect("Failed to parse path + protocol")
  309. );
  310. url.path_segments_mut()
  311. .expect("path_segments_mut")
  312. .pop_if_empty();
  313. }
  314. #[test]
  315. fn issue_241() {
  316. Url::parse("mailto:").unwrap().cannot_be_a_base();
  317. }
  318. #[test]
  319. /// https://github.com/servo/rust-url/issues/222
  320. fn append_trailing_slash() {
  321. let mut url: Url = "http://localhost:6767/foo/bar?a=b".parse().unwrap();
  322. url.check_invariants().unwrap();
  323. url.path_segments_mut().unwrap().push("");
  324. url.check_invariants().unwrap();
  325. assert_eq!(url.to_string(), "http://localhost:6767/foo/bar/?a=b");
  326. }
  327. #[test]
  328. /// https://github.com/servo/rust-url/issues/227
  329. fn extend_query_pairs_then_mutate() {
  330. let mut url: Url = "http://localhost:6767/foo/bar".parse().unwrap();
  331. url.query_pairs_mut()
  332. .extend_pairs(vec![("auth", "my-token")].into_iter());
  333. url.check_invariants().unwrap();
  334. assert_eq!(
  335. url.to_string(),
  336. "http://localhost:6767/foo/bar?auth=my-token"
  337. );
  338. url.path_segments_mut().unwrap().push("some_other_path");
  339. url.check_invariants().unwrap();
  340. assert_eq!(
  341. url.to_string(),
  342. "http://localhost:6767/foo/bar/some_other_path?auth=my-token"
  343. );
  344. }
  345. #[test]
  346. /// https://github.com/servo/rust-url/issues/222
  347. fn append_empty_segment_then_mutate() {
  348. let mut url: Url = "http://localhost:6767/foo/bar?a=b".parse().unwrap();
  349. url.check_invariants().unwrap();
  350. url.path_segments_mut().unwrap().push("").pop();
  351. url.check_invariants().unwrap();
  352. assert_eq!(url.to_string(), "http://localhost:6767/foo/bar?a=b");
  353. }
  354. #[test]
  355. /// https://github.com/servo/rust-url/issues/243
  356. fn test_set_host() {
  357. let mut url = Url::parse("https://example.net/hello").unwrap();
  358. url.set_host(Some("foo.com")).unwrap();
  359. assert_eq!(url.as_str(), "https://foo.com/hello");
  360. assert!(url.set_host(None).is_err());
  361. assert_eq!(url.as_str(), "https://foo.com/hello");
  362. assert!(url.set_host(Some("")).is_err());
  363. assert_eq!(url.as_str(), "https://foo.com/hello");
  364. let mut url = Url::parse("foobar://example.net/hello").unwrap();
  365. url.set_host(None).unwrap();
  366. assert_eq!(url.as_str(), "foobar:/hello");
  367. let mut url = Url::parse("foo://ș").unwrap();
  368. assert_eq!(url.as_str(), "foo://%C8%99/");
  369. url.set_host(Some("goșu.ro")).unwrap();
  370. assert_eq!(url.as_str(), "foo://go%C8%99u.ro/");
  371. }
  372. #[test]
  373. // https://github.com/servo/rust-url/issues/166
  374. fn test_leading_dots() {
  375. assert_eq!(
  376. Host::parse(".org").unwrap(),
  377. Host::Domain(".org".to_owned())
  378. );
  379. assert_eq!(Url::parse("file://./foo").unwrap().domain(), Some("."));
  380. }
  381. #[test]
  382. /// https://github.com/servo/rust-url/issues/302
  383. fn test_origin_hash() {
  384. use std::collections::hash_map::DefaultHasher;
  385. use std::hash::{Hash, Hasher};
  386. fn hash<T: Hash>(value: &T) -> u64 {
  387. let mut hasher = DefaultHasher::new();
  388. value.hash(&mut hasher);
  389. hasher.finish()
  390. }
  391. let origin = &Url::parse("http://example.net/").unwrap().origin();
  392. let origins_to_compare = [
  393. Url::parse("http://example.net:80/").unwrap().origin(),
  394. Url::parse("http://example.net:81/").unwrap().origin(),
  395. Url::parse("http://example.net").unwrap().origin(),
  396. Url::parse("http://example.net/hello").unwrap().origin(),
  397. Url::parse("https://example.net").unwrap().origin(),
  398. Url::parse("ftp://example.net").unwrap().origin(),
  399. Url::parse("file://example.net").unwrap().origin(),
  400. Url::parse("http://user@example.net/").unwrap().origin(),
  401. Url::parse("http://user:pass@example.net/")
  402. .unwrap()
  403. .origin(),
  404. ];
  405. for origin_to_compare in &origins_to_compare {
  406. if origin == origin_to_compare {
  407. assert_eq!(hash(origin), hash(origin_to_compare));
  408. } else {
  409. assert_ne!(hash(origin), hash(origin_to_compare));
  410. }
  411. }
  412. let opaque_origin = Url::parse("file://example.net").unwrap().origin();
  413. let same_opaque_origin = Url::parse("file://example.net").unwrap().origin();
  414. let other_opaque_origin = Url::parse("file://other").unwrap().origin();
  415. assert_ne!(hash(&opaque_origin), hash(&same_opaque_origin));
  416. assert_ne!(hash(&opaque_origin), hash(&other_opaque_origin));
  417. }
  418. #[test]
  419. fn test_windows_unc_path() {
  420. if !cfg!(windows) {
  421. return;
  422. }
  423. let url = Url::from_file_path(Path::new(r"\\host\share\path\file.txt")).unwrap();
  424. assert_eq!(url.as_str(), "file://host/share/path/file.txt");
  425. let url = Url::from_file_path(Path::new(r"\\höst\share\path\file.txt")).unwrap();
  426. assert_eq!(url.as_str(), "file://xn--hst-sna/share/path/file.txt");
  427. let url = Url::from_file_path(Path::new(r"\\192.168.0.1\share\path\file.txt")).unwrap();
  428. assert_eq!(url.host(), Some(Host::Ipv4(Ipv4Addr::new(192, 168, 0, 1))));
  429. let path = url.to_file_path().unwrap();
  430. assert_eq!(path.to_str(), Some(r"\\192.168.0.1\share\path\file.txt"));
  431. // Another way to write these:
  432. let url = Url::from_file_path(Path::new(r"\\?\UNC\host\share\path\file.txt")).unwrap();
  433. assert_eq!(url.as_str(), "file://host/share/path/file.txt");
  434. // Paths starting with "\\.\" (Local Device Paths) are intentionally not supported.
  435. let url = Url::from_file_path(Path::new(r"\\.\some\path\file.txt"));
  436. assert!(url.is_err());
  437. }
  438. #[test]
  439. fn test_syntax_violation_callback() {
  440. use url::SyntaxViolation::*;
  441. let violation = Cell::new(None);
  442. let url = Url::options()
  443. .syntax_violation_callback(Some(&|v| violation.set(Some(v))))
  444. .parse("http:////mozilla.org:42")
  445. .unwrap();
  446. assert_eq!(url.port(), Some(42));
  447. let v = violation.take().unwrap();
  448. assert_eq!(v, ExpectedDoubleSlash);
  449. assert_eq!(v.description(), "expected //");
  450. }
  451. #[test]
  452. fn test_syntax_violation_callback_lifetimes() {
  453. use url::SyntaxViolation::*;
  454. let violation = Cell::new(None);
  455. let vfn = |s| violation.set(Some(s));
  456. let url = Url::options()
  457. .syntax_violation_callback(Some(&vfn))
  458. .parse("http:////mozilla.org:42")
  459. .unwrap();
  460. assert_eq!(url.port(), Some(42));
  461. assert_eq!(violation.take(), Some(ExpectedDoubleSlash));
  462. let url = Url::options()
  463. .syntax_violation_callback(Some(&vfn))
  464. .parse("http://mozilla.org\\path")
  465. .unwrap();
  466. assert_eq!(url.path(), "/path");
  467. assert_eq!(violation.take(), Some(Backslash));
  468. }
  469. #[test]
  470. fn test_options_reuse() {
  471. use url::SyntaxViolation::*;
  472. let violations = RefCell::new(Vec::new());
  473. let vfn = |v| violations.borrow_mut().push(v);
  474. let options = Url::options().syntax_violation_callback(Some(&vfn));
  475. let url = options.parse("http:////mozilla.org").unwrap();
  476. let options = options.base_url(Some(&url));
  477. let url = options.parse("/sub\\path").unwrap();
  478. assert_eq!(url.as_str(), "http://mozilla.org/sub/path");
  479. assert_eq!(*violations.borrow(), vec!(ExpectedDoubleSlash, Backslash));
  480. }