unit.rs 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164
  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. #[test]
  267. fn test_idna() {
  268. assert!("http://goșu.ro".parse::<Url>().is_ok());
  269. assert_eq!(
  270. Url::parse("http://☃.net/").unwrap().host(),
  271. Some(Host::Domain("xn--n3h.net"))
  272. );
  273. assert!("https://r2---sn-huoa-cvhl.googlevideo.com/crossdomain.xml"
  274. .parse::<Url>()
  275. .is_ok());
  276. }
  277. #[test]
  278. fn test_serialization() {
  279. let data = [
  280. ("http://example.com/", "http://example.com/"),
  281. ("http://addslash.com", "http://addslash.com/"),
  282. ("http://@emptyuser.com/", "http://emptyuser.com/"),
  283. ("http://:@emptypass.com/", "http://emptypass.com/"),
  284. ("http://user@user.com/", "http://user@user.com/"),
  285. (
  286. "http://user:pass@userpass.com/",
  287. "http://user:pass@userpass.com/",
  288. ),
  289. (
  290. "http://slashquery.com/path/?q=something",
  291. "http://slashquery.com/path/?q=something",
  292. ),
  293. (
  294. "http://noslashquery.com/path?q=something",
  295. "http://noslashquery.com/path?q=something",
  296. ),
  297. ];
  298. for &(input, result) in &data {
  299. let url = Url::parse(input).unwrap();
  300. assert_eq!(url.as_str(), result);
  301. }
  302. }
  303. #[test]
  304. fn test_form_urlencoded() {
  305. let pairs: &[(Cow<'_, str>, Cow<'_, str>)] = &[
  306. ("foo".into(), "é&".into()),
  307. ("bar".into(), "".into()),
  308. ("foo".into(), "#".into()),
  309. ];
  310. let encoded = form_urlencoded::Serializer::new(String::new())
  311. .extend_pairs(pairs)
  312. .finish();
  313. assert_eq!(encoded, "foo=%C3%A9%26&bar=&foo=%23");
  314. assert_eq!(
  315. form_urlencoded::parse(encoded.as_bytes()).collect::<Vec<_>>(),
  316. pairs.to_vec()
  317. );
  318. }
  319. #[test]
  320. fn test_form_serialize() {
  321. let encoded = form_urlencoded::Serializer::new(String::new())
  322. .append_pair("foo", "é&")
  323. .append_pair("bar", "")
  324. .append_pair("foo", "#")
  325. .append_key_only("json")
  326. .finish();
  327. assert_eq!(encoded, "foo=%C3%A9%26&bar=&foo=%23&json");
  328. }
  329. #[test]
  330. fn form_urlencoded_encoding_override() {
  331. let encoded = form_urlencoded::Serializer::new(String::new())
  332. .encoding_override(Some(&|s| s.as_bytes().to_ascii_uppercase().into()))
  333. .append_pair("foo", "bar")
  334. .append_key_only("xml")
  335. .finish();
  336. assert_eq!(encoded, "FOO=BAR&XML");
  337. }
  338. #[test]
  339. /// https://github.com/servo/rust-url/issues/61
  340. fn issue_61() {
  341. let mut url = Url::parse("http://mozilla.org").unwrap();
  342. url.set_scheme("https").unwrap();
  343. assert_eq!(url.port(), None);
  344. assert_eq!(url.port_or_known_default(), Some(443));
  345. url.check_invariants().unwrap();
  346. }
  347. #[test]
  348. #[cfg(not(windows))]
  349. /// https://github.com/servo/rust-url/issues/197
  350. fn issue_197() {
  351. let mut url = Url::from_file_path("/").expect("Failed to parse path");
  352. url.check_invariants().unwrap();
  353. assert_eq!(
  354. url,
  355. Url::parse("file:///").expect("Failed to parse path + protocol")
  356. );
  357. url.path_segments_mut()
  358. .expect("path_segments_mut")
  359. .pop_if_empty();
  360. }
  361. #[test]
  362. fn issue_241() {
  363. Url::parse("mailto:").unwrap().cannot_be_a_base();
  364. }
  365. #[test]
  366. /// https://github.com/servo/rust-url/issues/222
  367. fn append_trailing_slash() {
  368. let mut url: Url = "http://localhost:6767/foo/bar?a=b".parse().unwrap();
  369. url.check_invariants().unwrap();
  370. url.path_segments_mut().unwrap().push("");
  371. url.check_invariants().unwrap();
  372. assert_eq!(url.to_string(), "http://localhost:6767/foo/bar/?a=b");
  373. }
  374. #[test]
  375. /// https://github.com/servo/rust-url/issues/227
  376. fn extend_query_pairs_then_mutate() {
  377. let mut url: Url = "http://localhost:6767/foo/bar".parse().unwrap();
  378. url.query_pairs_mut()
  379. .extend_pairs(vec![("auth", "my-token")].into_iter());
  380. url.check_invariants().unwrap();
  381. assert_eq!(
  382. url.to_string(),
  383. "http://localhost:6767/foo/bar?auth=my-token"
  384. );
  385. url.path_segments_mut().unwrap().push("some_other_path");
  386. url.check_invariants().unwrap();
  387. assert_eq!(
  388. url.to_string(),
  389. "http://localhost:6767/foo/bar/some_other_path?auth=my-token"
  390. );
  391. }
  392. #[test]
  393. /// https://github.com/servo/rust-url/issues/222
  394. fn append_empty_segment_then_mutate() {
  395. let mut url: Url = "http://localhost:6767/foo/bar?a=b".parse().unwrap();
  396. url.check_invariants().unwrap();
  397. url.path_segments_mut().unwrap().push("").pop();
  398. url.check_invariants().unwrap();
  399. assert_eq!(url.to_string(), "http://localhost:6767/foo/bar?a=b");
  400. }
  401. #[test]
  402. /// https://github.com/servo/rust-url/issues/243
  403. fn test_set_host() {
  404. let mut url = Url::parse("https://example.net/hello").unwrap();
  405. url.set_host(Some("foo.com")).unwrap();
  406. assert_eq!(url.as_str(), "https://foo.com/hello");
  407. assert!(url.set_host(None).is_err());
  408. assert_eq!(url.as_str(), "https://foo.com/hello");
  409. assert!(url.set_host(Some("")).is_err());
  410. assert_eq!(url.as_str(), "https://foo.com/hello");
  411. let mut url = Url::parse("foobar://example.net/hello").unwrap();
  412. url.set_host(None).unwrap();
  413. assert_eq!(url.as_str(), "foobar:/hello");
  414. let mut url = Url::parse("foo://ș").unwrap();
  415. assert_eq!(url.as_str(), "foo://%C8%99");
  416. url.set_host(Some("goșu.ro")).unwrap();
  417. assert_eq!(url.as_str(), "foo://go%C8%99u.ro");
  418. }
  419. #[test]
  420. // https://github.com/servo/rust-url/issues/166
  421. fn test_leading_dots() {
  422. assert_eq!(
  423. Host::parse(".org").unwrap(),
  424. Host::Domain(".org".to_owned())
  425. );
  426. assert_eq!(Url::parse("file://./foo").unwrap().domain(), Some("."));
  427. }
  428. #[test]
  429. /// https://github.com/servo/rust-url/issues/302
  430. fn test_origin_hash() {
  431. use std::collections::hash_map::DefaultHasher;
  432. use std::hash::{Hash, Hasher};
  433. fn hash<T: Hash>(value: &T) -> u64 {
  434. let mut hasher = DefaultHasher::new();
  435. value.hash(&mut hasher);
  436. hasher.finish()
  437. }
  438. let origin = &Url::parse("http://example.net/").unwrap().origin();
  439. let origins_to_compare = [
  440. Url::parse("http://example.net:80/").unwrap().origin(),
  441. Url::parse("http://example.net:81/").unwrap().origin(),
  442. Url::parse("http://example.net").unwrap().origin(),
  443. Url::parse("http://example.net/hello").unwrap().origin(),
  444. Url::parse("https://example.net").unwrap().origin(),
  445. Url::parse("ftp://example.net").unwrap().origin(),
  446. Url::parse("file://example.net").unwrap().origin(),
  447. Url::parse("http://user@example.net/").unwrap().origin(),
  448. Url::parse("http://user:pass@example.net/")
  449. .unwrap()
  450. .origin(),
  451. ];
  452. for origin_to_compare in &origins_to_compare {
  453. if origin == origin_to_compare {
  454. assert_eq!(hash(origin), hash(origin_to_compare));
  455. } else {
  456. assert_ne!(hash(origin), hash(origin_to_compare));
  457. }
  458. }
  459. let opaque_origin = Url::parse("file://example.net").unwrap().origin();
  460. let same_opaque_origin = Url::parse("file://example.net").unwrap().origin();
  461. let other_opaque_origin = Url::parse("file://other").unwrap().origin();
  462. assert_ne!(hash(&opaque_origin), hash(&same_opaque_origin));
  463. assert_ne!(hash(&opaque_origin), hash(&other_opaque_origin));
  464. }
  465. #[test]
  466. fn test_origin_blob_equality() {
  467. let origin = &Url::parse("http://example.net/").unwrap().origin();
  468. let blob_origin = &Url::parse("blob:http://example.net/").unwrap().origin();
  469. assert_eq!(origin, blob_origin);
  470. }
  471. #[test]
  472. fn test_origin_opaque() {
  473. assert!(!Origin::new_opaque().is_tuple());
  474. assert!(!&Url::parse("blob:malformed//").unwrap().origin().is_tuple())
  475. }
  476. #[test]
  477. fn test_origin_unicode_serialization() {
  478. let data = [
  479. ("http://😅.com", "http://😅.com"),
  480. ("ftp://😅:🙂@🙂.com", "ftp://🙂.com"),
  481. ("https://user@😅.com", "https://😅.com"),
  482. ("http://😅.🙂:40", "http://😅.🙂:40"),
  483. ];
  484. for &(unicode_url, expected_serialization) in &data {
  485. let origin = Url::parse(unicode_url).unwrap().origin();
  486. assert_eq!(origin.unicode_serialization(), *expected_serialization);
  487. }
  488. let ascii_origins = [
  489. Url::parse("http://example.net/").unwrap().origin(),
  490. Url::parse("http://example.net:80/").unwrap().origin(),
  491. Url::parse("http://example.net:81/").unwrap().origin(),
  492. Url::parse("http://example.net").unwrap().origin(),
  493. Url::parse("http://example.net/hello").unwrap().origin(),
  494. Url::parse("https://example.net").unwrap().origin(),
  495. Url::parse("ftp://example.net").unwrap().origin(),
  496. Url::parse("file://example.net").unwrap().origin(),
  497. Url::parse("http://user@example.net/").unwrap().origin(),
  498. Url::parse("http://user:pass@example.net/")
  499. .unwrap()
  500. .origin(),
  501. Url::parse("http://127.0.0.1").unwrap().origin(),
  502. ];
  503. for ascii_origin in &ascii_origins {
  504. assert_eq!(
  505. ascii_origin.ascii_serialization(),
  506. ascii_origin.unicode_serialization()
  507. );
  508. }
  509. }
  510. #[test]
  511. fn test_socket_addrs() {
  512. use std::net::ToSocketAddrs;
  513. let data = [
  514. ("https://127.0.0.1/", "127.0.0.1", 443),
  515. ("https://127.0.0.1:9742/", "127.0.0.1", 9742),
  516. ("custom-protocol://127.0.0.1:9742/", "127.0.0.1", 9742),
  517. ("custom-protocol://127.0.0.1/", "127.0.0.1", 9743),
  518. ("https://[::1]/", "::1", 443),
  519. ("https://[::1]:9742/", "::1", 9742),
  520. ("custom-protocol://[::1]:9742/", "::1", 9742),
  521. ("custom-protocol://[::1]/", "::1", 9743),
  522. ("https://localhost/", "localhost", 443),
  523. ("https://localhost:9742/", "localhost", 9742),
  524. ("custom-protocol://localhost:9742/", "localhost", 9742),
  525. ("custom-protocol://localhost/", "localhost", 9743),
  526. ];
  527. for (url_string, host, port) in &data {
  528. let url = url::Url::parse(url_string).unwrap();
  529. let addrs = url
  530. .socket_addrs(|| match url.scheme() {
  531. "custom-protocol" => Some(9743),
  532. _ => None,
  533. })
  534. .unwrap();
  535. assert_eq!(
  536. Some(addrs[0]),
  537. (*host, *port).to_socket_addrs().unwrap().next()
  538. );
  539. }
  540. }
  541. #[test]
  542. fn test_no_base_url() {
  543. let mut no_base_url = Url::parse("mailto:test@example.net").unwrap();
  544. assert!(no_base_url.cannot_be_a_base());
  545. assert!(no_base_url.path_segments().is_none());
  546. assert!(no_base_url.path_segments_mut().is_err());
  547. assert!(no_base_url.set_host(Some("foo")).is_err());
  548. assert!(no_base_url
  549. .set_ip_host("127.0.0.1".parse().unwrap())
  550. .is_err());
  551. no_base_url.set_path("/foo");
  552. assert_eq!(no_base_url.path(), "%2Ffoo");
  553. }
  554. #[test]
  555. fn test_domain() {
  556. let url = Url::parse("https://127.0.0.1/").unwrap();
  557. assert_eq!(url.domain(), None);
  558. let url = Url::parse("mailto:test@example.net").unwrap();
  559. assert_eq!(url.domain(), None);
  560. let url = Url::parse("https://example.com/").unwrap();
  561. assert_eq!(url.domain(), Some("example.com"));
  562. }
  563. #[test]
  564. fn test_query() {
  565. let url = Url::parse("https://example.com/products?page=2#fragment").unwrap();
  566. assert_eq!(url.query(), Some("page=2"));
  567. assert_eq!(
  568. url.query_pairs().next(),
  569. Some((Cow::Borrowed("page"), Cow::Borrowed("2")))
  570. );
  571. let url = Url::parse("https://example.com/products").unwrap();
  572. assert!(url.query().is_none());
  573. assert_eq!(url.query_pairs().count(), 0);
  574. let url = Url::parse("https://example.com/?country=español").unwrap();
  575. assert_eq!(url.query(), Some("country=espa%C3%B1ol"));
  576. assert_eq!(
  577. url.query_pairs().next(),
  578. Some((Cow::Borrowed("country"), Cow::Borrowed("español")))
  579. );
  580. let url = Url::parse("https://example.com/products?page=2&sort=desc").unwrap();
  581. assert_eq!(url.query(), Some("page=2&sort=desc"));
  582. let mut pairs = url.query_pairs();
  583. assert_eq!(pairs.count(), 2);
  584. assert_eq!(
  585. pairs.next(),
  586. Some((Cow::Borrowed("page"), Cow::Borrowed("2")))
  587. );
  588. assert_eq!(
  589. pairs.next(),
  590. Some((Cow::Borrowed("sort"), Cow::Borrowed("desc")))
  591. );
  592. }
  593. #[test]
  594. fn test_fragment() {
  595. let url = Url::parse("https://example.com/#fragment").unwrap();
  596. assert_eq!(url.fragment(), Some("fragment"));
  597. let url = Url::parse("https://example.com/").unwrap();
  598. assert_eq!(url.fragment(), None);
  599. }
  600. #[test]
  601. fn test_set_ip_host() {
  602. let mut url = Url::parse("http://example.com").unwrap();
  603. url.set_ip_host("127.0.0.1".parse().unwrap()).unwrap();
  604. assert_eq!(url.host_str(), Some("127.0.0.1"));
  605. url.set_ip_host("::1".parse().unwrap()).unwrap();
  606. assert_eq!(url.host_str(), Some("[::1]"));
  607. }
  608. #[test]
  609. fn test_set_href() {
  610. use url::quirks::set_href;
  611. let mut url = Url::parse("https://existing.url").unwrap();
  612. assert!(set_href(&mut url, "mal//formed").is_err());
  613. assert!(set_href(
  614. &mut url,
  615. "https://user:pass@domain.com:9742/path/file.ext?key=val&key2=val2#fragment"
  616. )
  617. .is_ok());
  618. assert_eq!(
  619. url,
  620. Url::parse("https://user:pass@domain.com:9742/path/file.ext?key=val&key2=val2#fragment")
  621. .unwrap()
  622. );
  623. }
  624. #[test]
  625. fn test_domain_encoding_quirks() {
  626. use url::quirks::{domain_to_ascii, domain_to_unicode};
  627. let data = [
  628. ("http://example.com", "", ""),
  629. ("😅.🙂", "xn--j28h.xn--938h", "😅.🙂"),
  630. ("example.com", "example.com", "example.com"),
  631. ("mailto:test@example.net", "", ""),
  632. ];
  633. for url in &data {
  634. assert_eq!(domain_to_ascii(url.0), url.1);
  635. assert_eq!(domain_to_unicode(url.0), url.2);
  636. }
  637. }
  638. #[cfg(feature = "expose_internals")]
  639. #[test]
  640. fn test_expose_internals() {
  641. use url::quirks::internal_components;
  642. use url::quirks::InternalComponents;
  643. let url = Url::parse("https://example.com/path/file.ext?key=val&key2=val2#fragment").unwrap();
  644. let InternalComponents {
  645. scheme_end,
  646. username_end,
  647. host_start,
  648. host_end,
  649. port,
  650. path_start,
  651. query_start,
  652. fragment_start,
  653. } = internal_components(&url);
  654. assert_eq!(scheme_end, 5);
  655. assert_eq!(username_end, 8);
  656. assert_eq!(host_start, 8);
  657. assert_eq!(host_end, 19);
  658. assert_eq!(port, None);
  659. assert_eq!(path_start, 19);
  660. assert_eq!(query_start, Some(33));
  661. assert_eq!(fragment_start, Some(51));
  662. }
  663. #[test]
  664. fn test_windows_unc_path() {
  665. if !cfg!(windows) {
  666. return;
  667. }
  668. let url = Url::from_file_path(Path::new(r"\\host\share\path\file.txt")).unwrap();
  669. assert_eq!(url.as_str(), "file://host/share/path/file.txt");
  670. let url = Url::from_file_path(Path::new(r"\\höst\share\path\file.txt")).unwrap();
  671. assert_eq!(url.as_str(), "file://xn--hst-sna/share/path/file.txt");
  672. let url = Url::from_file_path(Path::new(r"\\192.168.0.1\share\path\file.txt")).unwrap();
  673. assert_eq!(url.host(), Some(Host::Ipv4(Ipv4Addr::new(192, 168, 0, 1))));
  674. let path = url.to_file_path().unwrap();
  675. assert_eq!(path.to_str(), Some(r"\\192.168.0.1\share\path\file.txt"));
  676. // Another way to write these:
  677. let url = Url::from_file_path(Path::new(r"\\?\UNC\host\share\path\file.txt")).unwrap();
  678. assert_eq!(url.as_str(), "file://host/share/path/file.txt");
  679. // Paths starting with "\\.\" (Local Device Paths) are intentionally not supported.
  680. let url = Url::from_file_path(Path::new(r"\\.\some\path\file.txt"));
  681. assert!(url.is_err());
  682. }
  683. #[test]
  684. fn test_syntax_violation_callback() {
  685. use url::SyntaxViolation::*;
  686. let violation = Cell::new(None);
  687. let url = Url::options()
  688. .syntax_violation_callback(Some(&|v| violation.set(Some(v))))
  689. .parse("http:////mozilla.org:42")
  690. .unwrap();
  691. assert_eq!(url.port(), Some(42));
  692. let v = violation.take().unwrap();
  693. assert_eq!(v, ExpectedDoubleSlash);
  694. assert_eq!(v.description(), "expected //");
  695. assert_eq!(v.to_string(), "expected //");
  696. }
  697. #[test]
  698. fn test_syntax_violation_callback_lifetimes() {
  699. use url::SyntaxViolation::*;
  700. let violation = Cell::new(None);
  701. let vfn = |s| violation.set(Some(s));
  702. let url = Url::options()
  703. .syntax_violation_callback(Some(&vfn))
  704. .parse("http:////mozilla.org:42")
  705. .unwrap();
  706. assert_eq!(url.port(), Some(42));
  707. assert_eq!(violation.take(), Some(ExpectedDoubleSlash));
  708. let url = Url::options()
  709. .syntax_violation_callback(Some(&vfn))
  710. .parse("http://mozilla.org\\path")
  711. .unwrap();
  712. assert_eq!(url.path(), "/path");
  713. assert_eq!(violation.take(), Some(Backslash));
  714. }
  715. #[test]
  716. fn test_syntax_violation_callback_types() {
  717. use url::SyntaxViolation::*;
  718. let data = [
  719. ("http://mozilla.org/\\foo", Backslash, "backslash"),
  720. (" http://mozilla.org", C0SpaceIgnored, "leading or trailing control or space character are ignored in URLs"),
  721. ("http://user:pass@mozilla.org", EmbeddedCredentials, "embedding authentication information (username or password) in an URL is not recommended"),
  722. ("http:///mozilla.org", ExpectedDoubleSlash, "expected //"),
  723. ("file:/foo.txt", ExpectedFileDoubleSlash, "expected // after file:"),
  724. ("file://mozilla.org/c:/file.txt", FileWithHostAndWindowsDrive, "file: with host and Windows drive letter"),
  725. ("http://mozilla.org/^", NonUrlCodePoint, "non-URL code point"),
  726. ("http://mozilla.org/#\x000", NullInFragment, "NULL characters are ignored in URL fragment identifiers"),
  727. ("http://mozilla.org/%1", PercentDecode, "expected 2 hex digits after %"),
  728. ("http://mozilla.org\t/foo", TabOrNewlineIgnored, "tabs or newlines are ignored in URLs"),
  729. ("http://user@:pass@mozilla.org", UnencodedAtSign, "unencoded @ sign in username or password")
  730. ];
  731. for test_case in &data {
  732. let violation = Cell::new(None);
  733. Url::options()
  734. .syntax_violation_callback(Some(&|v| violation.set(Some(v))))
  735. .parse(test_case.0)
  736. .unwrap();
  737. let v = violation.take();
  738. assert_eq!(v, Some(test_case.1));
  739. assert_eq!(v.unwrap().description(), test_case.2);
  740. assert_eq!(v.unwrap().to_string(), test_case.2);
  741. }
  742. }
  743. #[test]
  744. fn test_options_reuse() {
  745. use url::SyntaxViolation::*;
  746. let violations = RefCell::new(Vec::new());
  747. let vfn = |v| violations.borrow_mut().push(v);
  748. let options = Url::options().syntax_violation_callback(Some(&vfn));
  749. let url = options.parse("http:////mozilla.org").unwrap();
  750. let options = options.base_url(Some(&url));
  751. let url = options.parse("/sub\\path").unwrap();
  752. assert_eq!(url.as_str(), "http://mozilla.org/sub/path");
  753. assert_eq!(*violations.borrow(), vec!(ExpectedDoubleSlash, Backslash));
  754. }
  755. /// https://github.com/servo/rust-url/issues/505
  756. #[cfg(windows)]
  757. #[test]
  758. fn test_url_from_file_path() {
  759. use std::path::PathBuf;
  760. use url::Url;
  761. let p = PathBuf::from("c:///");
  762. let u = Url::from_file_path(p).unwrap();
  763. let path = u.to_file_path().unwrap();
  764. assert_eq!("C:\\", path.to_str().unwrap());
  765. }
  766. /// https://github.com/servo/rust-url/issues/505
  767. #[cfg(not(windows))]
  768. #[test]
  769. fn test_url_from_file_path() {
  770. use std::path::PathBuf;
  771. use url::Url;
  772. let p = PathBuf::from("/c:/");
  773. let u = Url::from_file_path(p).unwrap();
  774. let path = u.to_file_path().unwrap();
  775. assert_eq!("/c:/", path.to_str().unwrap());
  776. }
  777. #[test]
  778. fn test_non_special_path() {
  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("diesel_foo");
  782. assert_eq!(db_url.as_str(), "postgres://postgres@localhost/diesel_foo");
  783. assert_eq!(db_url.path(), "/diesel_foo");
  784. }
  785. #[test]
  786. fn test_non_special_path2() {
  787. let mut db_url = url::Url::parse("postgres://postgres@localhost/").unwrap();
  788. assert_eq!(db_url.as_str(), "postgres://postgres@localhost/");
  789. db_url.set_path("");
  790. assert_eq!(db_url.path(), "");
  791. assert_eq!(db_url.as_str(), "postgres://postgres@localhost");
  792. db_url.set_path("foo");
  793. assert_eq!(db_url.path(), "/foo");
  794. assert_eq!(db_url.as_str(), "postgres://postgres@localhost/foo");
  795. db_url.set_path("/bar");
  796. assert_eq!(db_url.path(), "/bar");
  797. assert_eq!(db_url.as_str(), "postgres://postgres@localhost/bar");
  798. }
  799. #[test]
  800. fn test_non_special_path3() {
  801. let mut db_url = url::Url::parse("postgres://postgres@localhost/").unwrap();
  802. assert_eq!(db_url.as_str(), "postgres://postgres@localhost/");
  803. db_url.set_path("/");
  804. assert_eq!(db_url.as_str(), "postgres://postgres@localhost/");
  805. assert_eq!(db_url.path(), "/");
  806. db_url.set_path("/foo");
  807. assert_eq!(db_url.as_str(), "postgres://postgres@localhost/foo");
  808. assert_eq!(db_url.path(), "/foo");
  809. }
  810. #[test]
  811. fn test_set_scheme_to_file_with_host() {
  812. let mut url: Url = "http://localhost:6767/foo/bar".parse().unwrap();
  813. let result = url.set_scheme("file");
  814. assert_eq!(url.to_string(), "http://localhost:6767/foo/bar");
  815. assert_eq!(result, Err(()));
  816. }
  817. #[test]
  818. fn no_panic() {
  819. let mut url = Url::parse("arhttpsps:/.//eom/dae.com/\\\\t\\:").unwrap();
  820. url::quirks::set_hostname(&mut url, "//eom/datcom/\\\\t\\://eom/data.cs").unwrap();
  821. }
  822. #[test]
  823. fn pop_if_empty_in_bounds() {
  824. let mut url = Url::parse("m://").unwrap();
  825. let mut segments = url.path_segments_mut().unwrap();
  826. segments.pop_if_empty();
  827. segments.pop();
  828. }
  829. #[test]
  830. fn test_slicing() {
  831. use url::Position::*;
  832. #[derive(Default)]
  833. struct ExpectedSlices<'a> {
  834. full: &'a str,
  835. scheme: &'a str,
  836. username: &'a str,
  837. password: &'a str,
  838. host: &'a str,
  839. port: &'a str,
  840. path: &'a str,
  841. query: &'a str,
  842. fragment: &'a str,
  843. }
  844. let data = [
  845. ExpectedSlices {
  846. full: "https://user:pass@domain.com:9742/path/file.ext?key=val&key2=val2#fragment",
  847. scheme: "https",
  848. username: "user",
  849. password: "pass",
  850. host: "domain.com",
  851. port: "9742",
  852. path: "/path/file.ext",
  853. query: "key=val&key2=val2",
  854. fragment: "fragment",
  855. },
  856. ExpectedSlices {
  857. full: "https://domain.com:9742/path/file.ext#fragment",
  858. scheme: "https",
  859. host: "domain.com",
  860. port: "9742",
  861. path: "/path/file.ext",
  862. fragment: "fragment",
  863. ..Default::default()
  864. },
  865. ExpectedSlices {
  866. full: "https://domain.com:9742/path/file.ext",
  867. scheme: "https",
  868. host: "domain.com",
  869. port: "9742",
  870. path: "/path/file.ext",
  871. ..Default::default()
  872. },
  873. ExpectedSlices {
  874. full: "blob:blob-info",
  875. scheme: "blob",
  876. path: "blob-info",
  877. ..Default::default()
  878. },
  879. ];
  880. for expected_slices in &data {
  881. let url = Url::parse(expected_slices.full).unwrap();
  882. assert_eq!(&url[..], expected_slices.full);
  883. assert_eq!(&url[BeforeScheme..AfterScheme], expected_slices.scheme);
  884. assert_eq!(
  885. &url[BeforeUsername..AfterUsername],
  886. expected_slices.username
  887. );
  888. assert_eq!(
  889. &url[BeforePassword..AfterPassword],
  890. expected_slices.password
  891. );
  892. assert_eq!(&url[BeforeHost..AfterHost], expected_slices.host);
  893. assert_eq!(&url[BeforePort..AfterPort], expected_slices.port);
  894. assert_eq!(&url[BeforePath..AfterPath], expected_slices.path);
  895. assert_eq!(&url[BeforeQuery..AfterQuery], expected_slices.query);
  896. assert_eq!(
  897. &url[BeforeFragment..AfterFragment],
  898. expected_slices.fragment
  899. );
  900. assert_eq!(&url[..AfterFragment], expected_slices.full);
  901. }
  902. }
  903. #[test]
  904. fn test_make_relative() {
  905. let tests = [
  906. (
  907. "http://127.0.0.1:8080/test",
  908. "http://127.0.0.1:8080/test",
  909. "",
  910. ),
  911. (
  912. "http://127.0.0.1:8080/test",
  913. "http://127.0.0.1:8080/test/",
  914. "test/",
  915. ),
  916. (
  917. "http://127.0.0.1:8080/test/",
  918. "http://127.0.0.1:8080/test",
  919. "../test",
  920. ),
  921. (
  922. "http://127.0.0.1:8080/",
  923. "http://127.0.0.1:8080/?foo=bar#123",
  924. "?foo=bar#123",
  925. ),
  926. (
  927. "http://127.0.0.1:8080/",
  928. "http://127.0.0.1:8080/test/video",
  929. "test/video",
  930. ),
  931. (
  932. "http://127.0.0.1:8080/test",
  933. "http://127.0.0.1:8080/test/video",
  934. "test/video",
  935. ),
  936. (
  937. "http://127.0.0.1:8080/test/",
  938. "http://127.0.0.1:8080/test/video",
  939. "video",
  940. ),
  941. (
  942. "http://127.0.0.1:8080/test",
  943. "http://127.0.0.1:8080/test2/video",
  944. "test2/video",
  945. ),
  946. (
  947. "http://127.0.0.1:8080/test/",
  948. "http://127.0.0.1:8080/test2/video",
  949. "../test2/video",
  950. ),
  951. (
  952. "http://127.0.0.1:8080/test/bla",
  953. "http://127.0.0.1:8080/test2/video",
  954. "../test2/video",
  955. ),
  956. (
  957. "http://127.0.0.1:8080/test/bla/",
  958. "http://127.0.0.1:8080/test2/video",
  959. "../../test2/video",
  960. ),
  961. (
  962. "http://127.0.0.1:8080/test/?foo=bar#123",
  963. "http://127.0.0.1:8080/test/video",
  964. "video",
  965. ),
  966. (
  967. "http://127.0.0.1:8080/test/",
  968. "http://127.0.0.1:8080/test/video?baz=meh#456",
  969. "video?baz=meh#456",
  970. ),
  971. (
  972. "http://127.0.0.1:8080/test",
  973. "http://127.0.0.1:8080/test?baz=meh#456",
  974. "?baz=meh#456",
  975. ),
  976. (
  977. "http://127.0.0.1:8080/test/",
  978. "http://127.0.0.1:8080/test?baz=meh#456",
  979. "../test?baz=meh#456",
  980. ),
  981. (
  982. "http://127.0.0.1:8080/test/",
  983. "http://127.0.0.1:8080/test/?baz=meh#456",
  984. "?baz=meh#456",
  985. ),
  986. (
  987. "http://127.0.0.1:8080/test/?foo=bar#123",
  988. "http://127.0.0.1:8080/test/video?baz=meh#456",
  989. "video?baz=meh#456",
  990. ),
  991. (
  992. "http://127.0.0.1:8080/file.txt",
  993. "http://127.0.0.1:8080/test/file.txt",
  994. "test/file.txt",
  995. ),
  996. (
  997. "http://127.0.0.1:8080/not_equal.txt",
  998. "http://127.0.0.1:8080/test/file.txt",
  999. "test/file.txt",
  1000. ),
  1001. ];
  1002. for (base, uri, relative) in &tests {
  1003. let base_uri = url::Url::parse(base).unwrap();
  1004. let relative_uri = url::Url::parse(uri).unwrap();
  1005. let make_relative = base_uri.make_relative(&relative_uri).unwrap();
  1006. assert_eq!(
  1007. make_relative, *relative,
  1008. "base: {}, uri: {}, relative: {}",
  1009. base, uri, relative
  1010. );
  1011. assert_eq!(
  1012. base_uri.join(relative).unwrap().as_str(),
  1013. *uri,
  1014. "base: {}, uri: {}, relative: {}",
  1015. base,
  1016. uri,
  1017. relative
  1018. );
  1019. }
  1020. let error_tests = [
  1021. ("http://127.0.0.1:8080/", "https://127.0.0.1:8080/test/"),
  1022. ("http://127.0.0.1:8080/", "http://127.0.0.1:8081/test/"),
  1023. ("http://127.0.0.1:8080/", "http://127.0.0.2:8080/test/"),
  1024. ("mailto:a@example.com", "mailto:b@example.com"),
  1025. ];
  1026. for (base, uri) in &error_tests {
  1027. let base_uri = url::Url::parse(base).unwrap();
  1028. let relative_uri = url::Url::parse(uri).unwrap();
  1029. let make_relative = base_uri.make_relative(&relative_uri);
  1030. assert_eq!(make_relative, None, "base: {}, uri: {}", base, uri);
  1031. }
  1032. }