unit.rs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119
  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. use std::borrow::Cow;
  10. use std::cell::{Cell, RefCell};
  11. use std::net::{Ipv4Addr, Ipv6Addr};
  12. use std::path::{Path, PathBuf};
  13. use url::{form_urlencoded, Host, Origin, Url};
  14. #[test]
  15. fn size() {
  16. use std::mem::size_of;
  17. assert_eq!(size_of::<Url>(), size_of::<Option<Url>>());
  18. }
  19. #[test]
  20. fn test_relative() {
  21. let base: Url = "sc://%C3%B1".parse().unwrap();
  22. let url = base.join("/resources/testharness.js").unwrap();
  23. assert_eq!(url.as_str(), "sc://%C3%B1/resources/testharness.js");
  24. }
  25. #[test]
  26. fn test_relative_empty() {
  27. let base: Url = "sc://%C3%B1".parse().unwrap();
  28. let url = base.join("").unwrap();
  29. assert_eq!(url.as_str(), "sc://%C3%B1");
  30. }
  31. #[test]
  32. fn test_set_empty_host() {
  33. let mut base: Url = "moz://foo:bar@servo/baz".parse().unwrap();
  34. base.set_username("").unwrap();
  35. assert_eq!(base.as_str(), "moz://:bar@servo/baz");
  36. base.set_host(None).unwrap();
  37. assert_eq!(base.as_str(), "moz:/baz");
  38. base.set_host(Some("servo")).unwrap();
  39. assert_eq!(base.as_str(), "moz://servo/baz");
  40. }
  41. #[test]
  42. fn test_set_empty_hostname() {
  43. use url::quirks;
  44. let mut base: Url = "moz://foo@servo/baz".parse().unwrap();
  45. assert!(
  46. quirks::set_hostname(&mut base, "").is_err(),
  47. "setting an empty hostname to a url with a username should fail"
  48. );
  49. base = "moz://:pass@servo/baz".parse().unwrap();
  50. assert!(
  51. quirks::set_hostname(&mut base, "").is_err(),
  52. "setting an empty hostname to a url with a password should fail"
  53. );
  54. base = "moz://servo/baz".parse().unwrap();
  55. quirks::set_hostname(&mut base, "").unwrap();
  56. assert_eq!(base.as_str(), "moz:///baz");
  57. }
  58. macro_rules! assert_from_file_path {
  59. ($path: expr) => {
  60. assert_from_file_path!($path, $path)
  61. };
  62. ($path: expr, $url_path: expr) => {{
  63. let url = Url::from_file_path(Path::new($path)).unwrap();
  64. assert_eq!(url.host(), None);
  65. assert_eq!(url.path(), $url_path);
  66. assert_eq!(url.to_file_path(), Ok(PathBuf::from($path)));
  67. }};
  68. }
  69. #[test]
  70. fn new_file_paths() {
  71. if cfg!(unix) {
  72. assert_eq!(Url::from_file_path(Path::new("relative")), Err(()));
  73. assert_eq!(Url::from_file_path(Path::new("../relative")), Err(()));
  74. }
  75. if cfg!(windows) {
  76. assert_eq!(Url::from_file_path(Path::new("relative")), Err(()));
  77. assert_eq!(Url::from_file_path(Path::new(r"..\relative")), Err(()));
  78. assert_eq!(Url::from_file_path(Path::new(r"\drive-relative")), Err(()));
  79. assert_eq!(Url::from_file_path(Path::new(r"\\ucn\")), Err(()));
  80. }
  81. if cfg!(unix) {
  82. assert_from_file_path!("/foo/bar");
  83. assert_from_file_path!("/foo/ba\0r", "/foo/ba%00r");
  84. assert_from_file_path!("/foo/ba%00r", "/foo/ba%2500r");
  85. }
  86. }
  87. #[test]
  88. #[cfg(unix)]
  89. fn new_path_bad_utf8() {
  90. use std::ffi::OsStr;
  91. use std::os::unix::prelude::*;
  92. let url = Url::from_file_path(Path::new(OsStr::from_bytes(b"/foo/ba\x80r"))).unwrap();
  93. let os_str = OsStr::from_bytes(b"/foo/ba\x80r");
  94. assert_eq!(url.to_file_path(), Ok(PathBuf::from(os_str)));
  95. }
  96. #[test]
  97. fn new_path_windows_fun() {
  98. if cfg!(windows) {
  99. assert_from_file_path!(r"C:\foo\bar", "/C:/foo/bar");
  100. assert_from_file_path!("C:\\foo\\ba\0r", "/C:/foo/ba%00r");
  101. // Invalid UTF-8
  102. assert!(Url::parse("file:///C:/foo/ba%80r")
  103. .unwrap()
  104. .to_file_path()
  105. .is_err());
  106. // test windows canonicalized path
  107. let path = PathBuf::from(r"\\?\C:\foo\bar");
  108. assert!(Url::from_file_path(path).is_ok());
  109. // Percent-encoded drive letter
  110. let url = Url::parse("file:///C%3A/foo/bar").unwrap();
  111. assert_eq!(url.to_file_path(), Ok(PathBuf::from(r"C:\foo\bar")));
  112. }
  113. }
  114. #[test]
  115. fn new_directory_paths() {
  116. if cfg!(unix) {
  117. assert_eq!(Url::from_directory_path(Path::new("relative")), Err(()));
  118. assert_eq!(Url::from_directory_path(Path::new("../relative")), Err(()));
  119. let url = Url::from_directory_path(Path::new("/foo/bar")).unwrap();
  120. assert_eq!(url.host(), None);
  121. assert_eq!(url.path(), "/foo/bar/");
  122. }
  123. if cfg!(windows) {
  124. assert_eq!(Url::from_directory_path(Path::new("relative")), Err(()));
  125. assert_eq!(Url::from_directory_path(Path::new(r"..\relative")), Err(()));
  126. assert_eq!(
  127. Url::from_directory_path(Path::new(r"\drive-relative")),
  128. Err(())
  129. );
  130. assert_eq!(Url::from_directory_path(Path::new(r"\\ucn\")), Err(()));
  131. let url = Url::from_directory_path(Path::new(r"C:\foo\bar")).unwrap();
  132. assert_eq!(url.host(), None);
  133. assert_eq!(url.path(), "/C:/foo/bar/");
  134. }
  135. }
  136. #[test]
  137. fn path_backslash_fun() {
  138. let mut special_url = "http://foobar.com".parse::<Url>().unwrap();
  139. special_url.path_segments_mut().unwrap().push("foo\\bar");
  140. assert_eq!(special_url.as_str(), "http://foobar.com/foo%5Cbar");
  141. let mut nonspecial_url = "thing://foobar.com".parse::<Url>().unwrap();
  142. nonspecial_url.path_segments_mut().unwrap().push("foo\\bar");
  143. assert_eq!(nonspecial_url.as_str(), "thing://foobar.com/foo\\bar");
  144. }
  145. #[test]
  146. fn from_str() {
  147. assert!("http://testing.com/this".parse::<Url>().is_ok());
  148. }
  149. #[test]
  150. fn parse_with_params() {
  151. let url = Url::parse_with_params(
  152. "http://testing.com/this?dont=clobberme",
  153. &[("lang", "rust")],
  154. )
  155. .unwrap();
  156. assert_eq!(
  157. url.as_str(),
  158. "http://testing.com/this?dont=clobberme&lang=rust"
  159. );
  160. }
  161. #[test]
  162. fn issue_124() {
  163. let url: Url = "file:a".parse().unwrap();
  164. assert_eq!(url.path(), "/a");
  165. let url: Url = "file:...".parse().unwrap();
  166. assert_eq!(url.path(), "/...");
  167. let url: Url = "file:..".parse().unwrap();
  168. assert_eq!(url.path(), "/");
  169. }
  170. #[test]
  171. fn test_equality() {
  172. use std::collections::hash_map::DefaultHasher;
  173. use std::hash::{Hash, Hasher};
  174. fn check_eq(a: &Url, b: &Url) {
  175. assert_eq!(a, b);
  176. let mut h1 = DefaultHasher::new();
  177. a.hash(&mut h1);
  178. let mut h2 = DefaultHasher::new();
  179. b.hash(&mut h2);
  180. assert_eq!(h1.finish(), h2.finish());
  181. }
  182. fn url(s: &str) -> Url {
  183. let rv = s.parse().unwrap();
  184. check_eq(&rv, &rv);
  185. rv
  186. }
  187. // Doesn't care if default port is given.
  188. let a: Url = url("https://example.com/");
  189. let b: Url = url("https://example.com:443/");
  190. check_eq(&a, &b);
  191. // Different ports
  192. let a: Url = url("http://example.com/");
  193. let b: Url = url("http://example.com:8080/");
  194. assert!(a != b, "{:?} != {:?}", a, b);
  195. // Different scheme
  196. let a: Url = url("http://example.com/");
  197. let b: Url = url("https://example.com/");
  198. assert_ne!(a, b);
  199. // Different host
  200. let a: Url = url("http://foo.com/");
  201. let b: Url = url("http://bar.com/");
  202. assert_ne!(a, b);
  203. // Missing path, automatically substituted. Semantically the same.
  204. let a: Url = url("http://foo.com");
  205. let b: Url = url("http://foo.com/");
  206. check_eq(&a, &b);
  207. }
  208. #[test]
  209. fn host() {
  210. fn assert_host(input: &str, host: Host<&str>) {
  211. assert_eq!(Url::parse(input).unwrap().host(), Some(host));
  212. }
  213. assert_host("http://www.mozilla.org", Host::Domain("www.mozilla.org"));
  214. assert_host(
  215. "http://1.35.33.49",
  216. Host::Ipv4(Ipv4Addr::new(1, 35, 33, 49)),
  217. );
  218. assert_host(
  219. "http://[2001:0db8:85a3:08d3:1319:8a2e:0370:7344]",
  220. Host::Ipv6(Ipv6Addr::new(
  221. 0x2001, 0x0db8, 0x85a3, 0x08d3, 0x1319, 0x8a2e, 0x0370, 0x7344,
  222. )),
  223. );
  224. assert_host("http://1.35.+33.49", Host::Domain("1.35.+33.49"));
  225. assert_host(
  226. "http://[::]",
  227. Host::Ipv6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)),
  228. );
  229. assert_host(
  230. "http://[::1]",
  231. Host::Ipv6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)),
  232. );
  233. assert_host(
  234. "http://0x1.0X23.0x21.061",
  235. Host::Ipv4(Ipv4Addr::new(1, 35, 33, 49)),
  236. );
  237. assert_host("http://0x1232131", Host::Ipv4(Ipv4Addr::new(1, 35, 33, 49)));
  238. assert_host("http://111", Host::Ipv4(Ipv4Addr::new(0, 0, 0, 111)));
  239. assert_host("http://2..2.3", Host::Domain("2..2.3"));
  240. assert!(Url::parse("http://42.0x1232131").is_err());
  241. assert!(Url::parse("http://192.168.0.257").is_err());
  242. assert_eq!(Host::Domain("foo"), Host::Domain("foo").to_owned());
  243. assert_ne!(Host::Domain("foo"), Host::Domain("bar").to_owned());
  244. }
  245. #[test]
  246. fn host_serialization() {
  247. // libstd’s `Display for Ipv6Addr` serializes 0:0:0:0:0:0:_:_ and 0:0:0:0:0:ffff:_:_
  248. // using IPv4-like syntax, as suggested in https://tools.ietf.org/html/rfc5952#section-4
  249. // but https://url.spec.whatwg.org/#concept-ipv6-serializer specifies not to.
  250. // Not [::0.0.0.2] / [::ffff:0.0.0.2]
  251. assert_eq!(
  252. Url::parse("http://[0::2]").unwrap().host_str(),
  253. Some("[::2]")
  254. );
  255. assert_eq!(
  256. Url::parse("http://[0::ffff:0:2]").unwrap().host_str(),
  257. Some("[::ffff:0:2]")
  258. );
  259. }
  260. #[test]
  261. fn test_idna() {
  262. assert!("http://goșu.ro".parse::<Url>().is_ok());
  263. assert_eq!(
  264. Url::parse("http://☃.net/").unwrap().host(),
  265. Some(Host::Domain("xn--n3h.net"))
  266. );
  267. assert!("https://r2---sn-huoa-cvhl.googlevideo.com/crossdomain.xml"
  268. .parse::<Url>()
  269. .is_ok());
  270. }
  271. #[test]
  272. fn test_serialization() {
  273. let data = [
  274. ("http://example.com/", "http://example.com/"),
  275. ("http://addslash.com", "http://addslash.com/"),
  276. ("http://@emptyuser.com/", "http://emptyuser.com/"),
  277. ("http://:@emptypass.com/", "http://emptypass.com/"),
  278. ("http://user@user.com/", "http://user@user.com/"),
  279. (
  280. "http://user:pass@userpass.com/",
  281. "http://user:pass@userpass.com/",
  282. ),
  283. (
  284. "http://slashquery.com/path/?q=something",
  285. "http://slashquery.com/path/?q=something",
  286. ),
  287. (
  288. "http://noslashquery.com/path?q=something",
  289. "http://noslashquery.com/path?q=something",
  290. ),
  291. ];
  292. for &(input, result) in &data {
  293. let url = Url::parse(input).unwrap();
  294. assert_eq!(url.as_str(), result);
  295. }
  296. }
  297. #[test]
  298. fn test_form_urlencoded() {
  299. let pairs: &[(Cow<'_, str>, Cow<'_, str>)] = &[
  300. ("foo".into(), "é&".into()),
  301. ("bar".into(), "".into()),
  302. ("foo".into(), "#".into()),
  303. ];
  304. let encoded = form_urlencoded::Serializer::new(String::new())
  305. .extend_pairs(pairs)
  306. .finish();
  307. assert_eq!(encoded, "foo=%C3%A9%26&bar=&foo=%23");
  308. assert_eq!(
  309. form_urlencoded::parse(encoded.as_bytes()).collect::<Vec<_>>(),
  310. pairs.to_vec()
  311. );
  312. }
  313. #[test]
  314. fn test_form_serialize() {
  315. let encoded = form_urlencoded::Serializer::new(String::new())
  316. .append_pair("foo", "é&")
  317. .append_pair("bar", "")
  318. .append_pair("foo", "#")
  319. .append_key_only("json")
  320. .finish();
  321. assert_eq!(encoded, "foo=%C3%A9%26&bar=&foo=%23&json");
  322. }
  323. #[test]
  324. fn form_urlencoded_encoding_override() {
  325. let encoded = form_urlencoded::Serializer::new(String::new())
  326. .encoding_override(Some(&|s| s.as_bytes().to_ascii_uppercase().into()))
  327. .append_pair("foo", "bar")
  328. .append_key_only("xml")
  329. .finish();
  330. assert_eq!(encoded, "FOO=BAR&XML");
  331. }
  332. #[test]
  333. /// https://github.com/servo/rust-url/issues/61
  334. fn issue_61() {
  335. let mut url = Url::parse("http://mozilla.org").unwrap();
  336. url.set_scheme("https").unwrap();
  337. assert_eq!(url.port(), None);
  338. assert_eq!(url.port_or_known_default(), Some(443));
  339. url.check_invariants().unwrap();
  340. }
  341. #[test]
  342. #[cfg(not(windows))]
  343. /// https://github.com/servo/rust-url/issues/197
  344. fn issue_197() {
  345. let mut url = Url::from_file_path("/").expect("Failed to parse path");
  346. url.check_invariants().unwrap();
  347. assert_eq!(
  348. url,
  349. Url::parse("file:///").expect("Failed to parse path + protocol")
  350. );
  351. url.path_segments_mut()
  352. .expect("path_segments_mut")
  353. .pop_if_empty();
  354. }
  355. #[test]
  356. fn issue_241() {
  357. Url::parse("mailto:").unwrap().cannot_be_a_base();
  358. }
  359. #[test]
  360. /// https://github.com/servo/rust-url/issues/222
  361. fn append_trailing_slash() {
  362. let mut url: Url = "http://localhost:6767/foo/bar?a=b".parse().unwrap();
  363. url.check_invariants().unwrap();
  364. url.path_segments_mut().unwrap().push("");
  365. url.check_invariants().unwrap();
  366. assert_eq!(url.to_string(), "http://localhost:6767/foo/bar/?a=b");
  367. }
  368. #[test]
  369. /// https://github.com/servo/rust-url/issues/227
  370. fn extend_query_pairs_then_mutate() {
  371. let mut url: Url = "http://localhost:6767/foo/bar".parse().unwrap();
  372. url.query_pairs_mut()
  373. .extend_pairs(vec![("auth", "my-token")].into_iter());
  374. url.check_invariants().unwrap();
  375. assert_eq!(
  376. url.to_string(),
  377. "http://localhost:6767/foo/bar?auth=my-token"
  378. );
  379. url.path_segments_mut().unwrap().push("some_other_path");
  380. url.check_invariants().unwrap();
  381. assert_eq!(
  382. url.to_string(),
  383. "http://localhost:6767/foo/bar/some_other_path?auth=my-token"
  384. );
  385. }
  386. #[test]
  387. /// https://github.com/servo/rust-url/issues/222
  388. fn append_empty_segment_then_mutate() {
  389. let mut url: Url = "http://localhost:6767/foo/bar?a=b".parse().unwrap();
  390. url.check_invariants().unwrap();
  391. url.path_segments_mut().unwrap().push("").pop();
  392. url.check_invariants().unwrap();
  393. assert_eq!(url.to_string(), "http://localhost:6767/foo/bar?a=b");
  394. }
  395. #[test]
  396. /// https://github.com/servo/rust-url/issues/243
  397. fn test_set_host() {
  398. let mut url = Url::parse("https://example.net/hello").unwrap();
  399. url.set_host(Some("foo.com")).unwrap();
  400. assert_eq!(url.as_str(), "https://foo.com/hello");
  401. assert!(url.set_host(None).is_err());
  402. assert_eq!(url.as_str(), "https://foo.com/hello");
  403. assert!(url.set_host(Some("")).is_err());
  404. assert_eq!(url.as_str(), "https://foo.com/hello");
  405. let mut url = Url::parse("foobar://example.net/hello").unwrap();
  406. url.set_host(None).unwrap();
  407. assert_eq!(url.as_str(), "foobar:/hello");
  408. let mut url = Url::parse("foo://ș").unwrap();
  409. assert_eq!(url.as_str(), "foo://%C8%99");
  410. url.set_host(Some("goșu.ro")).unwrap();
  411. assert_eq!(url.as_str(), "foo://go%C8%99u.ro");
  412. }
  413. #[test]
  414. // https://github.com/servo/rust-url/issues/166
  415. fn test_leading_dots() {
  416. assert_eq!(
  417. Host::parse(".org").unwrap(),
  418. Host::Domain(".org".to_owned())
  419. );
  420. assert_eq!(Url::parse("file://./foo").unwrap().domain(), Some("."));
  421. }
  422. #[test]
  423. /// https://github.com/servo/rust-url/issues/302
  424. fn test_origin_hash() {
  425. use std::collections::hash_map::DefaultHasher;
  426. use std::hash::{Hash, Hasher};
  427. fn hash<T: Hash>(value: &T) -> u64 {
  428. let mut hasher = DefaultHasher::new();
  429. value.hash(&mut hasher);
  430. hasher.finish()
  431. }
  432. let origin = &Url::parse("http://example.net/").unwrap().origin();
  433. let origins_to_compare = [
  434. Url::parse("http://example.net:80/").unwrap().origin(),
  435. Url::parse("http://example.net:81/").unwrap().origin(),
  436. Url::parse("http://example.net").unwrap().origin(),
  437. Url::parse("http://example.net/hello").unwrap().origin(),
  438. Url::parse("https://example.net").unwrap().origin(),
  439. Url::parse("ftp://example.net").unwrap().origin(),
  440. Url::parse("file://example.net").unwrap().origin(),
  441. Url::parse("http://user@example.net/").unwrap().origin(),
  442. Url::parse("http://user:pass@example.net/")
  443. .unwrap()
  444. .origin(),
  445. ];
  446. for origin_to_compare in &origins_to_compare {
  447. if origin == origin_to_compare {
  448. assert_eq!(hash(origin), hash(origin_to_compare));
  449. } else {
  450. assert_ne!(hash(origin), hash(origin_to_compare));
  451. }
  452. }
  453. let opaque_origin = Url::parse("file://example.net").unwrap().origin();
  454. let same_opaque_origin = Url::parse("file://example.net").unwrap().origin();
  455. let other_opaque_origin = Url::parse("file://other").unwrap().origin();
  456. assert_ne!(hash(&opaque_origin), hash(&same_opaque_origin));
  457. assert_ne!(hash(&opaque_origin), hash(&other_opaque_origin));
  458. }
  459. #[test]
  460. fn test_origin_blob_equality() {
  461. let origin = &Url::parse("http://example.net/").unwrap().origin();
  462. let blob_origin = &Url::parse("blob:http://example.net/").unwrap().origin();
  463. assert_eq!(origin, blob_origin);
  464. }
  465. #[test]
  466. fn test_origin_opaque() {
  467. assert!(!Origin::new_opaque().is_tuple());
  468. assert!(!&Url::parse("blob:malformed//").unwrap().origin().is_tuple())
  469. }
  470. #[test]
  471. fn test_origin_unicode_serialization() {
  472. let data = [
  473. ("http://😅.com", "http://😅.com"),
  474. ("ftp://😅:🙂@🙂.com", "ftp://🙂.com"),
  475. ("https://user@😅.com", "https://😅.com"),
  476. ("http://😅.🙂:40", "http://😅.🙂:40"),
  477. ];
  478. for &(unicode_url, expected_serialization) in &data {
  479. let origin = Url::parse(unicode_url).unwrap().origin();
  480. assert_eq!(origin.unicode_serialization(), *expected_serialization);
  481. }
  482. let ascii_origins = [
  483. Url::parse("http://example.net/").unwrap().origin(),
  484. Url::parse("http://example.net:80/").unwrap().origin(),
  485. Url::parse("http://example.net:81/").unwrap().origin(),
  486. Url::parse("http://example.net").unwrap().origin(),
  487. Url::parse("http://example.net/hello").unwrap().origin(),
  488. Url::parse("https://example.net").unwrap().origin(),
  489. Url::parse("ftp://example.net").unwrap().origin(),
  490. Url::parse("file://example.net").unwrap().origin(),
  491. Url::parse("http://user@example.net/").unwrap().origin(),
  492. Url::parse("http://user:pass@example.net/")
  493. .unwrap()
  494. .origin(),
  495. Url::parse("http://127.0.0.1").unwrap().origin(),
  496. ];
  497. for ascii_origin in &ascii_origins {
  498. assert_eq!(
  499. ascii_origin.ascii_serialization(),
  500. ascii_origin.unicode_serialization()
  501. );
  502. }
  503. }
  504. #[test]
  505. fn test_socket_addrs() {
  506. use std::net::ToSocketAddrs;
  507. let data = [
  508. ("https://127.0.0.1/", "127.0.0.1", 443),
  509. ("https://127.0.0.1:9742/", "127.0.0.1", 9742),
  510. ("custom-protocol://127.0.0.1:9742/", "127.0.0.1", 9742),
  511. ("custom-protocol://127.0.0.1/", "127.0.0.1", 9743),
  512. ("https://[::1]/", "::1", 443),
  513. ("https://[::1]:9742/", "::1", 9742),
  514. ("custom-protocol://[::1]:9742/", "::1", 9742),
  515. ("custom-protocol://[::1]/", "::1", 9743),
  516. ("https://localhost/", "localhost", 443),
  517. ("https://localhost:9742/", "localhost", 9742),
  518. ("custom-protocol://localhost:9742/", "localhost", 9742),
  519. ("custom-protocol://localhost/", "localhost", 9743),
  520. ];
  521. for (url_string, host, port) in &data {
  522. let url = url::Url::parse(url_string).unwrap();
  523. let addrs = url
  524. .socket_addrs(|| match url.scheme() {
  525. "custom-protocol" => Some(9743),
  526. _ => None,
  527. })
  528. .unwrap();
  529. assert_eq!(
  530. Some(addrs[0]),
  531. (*host, *port).to_socket_addrs().unwrap().next()
  532. );
  533. }
  534. }
  535. #[test]
  536. fn test_no_base_url() {
  537. let mut no_base_url = Url::parse("mailto:test@example.net").unwrap();
  538. assert!(no_base_url.cannot_be_a_base());
  539. assert!(no_base_url.path_segments().is_none());
  540. assert!(no_base_url.path_segments_mut().is_err());
  541. assert!(no_base_url.set_host(Some("foo")).is_err());
  542. assert!(no_base_url
  543. .set_ip_host("127.0.0.1".parse().unwrap())
  544. .is_err());
  545. no_base_url.set_path("/foo");
  546. assert_eq!(no_base_url.path(), "%2Ffoo");
  547. }
  548. #[test]
  549. fn test_domain() {
  550. let url = Url::parse("https://127.0.0.1/").unwrap();
  551. assert_eq!(url.domain(), None);
  552. let url = Url::parse("mailto:test@example.net").unwrap();
  553. assert_eq!(url.domain(), None);
  554. let url = Url::parse("https://example.com/").unwrap();
  555. assert_eq!(url.domain(), Some("example.com"));
  556. }
  557. #[test]
  558. fn test_query() {
  559. let url = Url::parse("https://example.com/products?page=2#fragment").unwrap();
  560. assert_eq!(url.query(), Some("page=2"));
  561. assert_eq!(
  562. url.query_pairs().next(),
  563. Some((Cow::Borrowed("page"), Cow::Borrowed("2")))
  564. );
  565. let url = Url::parse("https://example.com/products").unwrap();
  566. assert!(url.query().is_none());
  567. assert_eq!(url.query_pairs().count(), 0);
  568. let url = Url::parse("https://example.com/?country=español").unwrap();
  569. assert_eq!(url.query(), Some("country=espa%C3%B1ol"));
  570. assert_eq!(
  571. url.query_pairs().next(),
  572. Some((Cow::Borrowed("country"), Cow::Borrowed("español")))
  573. );
  574. let url = Url::parse("https://example.com/products?page=2&sort=desc").unwrap();
  575. assert_eq!(url.query(), Some("page=2&sort=desc"));
  576. let mut pairs = url.query_pairs();
  577. assert_eq!(pairs.count(), 2);
  578. assert_eq!(
  579. pairs.next(),
  580. Some((Cow::Borrowed("page"), Cow::Borrowed("2")))
  581. );
  582. assert_eq!(
  583. pairs.next(),
  584. Some((Cow::Borrowed("sort"), Cow::Borrowed("desc")))
  585. );
  586. }
  587. #[test]
  588. fn test_fragment() {
  589. let url = Url::parse("https://example.com/#fragment").unwrap();
  590. assert_eq!(url.fragment(), Some("fragment"));
  591. let url = Url::parse("https://example.com/").unwrap();
  592. assert_eq!(url.fragment(), None);
  593. }
  594. #[test]
  595. fn test_set_ip_host() {
  596. let mut url = Url::parse("http://example.com").unwrap();
  597. url.set_ip_host("127.0.0.1".parse().unwrap()).unwrap();
  598. assert_eq!(url.host_str(), Some("127.0.0.1"));
  599. url.set_ip_host("::1".parse().unwrap()).unwrap();
  600. assert_eq!(url.host_str(), Some("[::1]"));
  601. }
  602. #[test]
  603. fn test_set_href() {
  604. use url::quirks::set_href;
  605. let mut url = Url::parse("https://existing.url").unwrap();
  606. assert!(set_href(&mut url, "mal//formed").is_err());
  607. assert!(set_href(
  608. &mut url,
  609. "https://user:pass@domain.com:9742/path/file.ext?key=val&key2=val2#fragment"
  610. )
  611. .is_ok());
  612. assert_eq!(
  613. url,
  614. Url::parse("https://user:pass@domain.com:9742/path/file.ext?key=val&key2=val2#fragment")
  615. .unwrap()
  616. );
  617. }
  618. #[cfg(feature = "idna")]
  619. #[test]
  620. fn test_domain_encoding_quirks() {
  621. use url::quirks::{domain_to_ascii, domain_to_unicode};
  622. let data = [
  623. ("http://example.com", "", ""),
  624. ("😅.🙂", "xn--j28h.xn--938h", "😅.🙂"),
  625. ("example.com", "example.com", "example.com"),
  626. ("mailto:test@example.net", "", ""),
  627. ];
  628. for url in &data {
  629. assert_eq!(domain_to_ascii(url.0), url.1);
  630. assert_eq!(domain_to_unicode(url.0), url.2);
  631. }
  632. }
  633. #[test]
  634. fn test_windows_unc_path() {
  635. if !cfg!(windows) {
  636. return;
  637. }
  638. let url = Url::from_file_path(Path::new(r"\\host\share\path\file.txt")).unwrap();
  639. assert_eq!(url.as_str(), "file://host/share/path/file.txt");
  640. let url = Url::from_file_path(Path::new(r"\\höst\share\path\file.txt")).unwrap();
  641. assert_eq!(url.as_str(), "file://xn--hst-sna/share/path/file.txt");
  642. let url = Url::from_file_path(Path::new(r"\\192.168.0.1\share\path\file.txt")).unwrap();
  643. assert_eq!(url.host(), Some(Host::Ipv4(Ipv4Addr::new(192, 168, 0, 1))));
  644. let path = url.to_file_path().unwrap();
  645. assert_eq!(path.to_str(), Some(r"\\192.168.0.1\share\path\file.txt"));
  646. // Another way to write these:
  647. let url = Url::from_file_path(Path::new(r"\\?\UNC\host\share\path\file.txt")).unwrap();
  648. assert_eq!(url.as_str(), "file://host/share/path/file.txt");
  649. // Paths starting with "\\.\" (Local Device Paths) are intentionally not supported.
  650. let url = Url::from_file_path(Path::new(r"\\.\some\path\file.txt"));
  651. assert!(url.is_err());
  652. }
  653. #[test]
  654. fn test_syntax_violation_callback() {
  655. use url::SyntaxViolation::*;
  656. let violation = Cell::new(None);
  657. let url = Url::options()
  658. .syntax_violation_callback(Some(&|v| violation.set(Some(v))))
  659. .parse("http:////mozilla.org:42")
  660. .unwrap();
  661. assert_eq!(url.port(), Some(42));
  662. let v = violation.take().unwrap();
  663. assert_eq!(v, ExpectedDoubleSlash);
  664. assert_eq!(v.description(), "expected //");
  665. assert_eq!(v.to_string(), "expected //");
  666. }
  667. #[test]
  668. fn test_syntax_violation_callback_lifetimes() {
  669. use url::SyntaxViolation::*;
  670. let violation = Cell::new(None);
  671. let vfn = |s| violation.set(Some(s));
  672. let url = Url::options()
  673. .syntax_violation_callback(Some(&vfn))
  674. .parse("http:////mozilla.org:42")
  675. .unwrap();
  676. assert_eq!(url.port(), Some(42));
  677. assert_eq!(violation.take(), Some(ExpectedDoubleSlash));
  678. let url = Url::options()
  679. .syntax_violation_callback(Some(&vfn))
  680. .parse("http://mozilla.org\\path")
  681. .unwrap();
  682. assert_eq!(url.path(), "/path");
  683. assert_eq!(violation.take(), Some(Backslash));
  684. }
  685. #[test]
  686. fn test_syntax_violation_callback_types() {
  687. use url::SyntaxViolation::*;
  688. let data = [
  689. ("http://mozilla.org/\\foo", Backslash, "backslash"),
  690. (" http://mozilla.org", C0SpaceIgnored, "leading or trailing control or space character are ignored in URLs"),
  691. ("http://user:pass@mozilla.org", EmbeddedCredentials, "embedding authentication information (username or password) in an URL is not recommended"),
  692. ("http:///mozilla.org", ExpectedDoubleSlash, "expected //"),
  693. ("file:/foo.txt", ExpectedFileDoubleSlash, "expected // after file:"),
  694. ("file://mozilla.org/c:/file.txt", FileWithHostAndWindowsDrive, "file: with host and Windows drive letter"),
  695. ("http://mozilla.org/^", NonUrlCodePoint, "non-URL code point"),
  696. ("http://mozilla.org/#\00", NullInFragment, "NULL characters are ignored in URL fragment identifiers"),
  697. ("http://mozilla.org/%1", PercentDecode, "expected 2 hex digits after %"),
  698. ("http://mozilla.org\t/foo", TabOrNewlineIgnored, "tabs or newlines are ignored in URLs"),
  699. ("http://user@:pass@mozilla.org", UnencodedAtSign, "unencoded @ sign in username or password")
  700. ];
  701. for test_case in &data {
  702. let violation = Cell::new(None);
  703. Url::options()
  704. .syntax_violation_callback(Some(&|v| violation.set(Some(v))))
  705. .parse(test_case.0)
  706. .unwrap();
  707. let v = violation.take();
  708. assert_eq!(v, Some(test_case.1));
  709. assert_eq!(v.unwrap().description(), test_case.2);
  710. assert_eq!(v.unwrap().to_string(), test_case.2);
  711. }
  712. }
  713. #[test]
  714. fn test_options_reuse() {
  715. use url::SyntaxViolation::*;
  716. let violations = RefCell::new(Vec::new());
  717. let vfn = |v| violations.borrow_mut().push(v);
  718. let options = Url::options().syntax_violation_callback(Some(&vfn));
  719. let url = options.parse("http:////mozilla.org").unwrap();
  720. let options = options.base_url(Some(&url));
  721. let url = options.parse("/sub\\path").unwrap();
  722. assert_eq!(url.as_str(), "http://mozilla.org/sub/path");
  723. assert_eq!(*violations.borrow(), vec!(ExpectedDoubleSlash, Backslash));
  724. }
  725. /// https://github.com/servo/rust-url/issues/505
  726. #[cfg(windows)]
  727. #[test]
  728. fn test_url_from_file_path() {
  729. use std::path::PathBuf;
  730. use url::Url;
  731. let p = PathBuf::from("c:///");
  732. let u = Url::from_file_path(p).unwrap();
  733. let path = u.to_file_path().unwrap();
  734. assert_eq!("C:\\", path.to_str().unwrap());
  735. }
  736. /// https://github.com/servo/rust-url/issues/505
  737. #[cfg(not(windows))]
  738. #[test]
  739. fn test_url_from_file_path() {
  740. use std::path::PathBuf;
  741. use url::Url;
  742. let p = PathBuf::from("/c:/");
  743. let u = Url::from_file_path(p).unwrap();
  744. let path = u.to_file_path().unwrap();
  745. assert_eq!("/c:/", path.to_str().unwrap());
  746. }
  747. #[test]
  748. fn test_non_special_path() {
  749. let mut db_url = url::Url::parse("postgres://postgres@localhost/").unwrap();
  750. assert_eq!(db_url.as_str(), "postgres://postgres@localhost/");
  751. db_url.set_path("diesel_foo");
  752. assert_eq!(db_url.as_str(), "postgres://postgres@localhost/diesel_foo");
  753. assert_eq!(db_url.path(), "/diesel_foo");
  754. }
  755. #[test]
  756. fn test_non_special_path2() {
  757. let mut db_url = url::Url::parse("postgres://postgres@localhost/").unwrap();
  758. assert_eq!(db_url.as_str(), "postgres://postgres@localhost/");
  759. db_url.set_path("");
  760. assert_eq!(db_url.path(), "");
  761. assert_eq!(db_url.as_str(), "postgres://postgres@localhost");
  762. db_url.set_path("foo");
  763. assert_eq!(db_url.path(), "/foo");
  764. assert_eq!(db_url.as_str(), "postgres://postgres@localhost/foo");
  765. db_url.set_path("/bar");
  766. assert_eq!(db_url.path(), "/bar");
  767. assert_eq!(db_url.as_str(), "postgres://postgres@localhost/bar");
  768. }
  769. #[test]
  770. fn test_non_special_path3() {
  771. let mut db_url = url::Url::parse("postgres://postgres@localhost/").unwrap();
  772. assert_eq!(db_url.as_str(), "postgres://postgres@localhost/");
  773. db_url.set_path("/");
  774. assert_eq!(db_url.as_str(), "postgres://postgres@localhost/");
  775. assert_eq!(db_url.path(), "/");
  776. db_url.set_path("/foo");
  777. assert_eq!(db_url.as_str(), "postgres://postgres@localhost/foo");
  778. assert_eq!(db_url.path(), "/foo");
  779. }
  780. #[test]
  781. fn test_set_scheme_to_file_with_host() {
  782. let mut url: Url = "http://localhost:6767/foo/bar".parse().unwrap();
  783. let result = url.set_scheme("file");
  784. assert_eq!(url.to_string(), "http://localhost:6767/foo/bar");
  785. assert_eq!(result, Err(()));
  786. }
  787. #[test]
  788. fn no_panic() {
  789. let mut url = Url::parse("arhttpsps:/.//eom/dae.com/\\\\t\\:").unwrap();
  790. url::quirks::set_hostname(&mut url, "//eom/datcom/\\\\t\\://eom/data.cs").unwrap();
  791. }
  792. #[test]
  793. fn pop_if_empty_in_bounds() {
  794. let mut url = Url::parse("m://").unwrap();
  795. let mut segments = url.path_segments_mut().unwrap();
  796. segments.pop_if_empty();
  797. segments.pop();
  798. }
  799. #[test]
  800. fn test_slicing() {
  801. use url::Position::*;
  802. #[derive(Default)]
  803. struct ExpectedSlices<'a> {
  804. full: &'a str,
  805. scheme: &'a str,
  806. username: &'a str,
  807. password: &'a str,
  808. host: &'a str,
  809. port: &'a str,
  810. path: &'a str,
  811. query: &'a str,
  812. fragment: &'a str,
  813. }
  814. let data = [
  815. ExpectedSlices {
  816. full: "https://user:pass@domain.com:9742/path/file.ext?key=val&key2=val2#fragment",
  817. scheme: "https",
  818. username: "user",
  819. password: "pass",
  820. host: "domain.com",
  821. port: "9742",
  822. path: "/path/file.ext",
  823. query: "key=val&key2=val2",
  824. fragment: "fragment",
  825. },
  826. ExpectedSlices {
  827. full: "https://domain.com:9742/path/file.ext#fragment",
  828. scheme: "https",
  829. host: "domain.com",
  830. port: "9742",
  831. path: "/path/file.ext",
  832. fragment: "fragment",
  833. ..Default::default()
  834. },
  835. ExpectedSlices {
  836. full: "https://domain.com:9742/path/file.ext",
  837. scheme: "https",
  838. host: "domain.com",
  839. port: "9742",
  840. path: "/path/file.ext",
  841. ..Default::default()
  842. },
  843. ExpectedSlices {
  844. full: "blob:blob-info",
  845. scheme: "blob",
  846. path: "blob-info",
  847. ..Default::default()
  848. },
  849. ];
  850. for expected_slices in &data {
  851. let url = Url::parse(expected_slices.full).unwrap();
  852. assert_eq!(&url[..], expected_slices.full);
  853. assert_eq!(&url[BeforeScheme..AfterScheme], expected_slices.scheme);
  854. assert_eq!(
  855. &url[BeforeUsername..AfterUsername],
  856. expected_slices.username
  857. );
  858. assert_eq!(
  859. &url[BeforePassword..AfterPassword],
  860. expected_slices.password
  861. );
  862. assert_eq!(&url[BeforeHost..AfterHost], expected_slices.host);
  863. assert_eq!(&url[BeforePort..AfterPort], expected_slices.port);
  864. assert_eq!(&url[BeforePath..AfterPath], expected_slices.path);
  865. assert_eq!(&url[BeforeQuery..AfterQuery], expected_slices.query);
  866. assert_eq!(
  867. &url[BeforeFragment..AfterFragment],
  868. expected_slices.fragment
  869. );
  870. assert_eq!(&url[..AfterFragment], expected_slices.full);
  871. }
  872. }
  873. #[test]
  874. fn test_make_relative() {
  875. let tests = [
  876. (
  877. "http://127.0.0.1:8080/test",
  878. "http://127.0.0.1:8080/test",
  879. "",
  880. ),
  881. (
  882. "http://127.0.0.1:8080/test",
  883. "http://127.0.0.1:8080/test/",
  884. "test/",
  885. ),
  886. (
  887. "http://127.0.0.1:8080/test/",
  888. "http://127.0.0.1:8080/test",
  889. "../test",
  890. ),
  891. (
  892. "http://127.0.0.1:8080/",
  893. "http://127.0.0.1:8080/?foo=bar#123",
  894. "?foo=bar#123",
  895. ),
  896. (
  897. "http://127.0.0.1:8080/",
  898. "http://127.0.0.1:8080/test/video",
  899. "test/video",
  900. ),
  901. (
  902. "http://127.0.0.1:8080/test",
  903. "http://127.0.0.1:8080/test/video",
  904. "test/video",
  905. ),
  906. (
  907. "http://127.0.0.1:8080/test/",
  908. "http://127.0.0.1:8080/test/video",
  909. "video",
  910. ),
  911. (
  912. "http://127.0.0.1:8080/test",
  913. "http://127.0.0.1:8080/test2/video",
  914. "test2/video",
  915. ),
  916. (
  917. "http://127.0.0.1:8080/test/",
  918. "http://127.0.0.1:8080/test2/video",
  919. "../test2/video",
  920. ),
  921. (
  922. "http://127.0.0.1:8080/test/bla",
  923. "http://127.0.0.1:8080/test2/video",
  924. "../test2/video",
  925. ),
  926. (
  927. "http://127.0.0.1:8080/test/bla/",
  928. "http://127.0.0.1:8080/test2/video",
  929. "../../test2/video",
  930. ),
  931. (
  932. "http://127.0.0.1:8080/test/?foo=bar#123",
  933. "http://127.0.0.1:8080/test/video",
  934. "video",
  935. ),
  936. (
  937. "http://127.0.0.1:8080/test/",
  938. "http://127.0.0.1:8080/test/video?baz=meh#456",
  939. "video?baz=meh#456",
  940. ),
  941. (
  942. "http://127.0.0.1:8080/test",
  943. "http://127.0.0.1:8080/test?baz=meh#456",
  944. "?baz=meh#456",
  945. ),
  946. (
  947. "http://127.0.0.1:8080/test/",
  948. "http://127.0.0.1:8080/test?baz=meh#456",
  949. "../test?baz=meh#456",
  950. ),
  951. (
  952. "http://127.0.0.1:8080/test/",
  953. "http://127.0.0.1:8080/test/?baz=meh#456",
  954. "?baz=meh#456",
  955. ),
  956. (
  957. "http://127.0.0.1:8080/test/?foo=bar#123",
  958. "http://127.0.0.1:8080/test/video?baz=meh#456",
  959. "video?baz=meh#456",
  960. ),
  961. ];
  962. for (base, uri, relative) in &tests {
  963. let base_uri = url::Url::parse(base).unwrap();
  964. let relative_uri = url::Url::parse(uri).unwrap();
  965. let make_relative = base_uri.make_relative(&relative_uri).unwrap();
  966. assert_eq!(
  967. make_relative, *relative,
  968. "base: {}, uri: {}, relative: {}",
  969. base, uri, relative
  970. );
  971. assert_eq!(
  972. base_uri.join(&relative).unwrap().as_str(),
  973. *uri,
  974. "base: {}, uri: {}, relative: {}",
  975. base,
  976. uri,
  977. relative
  978. );
  979. }
  980. let error_tests = [
  981. ("http://127.0.0.1:8080/", "https://127.0.0.1:8080/test/"),
  982. ("http://127.0.0.1:8080/", "http://127.0.0.1:8081/test/"),
  983. ("http://127.0.0.1:8080/", "http://127.0.0.2:8080/test/"),
  984. ("mailto:a@example.com", "mailto:b@example.com"),
  985. ];
  986. for (base, uri) in &error_tests {
  987. let base_uri = url::Url::parse(base).unwrap();
  988. let relative_uri = url::Url::parse(uri).unwrap();
  989. let make_relative = base_uri.make_relative(&relative_uri);
  990. assert_eq!(make_relative, None, "base: {}, uri: {}", base, uri);
  991. }
  992. }