unit.rs 42 KB

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