test-url.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. 'use strict';
  5. const {
  6. URL,
  7. toFilename,
  8. fromFilename,
  9. isValidURI,
  10. getTLD,
  11. DataURL,
  12. isLocalURL } = require('sdk/url');
  13. const { pathFor } = require('sdk/system');
  14. const file = require('sdk/io/file');
  15. const tabs = require('sdk/tabs');
  16. const { decode } = require('sdk/base64');
  17. const httpd = require('sdk/test/httpd');
  18. const port = 8099;
  19. const defaultLocation = '{\'scheme\':\'about\',\'userPass\':null,\'host\':null,\'hostname\':null,\'port\':null,\'path\':\'addons\',\'pathname\':\'addons\',\'hash\':\'\',\'href\':\'about:addons\',\'origin\':\'about:\',\'protocol\':\'about:\',\'search\':\'\'}'.replace(/'/g, '"');
  20. exports.testResolve = function(assert) {
  21. assert.equal(URL('bar', 'http://www.foo.com/').toString(),
  22. 'http://www.foo.com/bar');
  23. assert.equal(URL('bar', 'http://www.foo.com'),
  24. 'http://www.foo.com/bar');
  25. assert.equal(URL('http://bar.com/', 'http://foo.com/'),
  26. 'http://bar.com/',
  27. 'relative should override base');
  28. assert.throws(function() { URL('blah'); },
  29. /malformed URI: blah/i,
  30. 'url.resolve() should throw malformed URI on base');
  31. assert.throws(function() { URL('chrome://global'); },
  32. /invalid URI: chrome:\/\/global/i,
  33. 'url.resolve() should throw invalid URI on base');
  34. assert.throws(function() { URL('chrome://foo/bar'); },
  35. /invalid URI: chrome:\/\/foo\/bar/i,
  36. 'url.resolve() should throw on bad chrome URI');
  37. assert.equal(URL('', 'http://www.foo.com'),
  38. 'http://www.foo.com/',
  39. 'url.resolve() should add slash to end of domain');
  40. };
  41. exports.testParseHttp = function(assert) {
  42. var aUrl = 'http://sub.foo.com/bar?locale=en-US&otherArg=%20x%20#myhash';
  43. var info = URL(aUrl);
  44. assert.equal(info.scheme, 'http');
  45. assert.equal(info.protocol, 'http:');
  46. assert.equal(info.host, 'sub.foo.com');
  47. assert.equal(info.hostname, 'sub.foo.com');
  48. assert.equal(info.port, null);
  49. assert.equal(info.userPass, null);
  50. assert.equal(info.path, '/bar?locale=en-US&otherArg=%20x%20#myhash');
  51. assert.equal(info.pathname, '/bar');
  52. assert.equal(info.href, aUrl);
  53. assert.equal(info.hash, '#myhash');
  54. assert.equal(info.search, '?locale=en-US&otherArg=%20x%20');
  55. };
  56. exports.testParseHttpSearchAndHash = function (assert) {
  57. var info = URL('https://www.moz.com/some/page.html');
  58. assert.equal(info.hash, '');
  59. assert.equal(info.search, '');
  60. var hashOnly = URL('https://www.sub.moz.com/page.html#justhash');
  61. assert.equal(hashOnly.search, '');
  62. assert.equal(hashOnly.hash, '#justhash');
  63. var queryOnly = URL('https://www.sub.moz.com/page.html?my=query');
  64. assert.equal(queryOnly.search, '?my=query');
  65. assert.equal(queryOnly.hash, '');
  66. var qMark = URL('http://www.moz.org?');
  67. assert.equal(qMark.search, '');
  68. assert.equal(qMark.hash, '');
  69. var hash = URL('http://www.moz.org#');
  70. assert.equal(hash.search, '');
  71. assert.equal(hash.hash, '');
  72. var empty = URL('http://www.moz.org?#');
  73. assert.equal(hash.search, '');
  74. assert.equal(hash.hash, '');
  75. var strange = URL('http://moz.org?test1#test2?test3');
  76. assert.equal(strange.search, '?test1');
  77. assert.equal(strange.hash, '#test2?test3');
  78. };
  79. exports.testParseHttpWithPort = function(assert) {
  80. var info = URL('http://foo.com:5/bar');
  81. assert.equal(info.port, 5);
  82. };
  83. exports.testParseChrome = function(assert) {
  84. var info = URL('chrome://global/content/blah');
  85. assert.equal(info.scheme, 'chrome');
  86. assert.equal(info.host, 'global');
  87. assert.equal(info.port, null);
  88. assert.equal(info.userPass, null);
  89. assert.equal(info.path, '/content/blah');
  90. };
  91. exports.testParseAbout = function(assert) {
  92. var info = URL('about:boop');
  93. assert.equal(info.scheme, 'about');
  94. assert.equal(info.host, null);
  95. assert.equal(info.port, null);
  96. assert.equal(info.userPass, null);
  97. assert.equal(info.path, 'boop');
  98. };
  99. exports.testParseFTP = function(assert) {
  100. var info = URL('ftp://1.2.3.4/foo');
  101. assert.equal(info.scheme, 'ftp');
  102. assert.equal(info.host, '1.2.3.4');
  103. assert.equal(info.port, null);
  104. assert.equal(info.userPass, null);
  105. assert.equal(info.path, '/foo');
  106. };
  107. exports.testParseFTPWithUserPass = function(assert) {
  108. var info = URL('ftp://user:pass@1.2.3.4/foo');
  109. assert.equal(info.userPass, 'user:pass');
  110. };
  111. exports.testToFilename = function(assert) {
  112. assert.throws(
  113. function() { toFilename('resource://nonexistent'); },
  114. /resource does not exist: resource:\/\/nonexistent\//i,
  115. 'toFilename() on nonexistent resources should throw'
  116. );
  117. assert.throws(
  118. function() { toFilename('http://foo.com/'); },
  119. /cannot map to filename: http:\/\/foo.com\//i,
  120. 'toFilename() on http: URIs should raise error'
  121. );
  122. try {
  123. assert.ok(
  124. /.*console\.xul$/.test(toFilename('chrome://global/content/console.xul')),
  125. 'toFilename() w/ console.xul works when it maps to filesystem'
  126. );
  127. }
  128. catch (e) {
  129. if (/chrome url isn\'t on filesystem/.test(e.message))
  130. assert.pass('accessing console.xul in jar raises exception');
  131. else
  132. assert.fail('accessing console.xul raises ' + e);
  133. }
  134. // TODO: Are there any chrome URLs that we're certain exist on the
  135. // filesystem?
  136. // assert.ok(/.*main\.js$/.test(toFilename('chrome://myapp/content/main.js')));
  137. };
  138. exports.testFromFilename = function(assert) {
  139. var profileDirName = require('sdk/system').pathFor('ProfD');
  140. var fileUrl = fromFilename(profileDirName);
  141. assert.equal(URL(fileUrl).scheme, 'file',
  142. 'toFilename() should return a file: url');
  143. assert.equal(fromFilename(toFilename(fileUrl)), fileUrl);
  144. };
  145. exports.testURL = function(assert) {
  146. assert.ok(URL('h:foo') instanceof URL, 'instance is of correct type');
  147. assert.throws(function() URL(),
  148. /malformed URI: undefined/i,
  149. 'url.URL should throw on undefined');
  150. assert.throws(function() URL(''),
  151. /malformed URI: /i,
  152. 'url.URL should throw on empty string');
  153. assert.throws(function() URL('foo'),
  154. /malformed URI: foo/i,
  155. 'url.URL should throw on invalid URI');
  156. assert.ok(URL('h:foo').scheme, 'has scheme');
  157. assert.equal(URL('h:foo').toString(),
  158. 'h:foo',
  159. 'toString should roundtrip');
  160. // test relative + base
  161. assert.equal(URL('mypath', 'http://foo').toString(),
  162. 'http://foo/mypath',
  163. 'relative URL resolved to base');
  164. // test relative + no base
  165. assert.throws(function() URL('path').toString(),
  166. /malformed URI: path/i,
  167. 'no base for relative URI should throw');
  168. let a = URL('h:foo');
  169. let b = URL(a);
  170. assert.equal(b.toString(),
  171. 'h:foo',
  172. 'a URL can be initialized from another URL');
  173. assert.notStrictEqual(a, b,
  174. 'a URL initialized from another URL is not the same object');
  175. assert.ok(a == 'h:foo',
  176. 'toString is implicit when a URL is compared to a string via ==');
  177. assert.strictEqual(a + '', 'h:foo',
  178. 'toString is implicit when a URL is concatenated to a string');
  179. };
  180. exports.testStringInterface = function(assert) {
  181. var EM = 'about:addons';
  182. var a = URL(EM);
  183. // make sure the standard URL properties are enumerable and not the String interface bits
  184. assert.equal(Object.keys(a),
  185. 'scheme,userPass,host,hostname,port,path,pathname,hash,href,origin,protocol,search',
  186. 'enumerable key list check for URL.');
  187. assert.equal(
  188. JSON.stringify(a),
  189. defaultLocation,
  190. 'JSON.stringify should return a object with correct props and vals.');
  191. // make sure that the String interface exists and works as expected
  192. assert.equal(a.indexOf(':'), EM.indexOf(':'), 'indexOf on URL works');
  193. assert.equal(a.valueOf(), EM.valueOf(), 'valueOf on URL works.');
  194. assert.equal(a.toSource(), EM.toSource(), 'toSource on URL works.');
  195. assert.equal(a.lastIndexOf('a'), EM.lastIndexOf('a'), 'lastIndexOf on URL works.');
  196. assert.equal(a.match('t:').toString(), EM.match('t:').toString(), 'match on URL works.');
  197. assert.equal(a.toUpperCase(), EM.toUpperCase(), 'toUpperCase on URL works.');
  198. assert.equal(a.toLowerCase(), EM.toLowerCase(), 'toLowerCase on URL works.');
  199. assert.equal(a.split(':').toString(), EM.split(':').toString(), 'split on URL works.');
  200. assert.equal(a.charAt(2), EM.charAt(2), 'charAt on URL works.');
  201. assert.equal(a.charCodeAt(2), EM.charCodeAt(2), 'charCodeAt on URL works.');
  202. assert.equal(a.concat(EM), EM.concat(a), 'concat on URL works.');
  203. assert.equal(a.substr(2,3), EM.substr(2,3), 'substr on URL works.');
  204. assert.equal(a.substring(2,3), EM.substring(2,3), 'substring on URL works.');
  205. assert.equal(a.trim(), EM.trim(), 'trim on URL works.');
  206. assert.equal(a.trimRight(), EM.trimRight(), 'trimRight on URL works.');
  207. assert.equal(a.trimLeft(), EM.trimLeft(), 'trimLeft on URL works.');
  208. }
  209. exports.testDataURLwithouthURI = function (assert) {
  210. let dataURL = new DataURL();
  211. assert.equal(dataURL.base64, false, 'base64 is false for empty uri')
  212. assert.equal(dataURL.data, '', 'data is an empty string for empty uri')
  213. assert.equal(dataURL.mimeType, '', 'mimeType is an empty string for empty uri')
  214. assert.equal(Object.keys(dataURL.parameters).length, 0, 'parameters is an empty object for empty uri');
  215. assert.equal(dataURL.toString(), 'data:,');
  216. }
  217. exports.testDataURLwithMalformedURI = function (assert) {
  218. assert.throws(function() {
  219. let dataURL = new DataURL('http://www.mozilla.com/');
  220. },
  221. /Malformed Data URL: http:\/\/www.mozilla.com\//i,
  222. 'DataURL raises an exception for malformed data uri'
  223. );
  224. }
  225. exports.testDataURLparse = function (assert) {
  226. let dataURL = new DataURL('data:text/html;charset=US-ASCII,%3Ch1%3EHello!%3C%2Fh1%3E');
  227. assert.equal(dataURL.base64, false, 'base64 is false for non base64 data uri')
  228. assert.equal(dataURL.data, '<h1>Hello!</h1>', 'data is properly decoded')
  229. assert.equal(dataURL.mimeType, 'text/html', 'mimeType is set properly')
  230. assert.equal(Object.keys(dataURL.parameters).length, 1, 'one parameters specified');
  231. assert.equal(dataURL.parameters['charset'], 'US-ASCII', 'charset parsed');
  232. assert.equal(dataURL.toString(), 'data:text/html;charset=US-ASCII,%3Ch1%3EHello!%3C%2Fh1%3E');
  233. }
  234. exports.testDataURLparseBase64 = function (assert) {
  235. let text = 'Awesome!';
  236. let b64text = 'QXdlc29tZSE=';
  237. let dataURL = new DataURL('data:text/plain;base64,' + b64text);
  238. assert.equal(dataURL.base64, true, 'base64 is true for base64 encoded data uri')
  239. assert.equal(dataURL.data, text, 'data is properly decoded')
  240. assert.equal(dataURL.mimeType, 'text/plain', 'mimeType is set properly')
  241. assert.equal(Object.keys(dataURL.parameters).length, 1, 'one parameters specified');
  242. assert.equal(dataURL.parameters['base64'], '', 'parameter set without value');
  243. assert.equal(dataURL.toString(), 'data:text/plain;base64,' + encodeURIComponent(b64text));
  244. }
  245. exports.testIsValidURI = function (assert) {
  246. validURIs().forEach(function (aUri) {
  247. assert.equal(isValidURI(aUri), true, aUri + ' is a valid URL');
  248. });
  249. };
  250. exports.testIsInvalidURI = function (assert) {
  251. invalidURIs().forEach(function (aUri) {
  252. assert.equal(isValidURI(aUri), false, aUri + ' is an invalid URL');
  253. });
  254. };
  255. exports.testURLFromURL = function(assert) {
  256. let aURL = URL('http://mozilla.org');
  257. let bURL = URL(aURL);
  258. assert.equal(aURL.toString(), bURL.toString(), 'Making a URL from a URL works');
  259. };
  260. exports.testTLD = function(assert) {
  261. let urls = [
  262. { url: 'http://my.sub.domains.mozilla.co.uk', tld: 'co.uk' },
  263. { url: 'http://my.mozilla.com', tld: 'com' },
  264. { url: 'http://my.domains.mozilla.org.hk', tld: 'org.hk' },
  265. { url: 'chrome://global/content/blah', tld: 'global' },
  266. { url: 'data:text/plain;base64,QXdlc29tZSE=', tld: null },
  267. { url: 'https://1.2.3.4', tld: null }
  268. ];
  269. urls.forEach(function (uri) {
  270. assert.equal(getTLD(uri.url), uri.tld);
  271. assert.equal(getTLD(URL(uri.url)), uri.tld);
  272. });
  273. }
  274. exports.testWindowLocationMatch = function (assert, done) {
  275. let server = httpd.startServerAsync(port);
  276. server.registerPathHandler('/index.html', function (request, response) {
  277. response.write('<html><head></head><body><h1>url tests</h1></body></html>');
  278. });
  279. let aUrl = 'http://localhost:' + port + '/index.html?q=aQuery#somehash';
  280. let urlObject = URL(aUrl);
  281. tabs.open({
  282. url: aUrl,
  283. onReady: function (tab) {
  284. tab.attach({
  285. onMessage: function (loc) {
  286. for (let prop in loc) {
  287. assert.equal(urlObject[prop], loc[prop], prop + ' matches');
  288. }
  289. tab.close(function() server.stop(done));
  290. },
  291. contentScript: '(' + function () {
  292. let res = {};
  293. // `origin` is `null` in this context???
  294. let props = 'hostname,port,pathname,hash,href,protocol,search'.split(',');
  295. props.forEach(function (prop) {
  296. res[prop] = window.location[prop];
  297. });
  298. self.postMessage(res);
  299. } + ')()'
  300. });
  301. }
  302. })
  303. };
  304. exports.testURLInRegExpTest = function(assert) {
  305. let url = 'https://mozilla.org';
  306. assert.equal((new RegExp(url).test(URL(url))), true, 'URL instances work in a RegExp test');
  307. }
  308. exports.testLocalURL = function(assert) {
  309. [
  310. 'data:text/html;charset=utf-8,foo and bar',
  311. 'data:text/plain,foo and bar',
  312. 'resource://gre/modules/commonjs/',
  313. 'chrome://browser/content/browser.xul'
  314. ].forEach(aUri => {
  315. assert.ok(isLocalURL(aUri), aUri + ' is a Local URL');
  316. })
  317. }
  318. exports.testLocalURLwithRemoteURL = function(assert) {
  319. validURIs().filter(url => !url.startsWith('data:')).forEach(aUri => {
  320. assert.ok(!isLocalURL(aUri), aUri + ' is an invalid Local URL');
  321. });
  322. }
  323. exports.testLocalURLwithInvalidURL = function(assert) {
  324. invalidURIs().concat([
  325. 'data:foo and bar',
  326. 'resource:// must fail',
  327. 'chrome:// here too'
  328. ]).forEach(aUri => {
  329. assert.ok(!isLocalURL(aUri), aUri + ' is an invalid Local URL');
  330. });
  331. }
  332. function validURIs() {
  333. return [
  334. 'http://foo.com/blah_blah',
  335. 'http://foo.com/blah_blah/',
  336. 'http://foo.com/blah_blah_(wikipedia)',
  337. 'http://foo.com/blah_blah_(wikipedia)_(again)',
  338. 'http://www.example.com/wpstyle/?p=364',
  339. 'https://www.example.com/foo/?bar=baz&amp;inga=42&amp;quux',
  340. 'http://✪df.ws/123',
  341. 'http://userid:password@example.com:8080',
  342. 'http://userid:password@example.com:8080/',
  343. 'http://userid@example.com',
  344. 'http://userid@example.com/',
  345. 'http://userid@example.com:8080',
  346. 'http://userid@example.com:8080/',
  347. 'http://userid:password@example.com',
  348. 'http://userid:password@example.com/',
  349. 'http://142.42.1.1/',
  350. 'http://142.42.1.1:8080/',
  351. 'http://➡.ws/䨹',
  352. 'http://⌘.ws',
  353. 'http://⌘.ws/',
  354. 'http://foo.com/blah_(wikipedia)#cite-1',
  355. 'http://foo.com/blah_(wikipedia)_blah#cite-1',
  356. 'http://foo.com/unicode_(✪)_in_parens',
  357. 'http://foo.com/(something)?after=parens',
  358. 'http://☺.damowmow.com/',
  359. 'http://code.google.com/events/#&amp;product=browser',
  360. 'http://j.mp',
  361. 'ftp://foo.bar/baz',
  362. 'http://foo.bar/?q=Test%20URL-encoded%20stuff',
  363. 'http://مثال.إختبار',
  364. 'http://例子.测试',
  365. 'http://उदाहरण.परीक्षा',
  366. 'http://-.~_!$&amp;\'()*+,;=:%40:80%2f::::::@example.com',
  367. 'http://1337.net',
  368. 'http://a.b-c.de',
  369. 'http://223.255.255.254',
  370. // Also want to validate data-uris, localhost
  371. 'http://localhost:8432/some-file.js',
  372. 'data:text/plain;base64,',
  373. 'data:text/html;charset=US-ASCII,%3Ch1%3EHello!%3C%2Fh1%3E',
  374. 'data:text/html;charset=utf-8,'
  375. ];
  376. }
  377. // Some invalidURIs are valid according to the regex used,
  378. // can be improved in the future, but better to pass some
  379. // invalid URLs than prevent valid URLs
  380. function invalidURIs () {
  381. return [
  382. // 'http://',
  383. // 'http://.',
  384. // 'http://..',
  385. // 'http://../',
  386. // 'http://?',
  387. // 'http://??',
  388. // 'http://??/',
  389. // 'http://#',
  390. // 'http://##',
  391. // 'http://##/',
  392. // 'http://foo.bar?q=Spaces should be encoded',
  393. 'not a url',
  394. '//',
  395. '//a',
  396. '///a',
  397. '///',
  398. // 'http:///a',
  399. 'foo.com',
  400. 'http:// shouldfail.com',
  401. ':// should fail',
  402. // 'http://foo.bar/foo(bar)baz quux',
  403. // 'http://-error-.invalid/',
  404. // 'http://a.b--c.de/',
  405. // 'http://-a.b.co',
  406. // 'http://a.b-.co',
  407. // 'http://0.0.0.0',
  408. // 'http://10.1.1.0',
  409. // 'http://10.1.1.255',
  410. // 'http://224.1.1.1',
  411. // 'http://1.1.1.1.1',
  412. // 'http://123.123.123',
  413. // 'http://3628126748',
  414. // 'http://.www.foo.bar/',
  415. // 'http://www.foo.bar./',
  416. // 'http://.www.foo.bar./',
  417. // 'http://10.1.1.1',
  418. // 'http://10.1.1.254'
  419. ];
  420. }
  421. require('sdk/test').run(exports);