unit.rs 41 KB

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