unit.rs 41 KB

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