unit.rs 36 KB

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