unit.rs 39 KB

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