Debian Codegraph @

tests/qunit/resources/mediawiki.util/util.test.js

raw symbols SCIP
1 QUnit.module( 'mediawiki.util', QUnit.newMwEnvironment( {
2 messages: {
3 // Used by accessKeyLabel in test for addPortletLink
4 brackets: '[$1]',
5 'word-separator': ' '
6 }
7 } ), ( hooks ) => {
8 const util = require( 'mediawiki.util' );
9
10 hooks.beforeEach( function () {
11 this.sandbox.useFakeTimers();
12
13 $.fn.updateTooltipAccessKeys.setTestMode( true );
14 mw.util.setOptionsForTest( {
15 FragmentMode: [ 'legacy', 'html5' ],
16 LoadScript: '/w/load.php'
17 } );
18 } );
19 hooks.afterEach( () => {
20 $.fn.updateTooltipAccessKeys.setTestMode( false );
21 mw.util.setOptionsForTest();
22 } );
23
24 QUnit.test( 'rawurlencode', ( assert ) => {
25 assert.strictEqual( util.rawurlencode( 'Test:A & B/Here' ), 'Test%3AA%20%26%20B%2FHere' );
26 } );
27
28 QUnit.test( 'escapeIdForAttribute', ( assert ) => {
29 // Test cases are kept in sync with SanitizerTest.php
30 const text = 'foo тест_#%!\'()[]:<>',
31 legacyEncoded = 'foo_.D1.82.D0.B5.D1.81.D1.82_.23.25.21.27.28.29.5B.5D:.3C.3E',
32 html5Encoded = 'foo_тест_#%!\'()[]:<>',
33 // Settings: this is $wgFragmentMode
34 legacy = [ 'legacy' ],
35 legacyNew = [ 'legacy', 'html5' ],
36 newLegacy = [ 'html5', 'legacy' ],
37 allNew = [ 'html5' ];
38
39 // Test cases are kept in sync with SanitizerTest.php
40 [
41 // Pure legacy: how MW worked before 2017
42 [ legacy, text, legacyEncoded ],
43 // Transition to a new world: legacy links with HTML5 fallback
44 [ legacyNew, text, legacyEncoded ],
45 // New world: HTML5 links, legacy fallbacks
46 [ newLegacy, text, html5Encoded ],
47 // Distant future: no legacy fallbacks
48 [ allNew, text, html5Encoded ]
49 ].forEach( ( testCase ) => {
50 mw.util.setOptionsForTest( { FragmentMode: testCase[ 0 ] } );
51
52 assert.strictEqual( util.escapeIdForAttribute( testCase[ 1 ] ), testCase[ 2 ] );
53 } );
54 } );
55
56 QUnit.test( 'escapeIdForLink', ( assert ) => {
57 // Test cases are kept in sync with SanitizerTest.php
58 const text = 'foo тест_#%!\'()[]:<>',
59 legacyEncoded = 'foo_.D1.82.D0.B5.D1.81.D1.82_.23.25.21.27.28.29.5B.5D:.3C.3E',
60 html5Encoded = 'foo_тест_#%!\'()[]:<>',
61 // Settings: this is wgFragmentMode
62 legacy = [ 'legacy' ],
63 legacyNew = [ 'legacy', 'html5' ],
64 newLegacy = [ 'html5', 'legacy' ],
65 allNew = [ 'html5' ];
66
67 [
68 // Pure legacy: how MW worked before 2017
69 [ legacy, text, legacyEncoded ],
70 // Transition to a new world: legacy links with HTML5 fallback
71 [ legacyNew, text, legacyEncoded ],
72 // New world: HTML5 links, legacy fallbacks
73 [ newLegacy, text, html5Encoded ],
74 // Distant future: no legacy fallbacks
75 [ allNew, text, html5Encoded ]
76 ].forEach( ( testCase ) => {
77 mw.util.setOptionsForTest( { FragmentMode: testCase[ 0 ] } );
78
79 assert.strictEqual( util.escapeIdForLink( testCase[ 1 ] ), testCase[ 2 ] );
80 } );
81 } );
82
83 QUnit.test.each( 'percentDecodeFragment', [
84 [ '', '' ],
85 [ 'foo+bar', 'foo+bar' ],
86 [ 'foo bar', 'foo bar' ],
87 [ 'foo%2Bbar', 'foo+bar' ],
88 [ 'foo%20bar', 'foo bar' ],
89 [ 'foo%20bar%A', 'foo bar%A' ],
90 [ 'Romeo+Juliet_%A_Ó_%2520', 'Romeo+Juliet_%A_Ó_%20' ],
91 [ 'Romeo&Juliet=%A', 'Romeo&Juliet=%A' ],
92 [ 'Romeo&Juliet=%20', 'Romeo&Juliet= ' ],
93 [ '%2B%26%3D%23', '+&=#' ],
94 [ '===', '===' ],
95 [ '&&&', '&&&' ],
96 [ '###', '###' ]
97 ], ( assert, data ) => {
98 assert.strictEqual( util.percentDecodeFragment( data[ 0 ] ), data[ 1 ], data[ 0 ] );
99 } );
100
101 QUnit.test.each( 'wikiUrlencode', [
102 [ 'Test:A & B/Here', 'Test:A_%26_B/Here' ],
103
104 // NOTE: Keep in sync with wfUrlencodeTest.php#provideURLS
105 [ '+', '%2B' ],
106 [ '&', '%26' ],
107 [ '=', '%3D' ],
108 [ ':', ':' ],
109 [ '/', '/' ],
110 [ '~', '~' ],
111 [ '\'', '%27' ],
112 [ '[]', '%5B%5D' ],
113 [ '<>', '%3C%3E' ],
114 [
115 ';@$-_.!*()',
116 ';@$-_.!*()'
117 ]
118 ], ( assert, data ) => {
119 assert.strictEqual( util.wikiUrlencode( data[ 0 ] ), data[ 1 ], data[ 0 ] );
120 } );
121
122 QUnit.test( 'getUrl', ( assert ) => {
123 let href;
124 mw.config.set( {
125 wgScript: '/w/index.php',
126 wgArticlePath: '/wiki/$1',
127 wgPageName: 'Foobar'
128 } );
129
130 href = util.getUrl( 'Sandbox' );
131 assert.strictEqual( href, '/wiki/Sandbox', 'simple title' );
132
133 href = util.getUrl( 'Foo:Sandbox? 5+5=10! (test)/sub ' );
134 assert.strictEqual( href, '/wiki/Foo:Sandbox%3F_5%2B5%3D10!_(test)/sub_', 'complex title' );
135
136 // T149767
137 href = util.getUrl( 'My$$test$$$$$title' );
138 assert.strictEqual( href, '/wiki/My$$test$$$$$title', 'title with multiple consecutive dollar signs' );
139
140 href = util.getUrl();
141 assert.strictEqual( href, '/wiki/Foobar', 'default title' );
142
143 href = util.getUrl( null, { action: 'edit' } );
144 assert.strictEqual( href, '/w/index.php?title=Foobar&action=edit', 'default title with query string' );
145
146 href = util.getUrl( 'Sandbox', { action: 'edit' } );
147 assert.strictEqual( href, '/w/index.php?title=Sandbox&action=edit', 'simple title with query string' );
148
149 // Test fragments
150 href = util.getUrl( 'Foo:Sandbox#Fragment', { action: 'edit' } );
151 assert.strictEqual( href, '/w/index.php?title=Foo:Sandbox&action=edit#Fragment', 'namespaced title with query string and fragment' );
152
153 href = util.getUrl( 'Sandbox#', { action: 'edit' } );
154 assert.strictEqual( href, '/w/index.php?title=Sandbox&action=edit', 'title with query string and empty fragment' );
155
156 href = util.getUrl( 'Sandbox', {} );
157 assert.strictEqual( href, '/wiki/Sandbox', 'title with empty query string' );
158
159 href = util.getUrl( '#Fragment' );
160 assert.strictEqual( href, '#Fragment', 'empty title with fragment' );
161
162 href = util.getUrl( '#Fragment', { action: 'edit' } );
163 assert.strictEqual( href, '#Fragment', 'empty title with query string and fragment' );
164
165 mw.util.setOptionsForTest( { FragmentMode: [ 'legacy' ] } );
166 href = util.getUrl( 'Foo:Sandbox \xC4#Fragment \xC4', { action: 'edit' } );
167 assert.strictEqual( href, '/w/index.php?title=Foo:Sandbox_%C3%84&action=edit#Fragment_.C3.84', 'title with query string, fragment, and special characters' );
168
169 mw.util.setOptionsForTest( { FragmentMode: [ 'html5' ] } );
170 href = util.getUrl( 'Foo:Sandbox \xC4#Fragment \xC4', { action: 'edit' } );
171 assert.strictEqual( href, '/w/index.php?title=Foo:Sandbox_%C3%84&action=edit#Fragment_Ä', 'title with query string, fragment, and special characters' );
172
173 href = util.getUrl( 'Foo:%23#Fragment', { action: 'edit' } );
174 assert.strictEqual( href, '/w/index.php?title=Foo:%2523&action=edit#Fragment', 'title containing %23 (#), fragment, and a query string' );
175
176 mw.util.setOptionsForTest( { FragmentMode: [ 'legacy' ] } );
177 href = util.getUrl( 'Sandbox#+&=:;@$-_.!*/[]<>\'§', { action: 'edit' } );
178 assert.strictEqual( href, '/w/index.php?title=Sandbox&action=edit#.2B.26.3D:.3B.40.24-_..21.2A.2F.5B.5D.3C.3E.27.C2.A7', 'fragment with various characters' );
179
180 mw.util.setOptionsForTest( { FragmentMode: [ 'html5' ] } );
181 href = util.getUrl( 'Sandbox#+&=:;@$-_.!*/[]<>\'§', { action: 'edit' } );
182 assert.strictEqual( href, '/w/index.php?title=Sandbox&action=edit#+&=:;@$-_.!*/[]<>\'§', 'fragment with various characters' );
183 } );
184
185 QUnit.test( 'wikiScript', ( assert ) => {
186 mw.util.setOptionsForTest( {
187 LoadScript: '/w/l.php'
188 } );
189 mw.config.set( {
190 // customized wgScript for T41103
191 wgScript: '/w/i.php',
192 wgScriptPath: '/w'
193 } );
194
195 assert.strictEqual( util.wikiScript(), '/w/i.php', 'default' );
196 assert.strictEqual( util.wikiScript( 'index' ), '/w/i.php', 'index' );
197 assert.strictEqual( util.wikiScript( 'load' ), '/w/l.php', 'load' );
198 assert.strictEqual( util.wikiScript( 'api' ), '/w/api.php', 'api' );
199 assert.strictEqual( util.wikiScript( 'rest' ), '/w/rest.php', 'rest' );
200 } );
201
202 QUnit.test( 'addCSS', ( assert ) => {
203 const $el = $( '<div>' ).attr( 'id', 'mw-addcsstest' ).appendTo( '#qunit-fixture' );
204 const style = util.addCSS( '#mw-addcsstest { visibility: hidden; }' );
205 assert.strictEqual( typeof style, 'object', 'addCSS returned an object' );
206 assert.strictEqual( style.disabled, false, 'property "disabled" is available and set to false' );
207
208 assert.strictEqual( $el.css( 'visibility' ), 'hidden', 'Added style properties are in effect' );
209
210 // Clean up
211 $( style.ownerNode ).remove();
212 } );
213
214 QUnit.test( 'getParamValue', ( assert ) => {
215 let url;
216
217 url = 'http://example.org/?foo=wrong&foo=right#&foo=bad';
218 assert.strictEqual( util.getParamValue( 'foo', url ), 'right', 'Use latest one, ignore hash' );
219 assert.strictEqual( util.getParamValue( 'bar', url ), null, 'Return null when not found' );
220
221 url = 'http://example.org/#&foo=bad';
222 assert.strictEqual( util.getParamValue( 'foo', url ), null, 'Ignore hash if param is not in querystring but in hash (T29427)' );
223
224 url = 'example.org?' + $.param( { TEST: 'a b+c' } );
225 assert.strictEqual( util.getParamValue( 'TEST', url ), 'a b+c', 'T32441: getParamValue must understand "+" encoding of space' );
226
227 url = 'example.org?' + $.param( { TEST: 'a b+c d' } ); // check for sloppy code from r95332 :)
228 assert.strictEqual( util.getParamValue( 'TEST', url ), 'a b+c d', 'T32441: getParamValue must understand "+" encoding of space (multiple spaces)' );
229
230 url = 'example.org?title=Autom%F3vil';
231 assert.strictEqual( util.getParamValue( 'title', url ), null, 'T268058: getParamValue can return null on input it cannot decode.' );
232 } );
233
234 QUnit.test( 'getArrayParam', ( assert ) => {
235 const params1 = new URLSearchParams( '?foo[]=a&foo[]=b&foo[]=c' );
236 const params2 = new URLSearchParams( '?foo[0]=a&foo[1]=b&foo[2]=c' );
237 const params3 = new URLSearchParams( '?foo[1]=b&foo[0]=a&foo[]=c' );
238 const expected = [ 'a', 'b', 'c' ];
239 assert.deepEqual( util.getArrayParam( 'foo', params1 ), expected,
240 'array query parameters are parsed (implicit indexes)' );
241 assert.deepEqual( util.getArrayParam( 'foo', params2 ), expected,
242 'array query parameters are parsed (explicit indexes)' );
243 assert.deepEqual( util.getArrayParam( 'foo', params3 ), expected,
244 'array query parameters are parsed (mixed indexes, out of order)' );
245
246 const paramsMissing = new URLSearchParams( '?foo[0]=a&foo[2]=c' );
247 // eslint-disable-next-line no-sparse-arrays
248 const expectedMissing = [ 'a', , 'c' ];
249 assert.deepEqual( util.getArrayParam( 'foo', paramsMissing ), expectedMissing,
250 'array query parameters are parsed (missing array item)' );
251
252 const paramsWeird = new URLSearchParams( '?foo[0]=a&foo[1][1]=b&foo[x]=c' );
253 const expectedWeird = [ 'a' ];
254 assert.deepEqual( util.getArrayParam( 'foo', paramsWeird ), expectedWeird,
255 'array query parameters are parsed (multi-dimensional or associative arrays are ignored)' );
256
257 const paramsNotArray = new URLSearchParams( '?foo=a' );
258 assert.deepEqual( util.getArrayParam( 'foo', paramsNotArray ), null,
259 'non-array query parameters are ignored' );
260
261 const paramsOther = new URLSearchParams( '?bar[]=a' );
262 assert.deepEqual( util.getArrayParam( 'foo', paramsOther ), null,
263 'other query parameters are ignored' );
264 } );
265
266 function getParents( link ) {
267 return $( link ).parents( '#qunit-fixture *' ).toArray()
268 .map( ( el ) => el.tagName + ( el.className && '.' + el.className ) + ( el.id && '#' + el.id ) );
269 }
270
271 QUnit.test( 'messageBox', ( assert ) => {
272 const message = util.messageBox( 'test' );
273 const errSpan = document.createElement( 'span' );
274 errSpan.textContent = 'error';
275 const errorMessage = util.messageBox( errSpan, 'error' );
276 assert.strictEqual( message.querySelector( '.cdx-message__content' ).textContent, 'test' );
277 assert.strictEqual( errorMessage.querySelector( '.cdx-message__content span' ).textContent, 'error' );
278 assert.true( errorMessage.classList.contains( 'cdx-message--error' ) );
279 } );
280
281 QUnit.test( 'addPortlet does not append to DOM if no `before` is provided', ( assert ) => {
282 $( '#qunit-fixture' ).html(
283 '<div class="portlet" id="p-toolbox"></div>'
284 );
285 const portlet = util.addPortlet( 'test', 'Hello' );
286 assert.true( portlet !== null, 'A portlet node is returned.' );
287 assert.true( portlet.parentNode === null, 'Portlet has no parent node' );
288 } );
289
290 QUnit.test( 'addPortlet returns null if bad selector given', ( assert ) => {
291 $( '#qunit-fixture' ).html(
292 '<div class="portlet" id="p-toolbox"></div>'
293 );
294 const portlet = util.addPortlet( 'test', 'Hello', '#?saasp-toolbox' );
295 assert.true( portlet === null, 'No portlet created.' );
296 } );
297
298 QUnit.test( 'addPortlet appends to DOM if before provided', ( assert ) => {
299 $( '#qunit-fixture' ).html(
300 '<div class="portlet" id="p-toolbox"></div>'
301 );
302 const portlet = util.addPortlet( 'test', 'Hello', '#p-toolbox' );
303 assert.true( !!portlet, 'A portlet node is returned.' );
304 assert.true( portlet.parentNode !== null, 'It is appended to the DOM' );
305 } );
306
307 QUnit.test( 'addPortletLink (Vector list)', ( assert ) => {
308 $( '#qunit-fixture' ).html(
309 '<div class="portlet" id="p-toolbox">' +
310 '<h3>Tools</h3>' +
311 '<div class="body"><ul></ul></div>' +
312 '</div>'
313 );
314 const link = util.addPortletLink( 'p-toolbox', 'https://foo.test/',
315 'Foo', 't-foo', 'Tooltip', 'l'
316 );
317
318 assert.domEqual(
319 link,
320 {
321 tagName: 'LI',
322 attributes: { id: 't-foo', class: 'mw-list-item mw-list-item-js' },
323 contents: [
324 {
325 tagName: 'A',
326 attributes: { href: 'https://foo.test/', title: 'Tooltip [test-l]', accesskey: 'l' },
327 contents: [ 'Foo' ]
328 }
329 ]
330 },
331 'Link element'
332 );
333 assert.propEqual(
334 [ 'UL', 'DIV.body', 'DIV.portlet#p-toolbox' ],
335 getParents( link ),
336 'List structure'
337 );
338 } );
339
340 QUnit.test( 'addPortletLink (Minerva list)', ( assert ) => {
341 $( '#qunit-fixture' ).html( '<ul id="p-list"></ul>' );
342 const link = util.addPortletLink( 'p-list', '#', 'Foo', 't-foo' );
343
344 assert.domEqual(
345 link,
346 {
347 tagName: 'LI',
348 attributes: { id: 't-foo', class: 'mw-list-item mw-list-item-js' },
349 contents: [
350 {
351 tagName: 'A',
352 attributes: { href: '#' },
353 contents: [ 'Foo' ]
354 }
355 ]
356 },
357 'Link element'
358 );
359 assert.propEqual(
360 getParents( link ),
361 [ 'UL#p-list' ],
362 'List structure'
363 );
364 } );
365
366 QUnit.test( 'addPortletLink (nextNode option)', ( assert ) => {
367 $( '#qunit-fixture' ).html( '<ul id="p-toolbox"></ul>' );
368 const linkFoo = util.addPortletLink( 'p-toolbox', 'https://foo.test/',
369 'Foo', 't-foo', 'Tooltip', 'l'
370 );
371
372 let link = util.addPortletLink( 'p-toolbox', '#',
373 'Label', 't-node', null, null, linkFoo );
374 assert.strictEqual( link.nextSibling, linkFoo, 'HTMLElement' );
375
376 link = util.addPortletLink( 'p-toolbox', '#',
377 'Label', 't-selector', null, null, '#t-foo' );
378 assert.strictEqual( link.nextSibling, linkFoo, 'CSS selector' );
379
380 link = util.addPortletLink( 'p-toolbox', '#',
381 'Label', 't-jqueryobj', null, null, $( '#t-foo' ) );
382 assert.strictEqual( link.nextSibling, linkFoo, 'jQuery object' );
383
384 link = util.addPortletLink( 'p-toolbox', '#',
385 'Label', 't-selector-unknown', null, null, '#t-nonexistent' );
386 assert.strictEqual( link.nextSibling, null, 'non-matching CSS selector' );
387
388 link = util.addPortletLink( 'p-toolbox', '#',
389 'Label', 't-jqueryobj-empty', null, null, $( '#t-nonexistent' ) );
390 assert.strictEqual( link.nextSibling, null, 'empty jQuery object' );
391 } );
392
393 QUnit.test( 'addPortletLink (accesskey option)', ( assert ) => {
394 $( '#qunit-fixture' ).html( '<ul id="p-toolbox"></ul>' );
395
396 const link = util.addPortletLink( 'p-toolbox', '#', 'Label', null, 'Tooltip [shift-x]', 'z' );
397 assert.strictEqual(
398 link.querySelector( 'a' ).title,
399 'Tooltip [test-z]',
400 'Change a pre-existing accesskey in a tooltip'
401 );
402 } );
403
404 QUnit.test( 'addPortletLink (nested list)', ( assert ) => {
405 // Regresion test for T37082
406 $( '#qunit-fixture' ).html(
407 '<ul id="p-toolbox">' +
408 '<li id="x-foo"><a href="#">Foo</a></li>' +
409 '<li id="x-bar"><ul><li id="quux"><a href="#">Quux</a></li></ul></li>' +
410 '</ul>'
411 );
412 util.addPortletLink( 'p-toolbox', 'https://example.test/', 'Example' );
413
414 assert.strictEqual(
415 $( 'a[href="https://example.test/"]' ).length,
416 1,
417 'No duplicates created (T37082)'
418 );
419 } );
420
421 QUnit.test( 'validateEmail', ( assert ) => {
422 assert.strictEqual( util.validateEmail( '' ), null, 'Should return null for empty string ' );
423 assert.strictEqual( util.validateEmail( 'user@localhost' ), true, 'Return true for a valid e-mail address' );
424
425 // testEmailWithCommasAreInvalids
426 assert.strictEqual( util.validateEmail( 'user,[email protected]' ), false, 'Emails with commas are invalid' );
427 assert.strictEqual( util.validateEmail( 'userfoo@ex,ample.org' ), false, 'Emails with commas are invalid' );
428
429 // testEmailWithHyphens
430 assert.strictEqual( util.validateEmail( '[email protected]' ), true, 'Emails may contain a hyphen' );
431 assert.strictEqual( util.validateEmail( '[email protected]' ), true, 'Emails may contain a hyphen' );
432 } );
433
434 // Based on mediawiki/libs/IPUtils: provideInvalidIPv4Addresses
435 QUnit.test.each( 'isIPv4Address invalid', [
436 false,
437 true,
438 '',
439 'abc',
440 ':',
441 '124.24.52', // not enough quads
442 '24.324.52.13', // outside of the IPv4 range
443 '.24.52.13',
444 '74.24.52.13/20' // Known difference: mw.util requires individual IP, not IP-range
445 ], ( assert, ip ) => {
446 assert.false( util.isIPv4Address( ip ), String( ip ) );
447 } );
448
449 // Based on mediawiki/libs/IPUtils: provideValidIPv4Address
450 QUnit.test.each( 'isIPv4Address valid', [
451 '124.24.52.13',
452 '1.24.52.13'
453 ], ( assert, ip ) => {
454 assert.true( util.isIPv4Address( ip ), ip );
455 } );
456
457 // Based on mediawiki/libs/IPUtils: testisIPv6
458 QUnit.test.each( 'isIPv6Address invalid', [
459 false,
460 true,
461 ':fc:100::', // starting with lone ":"
462 'fc:100:::', // ending with a tripple ":::"
463 'fc:300', // 2 words
464 'fc:100:300', // 3 words
465 'fc:100:a:d:1:e:ac:0::', // 8 words ending with "::"
466 'fc:100:a:d:1:e:ac:0:1::', // 9 words ending with "::"
467 ':::',
468 '::0:', // ending in a lone ":"
469 '::fc:100:a:d:1:e:ac:0', // 8 words starting with "::"
470 '::fc:100:a:d:1:e:ac:0:1', // 9 words
471 ':fc::100', // starting with lone ":"
472 'fc::100:', // ending with lone ":"
473 'fc:::100', // tripple ":::" in the middle
474 'fc::100:a:d:1:e:ac:0', // 8 words containing double "::"
475 'fc::100:a:d:1:e:ac:0:1' // 9 words
476 ], ( assert, ip ) => {
477 assert.false( util.isIPv6Address( ip ), String( ip ) );
478 } );
479
480 // Based on mediawiki/libs/IPUtils: testisIPv6
481 QUnit.test.each( 'isIPv6Address valid', [
482 '::', // IPv6 zero address
483 'fc::100', // 2 words with double "::"
484 'fc::100:a', // 3 words with double "::"
485 'fc::100:a:d', // 4 words with double "::"
486 'fc::100:a:d:1', // 5 words with double "::"
487 'fc::100:a:d:1:e', // 6 words with double "::"
488 'fc::100:a:d:1:e:ac', // 7 words with double "::"
489 '2001::df',
490 '2001:5c0:1400:a::df',
491 '2001:5c0:1400:a::df:2',
492 'fc:100::',
493 'fc:100:a::',
494 'fc:100:a:d::',
495 'fc:100:a:d:1::',
496 'fc:100:a:d:1:e::',
497 'fc:100:a:d:1:e:ac::',
498 '::0',
499 '::fc',
500 '::fc:100',
501 '::fc:100:a',
502 '::fc:100:a:d',
503 '::fc:100:a:d:1',
504 '::fc:100:a:d:1:e',
505 '::fc:100:a:d:1:e:ac',
506 'fc:100:a:d:1:e:ac:0'
507 ], ( assert, ip ) => {
508 assert.true( util.isIPv6Address( ip ), ip );
509 } );
510
511 QUnit.test.each( 'parseImageUrl', {
512 'Hashed thumb with shortened path': {
513 url: '//upload.wikimedia.org/wikipedia/commons/thumb/b/bf/Princess_Alexandra_of_Denmark_%28later_Queen_Alexandra%2C_wife_of_Edward_VII%29_with_her_two_eldest_sons%2C_Prince_Albert_Victor_%28Eddy%29_and_George_Frederick_Ernest_Albert_%28later_George_V%29.jpg/939px-thumbnail.jpg',
514 name: 'Princess Alexandra of Denmark (later Queen Alexandra, wife of Edward VII) with her two eldest sons, Prince Albert Victor (Eddy) and George Frederick Ernest Albert (later George V).jpg',
515 width: 939,
516 resizedUrl: '//upload.wikimedia.org/wikipedia/commons/thumb/b/bf/Princess_Alexandra_of_Denmark_%28later_Queen_Alexandra%2C_wife_of_Edward_VII%29_with_her_two_eldest_sons%2C_Prince_Albert_Victor_%28Eddy%29_and_George_Frederick_Ernest_Albert_%28later_George_V%29.jpg/1000px-thumbnail.jpg'
517 },
518 'Hashed thumb with sha1-ed path': {
519 url: '//upload.wikimedia.org/wikipedia/commons/thumb/b/bf/Princess_Alexandra_of_Denmark_%28later_Queen_Alexandra%2C_wife_of_Edward_VII%29_with_her_two_eldest_sons%2C_Prince_Albert_Victor_%28Eddy%29_and_George_Frederick_Ernest_Albert_%28later_George_V%29.jpg/939px-ki708pr1r6g2dl5lbhvwdqxenhait13.jpg',
520 name: 'Princess Alexandra of Denmark (later Queen Alexandra, wife of Edward VII) with her two eldest sons, Prince Albert Victor (Eddy) and George Frederick Ernest Albert (later George V).jpg',
521 width: 939,
522 resizedUrl: '//upload.wikimedia.org/wikipedia/commons/thumb/b/bf/Princess_Alexandra_of_Denmark_%28later_Queen_Alexandra%2C_wife_of_Edward_VII%29_with_her_two_eldest_sons%2C_Prince_Albert_Victor_%28Eddy%29_and_George_Frederick_Ernest_Albert_%28later_George_V%29.jpg/1000px-ki708pr1r6g2dl5lbhvwdqxenhait13.jpg'
523 },
524 'Normal hashed directory thumbnail': {
525 url: '/wiki/images/thumb/9/91/Anticlockwise_heliotrope%27s.jpg/99px-Anticlockwise_heliotrope%27s.jpg',
526 name: 'Anticlockwise heliotrope\'s.jpg',
527 width: 99,
528 resizedUrl: '/wiki/images/thumb/9/91/Anticlockwise_heliotrope%27s.jpg/1000px-Anticlockwise_heliotrope%27s.jpg'
529 },
530 'Normal hashed directory thumbnail with complex thumbnail parameters': {
531 url: '/wiki/images/thumb/8/80/Wikipedia-logo-v2.svg/langde-150px-Wikipedia-logo-v2.svg.png',
532 name: 'Wikipedia-logo-v2.svg',
533 width: 150,
534 resizedUrl: '/wiki/images/thumb/8/80/Wikipedia-logo-v2.svg/langde-1000px-Wikipedia-logo-v2.svg.png'
535 },
536 'Width-like filename component': {
537 url: '/wiki/images/thumb/1/10/Little_Bobby_Tables-100px-file.jpg/qlow-100px-Little_Bobby_Tables-100px-file.jpg',
538 name: 'Little Bobby Tables-100px-file.jpg',
539 width: 100,
540 resizedUrl: '/wiki/images/thumb/1/10/Little_Bobby_Tables-100px-file.jpg/qlow-1000px-Little_Bobby_Tables-100px-file.jpg'
541 },
542 'Width-like filename component in non-ASCII filename': {
543 url: '/wiki/images/thumb/1/10/Little_Bobby%22%3B_Tables-100px-file.jpg/qlow-100px-Little_Bobby%22%3B_Tables-100px-file.jpg',
544 name: 'Little Bobby"; Tables-100px-file.jpg',
545 width: 100,
546 resizedUrl: '/wiki/images/thumb/1/10/Little_Bobby%22%3B_Tables-100px-file.jpg/qlow-1000px-Little_Bobby%22%3B_Tables-100px-file.jpg'
547 },
548
549 'Commons thumbnail': {
550 url: '//upload.wikimedia.org/wikipedia/commons/thumb/8/80/Wikipedia-logo-v2.svg/150px-Wikipedia-logo-v2.svg.png',
551 name: 'Wikipedia-logo-v2.svg',
552 width: 150,
553 resizedUrl: '//upload.wikimedia.org/wikipedia/commons/thumb/8/80/Wikipedia-logo-v2.svg/1000px-Wikipedia-logo-v2.svg.png'
554 },
555 'Full image': {
556 url: '/wiki/images/9/91/Anticlockwise_heliotrope%27s.jpg',
557 name: 'Anticlockwise heliotrope\'s.jpg',
558 width: null
559 },
560 'thumb.php-based thumbnail': {
561 url: 'http://localhost/thumb.php?f=Stuffless_Figaro%27s.jpg&width=180',
562 name: 'Stuffless Figaro\'s.jpg',
563 width: 180,
564 resizedUrl: 'http://localhost/thumb.php?f=Stuffless_Figaro%27s.jpg&width=1000'
565 },
566 'thumb.php-based thumbnail with px width': {
567 url: 'http://localhost/thumb.php?f=Stuffless_Figaro%27s.jpg&width=180px',
568 name: 'Stuffless Figaro\'s.jpg',
569 width: 180,
570 resizedUrl: 'http://localhost/thumb.php?f=Stuffless_Figaro%27s.jpg&width=1000'
571 },
572 'thumb.php-based BC thumbnail': {
573 url: 'http://localhost/thumb.php?f=Stuffless_Figaro%27s.jpg&w=180',
574 name: 'Stuffless Figaro\'s.jpg',
575 width: 180,
576 resizedUrl: 'http://localhost/thumb.php?f=Stuffless_Figaro%27s.jpg&width=1000'
577 },
578 'Commons unhashed thumbnail': {
579 url: '/wikipedia/commons/thumb/Wikipedia-logo-v2.svg/150px-Wikipedia-logo-v2.svg.png',
580 name: 'Wikipedia-logo-v2.svg',
581 width: 150,
582 resizedUrl: '/wikipedia/commons/thumb/Wikipedia-logo-v2.svg/1000px-Wikipedia-logo-v2.svg.png'
583 },
584 'Commons unhashed thumbnail with complex thumbnail parameters': {
585 url: '/wikipedia/commons/thumb/Wikipedia-logo-v2.svg/langde-150px-Wikipedia-logo-v2.svg.png',
586 name: 'Wikipedia-logo-v2.svg',
587 width: 150,
588 resizedUrl: '/wikipedia/commons/thumb/Wikipedia-logo-v2.svg/langde-1000px-Wikipedia-logo-v2.svg.png'
589 },
590 'Unhashed local file': {
591 url: '/wiki/images/Anticlockwise_heliotrope%27s.jpg',
592 name: 'Anticlockwise heliotrope\'s.jpg',
593 width: null
594 },
595 'Empty string': {
596 url: ''
597 },
598 'String with only alphabet characters': {
599 url: 'foo'
600 },
601 'Not a file path': {
602 url: 'foobar.foobar'
603 },
604 'Space characters': {
605 url: '/a/a0/blah blah blah'
606 }
607 }, ( assert, thisCase ) => {
608 mw.util.setOptionsForTest( { GenerateThumbnailOnParse: false } );
609 const data = mw.util.parseImageUrl( thisCase.url );
610 if ( !thisCase.name ) {
611 assert.strictEqual( data, null, 'return null' );
612 return;
613 }
614
615 assert.strictEqual( typeof data, 'object', 'return object' );
616 assert.strictEqual( data.name, thisCase.name, 'file name' );
617 assert.strictEqual( data.width, thisCase.width, 'width' );
618 if ( thisCase.resizedUrl ) {
619 assert.strictEqual( typeof data.resizeUrl, 'function', 'resizeUrl type' );
620 assert.strictEqual( data.resizeUrl( 1000 ), thisCase.resizedUrl, 'resizeUrl return' );
621 } else {
622 assert.strictEqual( data.resizeUrl, null, 'resizeUrl is not set' );
623 }
624 } );
625
626 QUnit.test( 'parseImageUrl [no dynamic thumbnail generation]', function ( assert ) {
627 mw.util.setOptionsForTest( { GenerateThumbnailOnParse: true } );
628 this.sandbox.stub( mw.config.values, 'wgScript', '/w' );
629
630 const resizeUrl = mw.util.parseImageUrl( '//upload.wikimedia.org/wikipedia/commons/thumb/b/bf/Princess_Alexandra_of_Denmark_%28later_Queen_Alexandra%2C_wife_of_Edward_VII%29_with_her_two_eldest_sons%2C_Prince_Albert_Victor_%28Eddy%29_and_George_Frederick_Ernest_Albert_%28later_George_V%29.jpg/939px-thumbnail.jpg' ).resizeUrl;
631
632 assert.strictEqual( typeof resizeUrl, 'function', 'resizeUrl is set' );
633 assert.strictEqual( resizeUrl( 500 ), '/w?title=Special:Redirect/file/Princess_Alexandra_of_Denmark_(later_Queen_Alexandra,_wife_of_Edward_VII)_with_her_two_eldest_sons,_Prince_Albert_Victor_(Eddy)_and_George_Frederick_Ernest_Albert_(later_George_V).jpg&width=500', 'Resized URL is correct' );
634 } );
635
636 QUnit.test.each( 'adjustThumbWidthForSteps', {
637 'unchanged when disabled': {
638 enabled: false,
639 originalWidth: 500,
640 thumbWidth: 52,
641 expected: 52
642 },
643 'round up': {
644 enabled: true,
645 originalWidth: 500,
646 thumbWidth: 52,
647 expected: 100
648 },
649 'original width when first step beyond original width': {
650 enabled: true,
651 originalWidth: 90,
652 thumbWidth: 52,
653 expected: 90
654 },
655 'original width when no other step between requested & original width': {
656 enabled: true,
657 originalWidth: 180,
658 thumbWidth: 130,
659 expected: 180
660 },
661 'unchanged when beyond available steps': {
662 enabled: true,
663 originalWidth: 500,
664 thumbWidth: 252,
665 expected: 252
666 }
667 }, ( assert, data ) => {
668 // See also server-side logic test for File::adjustThumbWidthForSteps in FileTest.php
669 mw.util.setOptionsForTest( {
670 ThumbnailSteps: [ 100, 200 ],
671 ThumbnailStepsRatio: data.enabled ? 1 : 0
672 } );
673
674 const actual = mw.util.adjustThumbWidthForSteps( data.thumbWidth, data.originalWidth );
675 assert.strictEqual( actual, data.expected );
676 } );
677
678 QUnit.test( 'escapeRegExp [normal]', ( assert ) => {
679 const normal = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' +
680 'abcdefghijklmnopqrstuvwxyz' +
681 '0123456789';
682 assert.strictEqual( mw.util.escapeRegExp( normal ), normal, 'Alphanumerals are left alone' );
683 } );
684
685 QUnit.test.each( 'escapeRegExp [specials]', [
686 '\\',
687 '{',
688 '}',
689 '(',
690 ')',
691 '[',
692 ']',
693 '|',
694 '.',
695 '?',
696 '*',
697 '+',
698 '-',
699 '^',
700 '$'
701 ], ( assert, str ) => {
702 assert.propEqual(
703
704 str.match( new RegExp( mw.util.escapeRegExp( str ) ) ),
705 [ str ],
706 'confirm correct escaping by being able to match itself'
707 );
708 } );
709
710 QUnit.test( 'debounce(Function, timeout)', async function ( assert ) {
711 const fn = mw.util.debounce( ( data ) => {
712 assert.step( data );
713 }, 5 );
714
715 fn( 'A' );
716 setTimeout( () => {
717 fn( 'B' );
718 }, 1 );
719 this.sandbox.clock.tick( 2 );
720 setTimeout( () => {
721 fn( 'C' );
722 }, 1 );
723 this.sandbox.clock.tick( 2 );
724 this.sandbox.clock.tick( 10 );
725
726 assert.verifySteps( [ 'C' ] );
727 } );
728
729 QUnit.test( 'debounce(Function, timeout, immediate=true)', async function ( assert ) {
730 const fn = mw.util.debounce( ( data ) => {
731 assert.step( data );
732 }, 5, true );
733
734 fn( 'A' );
735 setTimeout( () => {
736 fn( 'B' );
737 }, 1 );
738 this.sandbox.clock.tick( 2 );
739 setTimeout( () => {
740 fn( 'C' );
741 }, 1 );
742 this.sandbox.clock.tick( 2 );
743 this.sandbox.clock.tick( 10 );
744
745 assert.verifySteps( [ 'A' ] );
746 } );
747
748 QUnit.test( 'debounce(timeout, Function) [old signature]', async function ( assert ) {
749 const fn = mw.util.debounce( 5, ( data ) => {
750 assert.step( data );
751 } );
752
753 fn( 'A' );
754 setTimeout( () => {
755 fn( 'B' );
756 }, 1 );
757 this.sandbox.clock.tick( 2 );
758 setTimeout( () => {
759 fn( 'C' );
760 }, 1 );
761 this.sandbox.clock.tick( 2 );
762 this.sandbox.clock.tick( 10 );
763
764 assert.verifySteps( [ 'C' ] );
765 } );
766
767 QUnit.test( 'init (.mw-body-primary)', ( assert ) => {
768 const node = $( '<div class="mw-body-primary mw-body">primary</div>' )[ 0 ];
769 $( '#qunit-fixture' ).append(
770 '<div id="mw-content-text"></div>',
771 '<div class="mw-body"></div>',
772 node
773 );
774
775 util.init();
776 assert.strictEqual( mw.util.$content[ 0 ], node );
777 } );
778
779 QUnit.test( 'init (first of multiple .mw-body)', ( assert ) => {
780 const node = $( '<div class="mw-body">first</div>' )[ 0 ];
781 $( '#qunit-fixture' ).append(
782 '<div id="mw-content-text"></div>',
783 node,
784 '<div class="mw-body">second</div>'
785 );
786
787 util.init();
788 assert.true( util.$content instanceof $, 'jQuery object' );
789 assert.strictEqual( mw.util.$content[ 0 ], node, 'node' );
790 assert.strictEqual( mw.util.$content.length, 1, 'length' );
791 } );
792
793 QUnit.test( 'init (#mw-content-text fallback)', ( assert ) => {
794 const node = $( '<div id="mw-content-text">fallback</div>' )[ 0 ];
795 $( '#qunit-fixture' ).append(
796 node
797 );
798
799 util.init();
800 assert.true( util.$content instanceof $, 'jQuery object' );
801 assert.strictEqual( mw.util.$content[ 0 ], node, 'node' );
802 assert.strictEqual( mw.util.$content.length, 1, 'length' );
803 } );
804
805 QUnit.test( 'init (body fallback)', ( assert ) => {
806 util.init();
807 assert.true( util.$content instanceof $, 'jQuery object' );
808 assert.strictEqual( mw.util.$content[ 0 ], document.body, 'node' );
809 assert.strictEqual( mw.util.$content.length, 1, 'length' );
810 } );
811
812 QUnit.test.each( 'sanitizeIP', {
813 'IPv6 with "::" and 2 words': [ 'FC:0:0:0:0:0:0:100', 'fc::100' ],
814 'IPv6 with "::" and 3 words': [ 'FC:0:0:0:0:0:100:A', 'fc::100:a' ],
815 'IPv6 with "::" and 4 words': [ 'FC:0:0:0:0:100:A:D', 'fc::100:a:d' ],
816 'IPv6 with "::" and 5 words': [ 'FC:0:0:0:100:A:D:1', 'fc::100:a:d:1' ],
817 'IPv6 with "::" and 6 words': [ 'FC:0:0:100:A:D:1:E', 'fc::100:a:d:1:e' ],
818 'IPv6 with "::" and 7 words': [ 'FC:0:100:A:D:1:E:AC', 'fc::100:a:d:1:e:ac' ],
819 // https://www.apnic.net/get-ip/faqs/what-is-an-ip-address/ipv6-address-types/
820 'IPv6 with "::" and 2 words (Teredo)': [ '2001:0:0:0:0:0:0:DF', '2001::df' ],
821 'IPv6 with "::" and 5 words (Teredo)': [ '2001:5C0:1400:A:0:0:0:DF', '2001:5c0:1400:a::df' ],
822 'IPv6 with "::" and 6 words (Teredo)': [ '2001:5C0:1400:A:0:0:DF:2', '2001:5c0:1400:a::df:2' ],
823 'IPv6 range with "::" and 6 words (Teredo)': [ '2001:DB8:A:0:0:0:0:123/64', '2001:db8:a::123/64' ],
824 'IPv4 no change': [ '1.24.52.13', '1.24.52.13' ],
825 'IPv4 strip leading 0s': [ '1.24.52.13', '01.024.052.013' ],
826 'IPv4 strip multiple leading 0s': [ '1.2.5.1', '001.002.005.001' ],
827 'IPv4 don\'t strip meaningful trailing 0s': [ '100.240.52.130', '100.240.52.130' ],
828 'IPv4 strip meaningless multiple 0s': [ '0.0.52.0', '00.000.52.00' ],
829 'IPv4 range strip meaningless multiple 0s': [ '0.0.52.0/32', '00.000.52.00/32' ],
830 'Not an IP': [ 'not an IP', 'not an IP' ],
831 'Empty string': [ null, ' ' ],
832 'IPv4 trim whitespace from start and end of the string': [ '1.24.52.13', ' 1.24.52.13 ' ],
833 'IPv6 starts with ::': [ '0:0:0:0:0:0:0:1', '::1' ],
834 'IPv6 remove leading zeros from each block.': [ '2001:DB8:0:0:0:FF00:42:8329', '2001:0db8:0000:0000:0000:ff00:0042:8329' ],
835 'IPv6 :: at the end': [ 'FE80:0:0:0:0:0:0:0/10', 'fe80::/10' ],
836 'Non-IP string': [ 'UserName', 'UserName' ],
837 'Non-string': [ null, null ]
838 }, ( assert, [ expected, input ] ) => {
839 assert.strictEqual( util.sanitizeIP( input ), expected );
840 } );
841
842 QUnit.test.each( 'prettifyIP', {
843 'IPv6 change to lowercase': [ 'fc::100', 'FC::100' ],
844 'IPv4 no change': [ '1.24.52.13', '1.24.52.13' ],
845 'IPv4 range strip meaningless multiple 0s': [ '0.0.52.0/32', '00.000.52.00/32' ],
846 'Empty string': [ null, ' ' ],
847 'IPv6 range Replace consecutive zeros with :: ': [ '2001:db8:a::123/64', '2001:db8:a:0000:0000:0000:0000:123/64' ],
848 'IPv6 middle only consecutive zeros with ::': [ '2001:db8::ff00:42:8329', '2001:DB8:0:0:0:FF00:42:8329' ],
849 'IPv6 first longer consecutive zeros with ::': [ '2001::15:0:0:1a2b', '2001:0000:0000:0000:0015:0000:0000:1a2b' ],
850 'IPv6 last longer consecutive zeros with ::': [ '2001:0:0:15::1a2b', '2001:0000:0000:0015:0000:0000:0000:1a2b' ],
851 'IPv6 first of equal length consecutive zeros with ::': [ '2001::15:0:0:3:1a2b', '2001:0000:0000:0015:0000:0000:0003:1a2b' ]
852 }, ( assert, [ expected, input ] ) => {
853 assert.strictEqual( util.prettifyIP( input ), expected );
854 } );
855
856 QUnit.test.each( 'isTemporaryUser', {
857 'prefix mismatch': [ '*$1', 'Test', false, true ],
858 'prefix match': [ '*$1', '*Some user', true, true ],
859 'suffix only match': [ '$1*', 'Some user*', true, true ],
860 'suffix only mismatch': [ '$1*', 'Some user', false, true ],
861 'prefix and suffix match': [ '*$1*', '*Unregistered 123*', true, true ],
862 'prefix and suffix mismatch': [ '*$1*', 'Unregistered 123*', false, true ],
863 'prefix and suffix zero length match': [ '*$1*', '**', true, true ],
864 'prefix and suffix overlapping': [ '*$1*', '*', false, true ],
865 'multiple patterns prefix match': [ [ '*$1', '~$1' ], '~Some user', true, true ],
866 'multiple patterns prefix mismatch': [ [ '*$1', '~$1' ], 'Some user', false, true ],
867 'multiple patterns suffix match': [ [ '*$1', '$1~' ], 'Some user~', true, true ],
868 'multiple patterns suffix mismatch': [ [ '*$1', '$1~' ], 'Some user', false, true ],
869 'multiple patterns prefix and suffix match': [ [ '*$1*', '$1~' ], '*Unregistered 123*', true, true ],
870 'Auto create temporary user disabled': [ '*$1*', '*', false, false ],
871 'null username': [ '*$1', null, false, true ]
872 }, ( assert, username ) => {
873 mw.util.setOptionsForTest( {
874 AutoCreateTempUser: { enabled: username[ 3 ], matchPattern: username[ 0 ] }
875 } );
876
877 assert.strictEqual( util.isTemporaryUser( username[ 1 ] ), username[ 2 ] );
878 } );
879
880 QUnit.test.each( 'isTemporaryUser matchPattern null', {
881 'prefix mismatch': [ '*$1', 'Test', false, true ],
882 'prefix match': [ '*$1', '*Some user', true, true ]
883 }, ( assert, username ) => {
884 mw.util.setOptionsForTest( {
885 AutoCreateTempUser: { enabled: username[ 3 ], genPattern: username[ 0 ], matchPattern: null }
886 } );
887
888 assert.strictEqual( util.isTemporaryUser( username[ 1 ] ), username[ 2 ] );
889 } );
890
891 QUnit.test( 'isInfinity', ( assert ) => {
892 assert.true( util.isInfinity( 'indefinite' ) );
893 assert.true( util.isInfinity( 'infinite' ) );
894 assert.true( util.isInfinity( 'infinity' ) );
895 assert.true( util.isInfinity( 'never' ) );
896 assert.false( util.isInfinity( '' ) );
897 assert.false( util.isInfinity( null ) );
898 } );
899 } );