unit.rs 43 KB

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