diff options
Diffstat (limited to 'tests/qunit/suites')
34 files changed, 8469 insertions, 0 deletions
diff --git a/tests/qunit/suites/resources/jquery/jquery.accessKeyLabel.test.js b/tests/qunit/suites/resources/jquery/jquery.accessKeyLabel.test.js new file mode 100644 index 00000000..f6ea1b48 --- /dev/null +++ b/tests/qunit/suites/resources/jquery/jquery.accessKeyLabel.test.js @@ -0,0 +1,108 @@ +( function ( $ ) { + QUnit.module( 'jquery.accessKeyLabel', QUnit.newMwEnvironment( { + messages: { + 'brackets': '[$1]', + 'word-separator': ' ' + } + } ) ); + + var getAccessKeyPrefixTestData = [ + //ua string, platform string, expected prefix + // Internet Explorer + ['Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)', 'Win32', 'alt-'], + ['Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)', 'Win32', 'alt-'], + ['Mozilla/5.0 (Windows NT 6.3; Win64; x64; Trident/7.0; rv:11.0) like Gecko', 'Win64', 'alt-'], + // Firefox + ['Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.1.19) Gecko/20110420 Firefox/3.5.19', 'MacIntel', 'ctrl-'], + ['Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.17) Gecko/20110422 Ubuntu/10.10 (maverick) Firefox/3.6.17', 'Linux i686', 'alt-shift-'], + ['Mozilla/5.0 (Windows NT 6.0; rv:2.0.1) Gecko/20100101 Firefox/4.0.1', 'Win32', 'alt-shift-'], + // Safari / Konqueror + ['Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_7; nl-nl) AppleWebKit/531.22.7 (KHTML, like Gecko) Version/4.0.5 Safari/531.22.7', 'MacIntel', 'ctrl-alt-'], + ['Mozilla/5.0 (Windows; U; Windows NT 6.0; cs-CZ) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/4.0.5 Safari/531.22.7', 'Win32', 'alt-'], + ['Mozilla/5.0 (X11; Linux i686) KHTML/4.9.1 (like Gecko) Konqueror/4.9', 'Linux i686', 'ctrl-'], + // Opera + ['Opera/9.80 (Windows NT 5.1)', 'Win32', 'shift-esc-'], + ['Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.52 Safari/537.36 OPR/15.0.1147.130', 'Win32', 'shift-esc-'], + // Chrome + ['Mozilla/5.0 (Macintosh; Intel Mac OS X 10_5_8) AppleWebKit/534.30 (KHTML, like Gecko) Chrome/12.0.742.112 Safari/534.30', 'MacIntel', 'ctrl-option-'], + ['Mozilla/5.0 (X11; Linux i686) AppleWebKit/534.30 (KHTML, like Gecko) Chrome/12.0.742.68 Safari/534.30', 'Linux i686', 'alt-shift-'] + ], + //strings appended to title to make sure updateTooltipAccessKeys handles them correctly + updateTooltipAccessKeysTestData = [ '', ' [a]', ' [test-a]', ' [alt-b]' ]; + + function makeInput( title, accessKey ) { + //The properties aren't escaped, so make sure you don't call this function with values that need to be escaped! + return '<input title="' + title + '" ' + ( accessKey ? 'accessKey="' + accessKey + '" ' : '' ) + ' />'; + } + + QUnit.test( 'getAccessKeyPrefix', getAccessKeyPrefixTestData.length, function ( assert ) { + var i; + for ( i = 0; i < getAccessKeyPrefixTestData.length; i++ ) { + assert.equal( $.fn.updateTooltipAccessKeys.getAccessKeyPrefix( { + userAgent: getAccessKeyPrefixTestData[i][0], + platform: getAccessKeyPrefixTestData[i][1] + } ), getAccessKeyPrefixTestData[i][2], 'Correct prefix for ' + getAccessKeyPrefixTestData[i][0] ); + } + } ); + + QUnit.test( 'updateTooltipAccessKeys - current browser', 2, function ( assert ) { + var title = $( makeInput ( 'Title', 'a' ) ).updateTooltipAccessKeys().prop( 'title' ), + //The new title should be something like "Title [alt-a]", but the exact label will depend on the browser. + //The "a" could be capitalized, and the prefix could be anything, e.g. a simple "^" for ctrl- + //(no browser is known using such a short prefix, though) or "Alt+Umschalt+" in German Firefox. + result = /^Title \[(.+)[aA]\]$/.exec( title ); + assert.ok( result, 'title should match expected structure.' ); + assert.notEqual( result[1], 'test-', 'Prefix used for testing shouldn\'t be used in production.' ); + } ); + + QUnit.test( 'updateTooltipAccessKeys - no access key', updateTooltipAccessKeysTestData.length, function ( assert ) { + var i, oldTitle, $input, newTitle; + for ( i = 0; i < updateTooltipAccessKeysTestData.length; i++ ) { + oldTitle = 'Title' + updateTooltipAccessKeysTestData[i]; + $input = $( makeInput( oldTitle ) ); + $( '#qunit-fixture' ).append( $input ); + newTitle = $input.updateTooltipAccessKeys().prop( 'title' ); + assert.equal( newTitle, 'Title', 'title="' + oldTitle + '"' ); + } + } ); + + QUnit.test( 'updateTooltipAccessKeys - with access key', updateTooltipAccessKeysTestData.length, function ( assert ) { + $.fn.updateTooltipAccessKeys.setTestMode( true ); + var i, oldTitle, $input, newTitle; + for ( i = 0; i < updateTooltipAccessKeysTestData.length; i++ ) { + oldTitle = 'Title' + updateTooltipAccessKeysTestData[i]; + $input = $( makeInput( oldTitle, 'a' ) ); + $( '#qunit-fixture' ).append( $input ); + newTitle = $input.updateTooltipAccessKeys().prop( 'title' ); + assert.equal( newTitle, 'Title [test-a]', 'title="' + oldTitle + '"' ); + } + $.fn.updateTooltipAccessKeys.setTestMode( false ); + } ); + + QUnit.test( 'updateTooltipAccessKeys with label element', 2, function ( assert ) { + $.fn.updateTooltipAccessKeys.setTestMode( true ); + var html = '<label for="testInput" title="Title">Label</label><input id="testInput" accessKey="a" />', + $label, $input; + $( '#qunit-fixture' ).html( html ); + $label = $( '#qunit-fixture label' ); + $input = $( '#qunit-fixture input' ); + $input.updateTooltipAccessKeys(); + assert.equal( $input.prop( 'title' ), '', 'No title attribute added to input element.' ); + assert.equal( $label.prop( 'title' ), 'Title [test-a]', 'title updated for associated label element.' ); + $.fn.updateTooltipAccessKeys.setTestMode( false ); + } ); + + QUnit.test( 'updateTooltipAccessKeys with label element as parent', 2, function ( assert ) { + $.fn.updateTooltipAccessKeys.setTestMode( true ); + var html = '<label title="Title">Label<input id="testInput" accessKey="a" /></label>', + $label, $input; + $( '#qunit-fixture' ).html( html ); + $label = $( '#qunit-fixture label' ); + $input = $( '#qunit-fixture input' ); + $input.updateTooltipAccessKeys(); + assert.equal( $input.prop( 'title' ), '', 'No title attribute added to input element.' ); + assert.equal( $label.prop( 'title' ), 'Title [test-a]', 'title updated for associated label element.' ); + $.fn.updateTooltipAccessKeys.setTestMode( false ); + } ); + +}( jQuery ) ); diff --git a/tests/qunit/suites/resources/jquery/jquery.autoEllipsis.test.js b/tests/qunit/suites/resources/jquery/jquery.autoEllipsis.test.js new file mode 100644 index 00000000..e8c51214 --- /dev/null +++ b/tests/qunit/suites/resources/jquery/jquery.autoEllipsis.test.js @@ -0,0 +1,53 @@ +( function ( $ ) { + + QUnit.module( 'jquery.autoEllipsis', QUnit.newMwEnvironment() ); + + function createWrappedDiv( text, width ) { + var $wrapper = $( '<div>' ).css( 'width', width ), + $div = $( '<div>' ).text( text ); + $wrapper.append( $div ); + return $wrapper; + } + + function findDivergenceIndex( a, b ) { + var i = 0; + while ( i < a.length && i < b.length && a[i] === b[i] ) { + i++; + } + return i; + } + + QUnit.test( 'Position right', 4, function ( assert ) { + // We need this thing to be visible, so append it to the DOM + var $span, spanText, d, spanTextNew, + origText = 'This is a really long random string and there is no way it fits in 100 pixels.', + $wrapper = createWrappedDiv( origText, '100px' ); + + $( '#qunit-fixture' ).append( $wrapper ); + $wrapper.autoEllipsis( { position: 'right' } ); + + // Verify that, and only one, span element was created + $span = $wrapper.find( '> span' ); + assert.strictEqual( $span.length, 1, 'autoEllipsis wrapped the contents in a span element' ); + + // Check that the text fits by turning on word wrapping + $span.css( 'whiteSpace', 'nowrap' ); + assert.ltOrEq( + $span.width(), + $span.parent().width(), + 'Text fits (making the span "white-space: nowrap" does not make it wider than its parent)' + ); + + // Add two characters using scary black magic + spanText = $span.text(); + d = findDivergenceIndex( origText, spanText ); + spanTextNew = spanText.slice( 0, d ) + origText[d] + origText[d] + '...'; + + assert.gt( spanTextNew.length, spanText.length, 'Verify that the new span-length is indeed greater' ); + + // Put this text in the span and verify it doesn't fit + $span.text( spanTextNew ); + assert.gt( $span.width(), $span.parent().width(), 'Fit is maximal (adding two characters makes it not fit any more)' ); + } ); + +}( jQuery ) ); diff --git a/tests/qunit/suites/resources/jquery/jquery.byteLength.test.js b/tests/qunit/suites/resources/jquery/jquery.byteLength.test.js new file mode 100644 index 00000000..e6aa3aa8 --- /dev/null +++ b/tests/qunit/suites/resources/jquery/jquery.byteLength.test.js @@ -0,0 +1,37 @@ +( function ( $ ) { + QUnit.module( 'jquery.byteLength', QUnit.newMwEnvironment() ); + + QUnit.test( 'Simple text', 5, function ( assert ) { + var azLc = 'abcdefghijklmnopqrstuvwxyz', + azUc = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', + num = '0123456789', + x = '*', + space = ' '; + + assert.equal( $.byteLength( azLc ), 26, 'Lowercase a-z' ); + assert.equal( $.byteLength( azUc ), 26, 'Uppercase A-Z' ); + assert.equal( $.byteLength( num ), 10, 'Numbers 0-9' ); + assert.equal( $.byteLength( x ), 1, 'An asterisk' ); + assert.equal( $.byteLength( space ), 3, '3 spaces' ); + + } ); + + QUnit.test( 'Special text', 4, function ( assert ) { + // https://en.wikipedia.org/wiki/UTF-8 + var u0024 = '$', + // Cent symbol + u00A2 = '\u00A2', + // Euro symbol + u20AC = '\u20AC', + // Character \U00024B62 (Han script) can't be represented in javascript as a single + // code point, instead it is composed as a surrogate pair of two separate code units. + // http://codepoints.net/U+24B62 + // http://www.fileformat.info/info/unicode/char/24B62/index.htm + u024B62 = '\uD852\uDF62'; + + assert.strictEqual( $.byteLength( u0024 ), 1, 'U+0024' ); + assert.strictEqual( $.byteLength( u00A2 ), 2, 'U+00A2' ); + assert.strictEqual( $.byteLength( u20AC ), 3, 'U+20AC' ); + assert.strictEqual( $.byteLength( u024B62 ), 4, 'U+024B62 (surrogate pair: \\uD852\\uDF62)' ); + } ); +}( jQuery ) ); diff --git a/tests/qunit/suites/resources/jquery/jquery.byteLimit.test.js b/tests/qunit/suites/resources/jquery/jquery.byteLimit.test.js new file mode 100644 index 00000000..22d2af19 --- /dev/null +++ b/tests/qunit/suites/resources/jquery/jquery.byteLimit.test.js @@ -0,0 +1,252 @@ +( function ( $, mw ) { + var simpleSample, U_20AC, mbSample; + + QUnit.module( 'jquery.byteLimit', QUnit.newMwEnvironment() ); + + // Simple sample (20 chars, 20 bytes) + simpleSample = '12345678901234567890'; + + // 3 bytes (euro-symbol) + U_20AC = '\u20AC'; + + // Multi-byte sample (22 chars, 26 bytes) + mbSample = '1234567890' + U_20AC + '1234567890' + U_20AC; + + // Basic sendkey-implementation + function addChars( $input, charstr ) { + var c, len; + + function x( $input, i ) { + // Add character to the value + return $input.val() + charstr.charAt( i ); + } + + for ( c = 0, len = charstr.length; c < len; c += 1 ) { + $input + .val( x( $input, c ) ) + .trigger( 'change' ); + } + } + + /** + * Test factory for $.fn.byteLimit + * + * @param {Object} options + * @param {string} options.description Test name + * @param {jQuery} options.$input jQuery object in an input element + * @param {string} options.sample Sequence of characters to simulate being + * added one by one + * @param {string} options.expected Expected final value of `$input` + */ + function byteLimitTest( options ) { + var opt = $.extend( { + description: '', + $input: null, + sample: '', + expected: '' + }, options ); + + QUnit.asyncTest( opt.description, 1, function ( assert ) { + setTimeout( function () { + opt.$input.appendTo( '#qunit-fixture' ); + + // Simulate pressing keys for each of the sample characters + addChars( opt.$input, opt.sample ); + + assert.equal( + opt.$input.val(), + opt.expected, + 'New value matches the expected string' + ); + + QUnit.start(); + }, 10 ); + } ); + } + + byteLimitTest( { + description: 'Plain text input', + $input: $( '<input type="text"/>' ), + sample: simpleSample, + expected: simpleSample + } ); + + byteLimitTest( { + description: 'Plain text input. Calling byteLimit with no parameters and no maxlength attribute (bug 36310)', + $input: $( '<input type="text"/>' ) + .byteLimit(), + sample: simpleSample, + expected: simpleSample + } ); + + byteLimitTest( { + description: 'Limit using the maxlength attribute', + $input: $( '<input type="text"/>' ) + .attr( 'maxlength', '10' ) + .byteLimit(), + sample: simpleSample, + expected: '1234567890' + } ); + + byteLimitTest( { + description: 'Limit using a custom value', + $input: $( '<input type="text"/>' ) + .byteLimit( 10 ), + sample: simpleSample, + expected: '1234567890' + } ); + + byteLimitTest( { + description: 'Limit using a custom value, overriding maxlength attribute', + $input: $( '<input type="text"/>' ) + .attr( 'maxlength', '10' ) + .byteLimit( 15 ), + sample: simpleSample, + expected: '123456789012345' + } ); + + byteLimitTest( { + description: 'Limit using a custom value (multibyte)', + $input: $( '<input type="text"/>' ) + .byteLimit( 14 ), + sample: mbSample, + expected: '1234567890' + U_20AC + '1' + } ); + + byteLimitTest( { + description: 'Limit using a custom value (multibyte) overlapping a byte', + $input: $( '<input type="text"/>' ) + .byteLimit( 12 ), + sample: mbSample, + expected: '1234567890' + '12' + } ); + + byteLimitTest( { + description: 'Pass the limit and a callback as input filter', + $input: $( '<input type="text"/>' ) + .byteLimit( 6, function ( val ) { + var title = mw.Title.newFromText( String( val ) ); + // Return without namespace prefix + return title ? title.getMain() : ''; + } ), + sample: 'User:Sample', + expected: 'User:Sample' + } ); + + byteLimitTest( { + description: 'Limit using the maxlength attribute and pass a callback as input filter', + $input: $( '<input type="text"/>' ) + .attr( 'maxlength', '6' ) + .byteLimit( function ( val ) { + var title = mw.Title.newFromText( String( val ) ); + // Return without namespace prefix + return title ? title.getMain() : ''; + } ), + sample: 'User:Sample', + expected: 'User:Sample' + } ); + + byteLimitTest( { + description: 'Pass the limit and a callback as input filter', + $input: $( '<input type="text"/>' ) + .byteLimit( 6, function ( val ) { + var title = mw.Title.newFromText( String( val ) ); + // Return without namespace prefix + return title ? title.getMain() : ''; + } ), + sample: 'User:Example', + // The callback alters the value to be used to calculeate + // the length. The altered value is "Exampl" which has + // a length of 6, the "e" would exceed the limit. + expected: 'User:Exampl' + } ); + + byteLimitTest( { + description: 'Input filter that increases the length', + $input: $( '<input type="text"/>' ) + .byteLimit( 10, function ( text ) { + return 'prefix' + text; + } ), + sample: simpleSample, + // Prefix adds 6 characters, limit is reached after 4 + expected: '1234' + } ); + + // Regression tests for bug 41450 + byteLimitTest( { + description: 'Input filter of which the base exceeds the limit', + $input: $( '<input type="text"/>' ) + .byteLimit( 3, function ( text ) { + return 'prefix' + text; + } ), + sample: simpleSample, + hasLimit: true, + limit: 6, // 'prefix' length + expected: '' + } ); + + QUnit.test( 'Confirm properties and attributes set', 4, function ( assert ) { + var $el, $elA, $elB; + + $el = $( '<input type="text"/>' ) + .attr( 'maxlength', '7' ) + .appendTo( '#qunit-fixture' ) + .byteLimit(); + + assert.strictEqual( $el.attr( 'maxlength' ), '7', 'maxlength attribute unchanged for simple limit' ); + + $el = $( '<input type="text"/>' ) + .attr( 'maxlength', '7' ) + .appendTo( '#qunit-fixture' ) + .byteLimit( 12 ); + + assert.strictEqual( $el.attr( 'maxlength' ), '12', 'maxlength attribute updated for custom limit' ); + + $el = $( '<input type="text"/>' ) + .attr( 'maxlength', '7' ) + .appendTo( '#qunit-fixture' ) + .byteLimit( 12, function ( val ) { + return val; + } ); + + assert.strictEqual( $el.attr( 'maxlength' ), undefined, 'maxlength attribute removed for limit with callback' ); + + $elA = $( '<input type="text"/>' ) + .addClass( 'mw-test-byteLimit-foo' ) + .attr( 'maxlength', '7' ) + .appendTo( '#qunit-fixture' ); + + $elB = $( '<input type="text"/>' ) + .addClass( 'mw-test-byteLimit-foo' ) + .attr( 'maxlength', '12' ) + .appendTo( '#qunit-fixture' ); + + $el = $( '.mw-test-byteLimit-foo' ); + + assert.strictEqual( $el.length, 2, 'Verify that there are no other elements clashing with this test suite' ); + + $el.byteLimit(); + } ); + + QUnit.test( 'Trim from insertion when limit exceeded', 2, function ( assert ) { + var $el; + + // Use a new <input /> because the bug only occurs on the first time + // the limit it reached (bug 40850) + $el = $( '<input type="text"/>' ) + .appendTo( '#qunit-fixture' ) + .byteLimit( 3 ) + .val( 'abc' ).trigger( 'change' ) + .val( 'zabc' ).trigger( 'change' ); + + assert.strictEqual( $el.val(), 'abc', 'Trim from the insertion point (at 0), not the end' ); + + $el = $( '<input type="text"/>' ) + .appendTo( '#qunit-fixture' ) + .byteLimit( 3 ) + .val( 'abc' ).trigger( 'change' ) + .val( 'azbc' ).trigger( 'change' ); + + assert.strictEqual( $el.val(), 'abc', 'Trim from the insertion point (at 1), not the end' ); + } ); +}( jQuery, mediaWiki ) ); diff --git a/tests/qunit/suites/resources/jquery/jquery.client.test.js b/tests/qunit/suites/resources/jquery/jquery.client.test.js new file mode 100644 index 00000000..c6dd91c4 --- /dev/null +++ b/tests/qunit/suites/resources/jquery/jquery.client.test.js @@ -0,0 +1,638 @@ +( function ( $ ) { + + QUnit.module( 'jquery.client', QUnit.newMwEnvironment() ); + + var uacount = 0, + // Object keyed by userAgent. Value is an array (human-readable name, client-profile object, navigator.platform value) + uas = { + // Internet Explorer 6 + // Internet Explorer 7 + 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)': { + title: 'Internet Explorer 7', + platform: 'Win32', + profile: { + name: 'msie', + layout: 'trident', + layoutVersion: 'unknown', + platform: 'win', + version: '7.0', + versionBase: '7', + versionNumber: 7 + }, + wikiEditor: { + ltr: true, + rtl: false + } + }, + // Internet Explorer 8 + // Internet Explorer 9 + // Internet Explorer 10 + 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)': { + title: 'Internet Explorer 10', + platform: 'Win32', + profile: { + name: 'msie', + layout: 'trident', + layoutVersion: 6, + platform: 'win', + version: '10.0', + versionBase: '10', + versionNumber: 10 + }, + wikiEditor: { + ltr: true, + rtl: true + } + }, + // Internet Explorer 11 + 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv 11.0) like Gecko': { + title: 'Internet Explorer 11', + platform: 'Win32', + profile: { + name: 'msie', + layout: 'trident', + layoutVersion: 7, + platform: 'win', + version: '11.0', + versionBase: '11', + versionNumber: 11 + }, + wikiEditor: { + ltr: true, + rtl: true + } + }, + // Internet Explorer 11 - Windows 8.1 x64 Modern UI + 'Mozilla/5.0 (Windows NT 6.3; Win64; x64; Trident/7.0; rv:11.0) like Gecko': { + title: 'Internet Explorer 11', + platform: 'Win64', + profile: { + name: 'msie', + layout: 'trident', + layoutVersion: 7, + platform: 'win', + version: '11.0', + versionBase: '11', + versionNumber: 11 + }, + wikiEditor: { + ltr: true, + rtl: true + } + }, + // Internet Explorer 11 - Windows 8.1 x64 desktop UI + 'Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko': { + title: 'Internet Explorer 11', + platform: 'WOW64', + profile: { + name: 'msie', + layout: 'trident', + layoutVersion: 7, + platform: 'win', + version: '11.0', + versionBase: '11', + versionNumber: 11 + }, + wikiEditor: { + ltr: true, + rtl: true + } + }, + // Firefox 2 + // Firefox 3.5 + 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.1.19) Gecko/20110420 Firefox/3.5.19': { + title: 'Firefox 3.5', + platform: 'MacIntel', + profile: { + name: 'firefox', + layout: 'gecko', + layoutVersion: 20110420, + platform: 'mac', + version: '3.5.19', + versionBase: '3', + versionNumber: 3.5 + }, + wikiEditor: { + ltr: true, + rtl: true + } + }, + // Firefox 3.6 + 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.17) Gecko/20110422 Ubuntu/10.10 (maverick) Firefox/3.6.17': { + title: 'Firefox 3.6', + platform: 'Linux i686', + profile: { + name: 'firefox', + layout: 'gecko', + layoutVersion: 20110422, + platform: 'linux', + version: '3.6.17', + versionBase: '3', + versionNumber: 3.6 + }, + wikiEditor: { + ltr: true, + rtl: true + } + }, + // Firefox 4 + 'Mozilla/5.0 (Windows NT 6.0; rv:2.0.1) Gecko/20100101 Firefox/4.0.1': { + title: 'Firefox 4', + platform: 'Win32', + profile: { + name: 'firefox', + layout: 'gecko', + layoutVersion: 20100101, + platform: 'win', + version: '4.0.1', + versionBase: '4', + versionNumber: 4 + }, + wikiEditor: { + ltr: true, + rtl: true + } + }, + // Firefox 10 nightly build + 'Mozilla/5.0 (X11; Linux x86_64; rv:10.0a1) Gecko/20111103 Firefox/10.0a1': { + title: 'Firefox 10 nightly', + platform: 'Linux', + profile: { + name: 'firefox', + layout: 'gecko', + layoutVersion: 20111103, + platform: 'linux', + version: '10.0a1', + versionBase: '10', + versionNumber: 10 + }, + wikiEditor: { + ltr: true, + rtl: true + } + }, + // Iceweasel 10.0.6 + 'Mozilla/5.0 (X11; Linux i686; rv:10.0.6) Gecko/20100101 Iceweasel/10.0.6': { + title: 'Iceweasel 10.0.6', + platform: 'Linux', + profile: { + name: 'iceweasel', + layout: 'gecko', + layoutVersion: 20100101, + platform: 'linux', + version: '10.0.6', + versionBase: '10', + versionNumber: 10 + }, + wikiEditor: { + ltr: true, + rtl: true + } + }, + // Iceweasel 15.0.1 + 'Mozilla/5.0 (X11; Linux x86_64; rv:15.0) Gecko/20100101 Firefox/15.0.1 Iceweasel/15.0.1': { + title: 'Iceweasel 15.0.1', + platform: 'Linux', + profile: { + name: 'iceweasel', + layout: 'gecko', + layoutVersion: 20100101, + platform: 'linux', + version: '15.0.1', + versionBase: '15', + versionNumber: 15 + }, + wikiEditor: { + ltr: true, + rtl: true + } + }, + // Firefox 5 + // Safari 3 + // Safari 4 + 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_7; nl-nl) AppleWebKit/531.22.7 (KHTML, like Gecko) Version/4.0.5 Safari/531.22.7': { + title: 'Safari 4', + platform: 'MacIntel', + profile: { + name: 'safari', + layout: 'webkit', + layoutVersion: 531, + platform: 'mac', + version: '4.0.5', + versionBase: '4', + versionNumber: 4 + }, + wikiEditor: { + ltr: true, + rtl: true + } + }, + 'Mozilla/5.0 (Windows; U; Windows NT 6.0; cs-CZ) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/4.0.5 Safari/531.22.7': { + title: 'Safari 4', + platform: 'Win32', + profile: { + name: 'safari', + layout: 'webkit', + layoutVersion: 533, + platform: 'win', + version: '4.0.5', + versionBase: '4', + versionNumber: 4 + }, + wikiEditor: { + ltr: true, + rtl: true + } + }, + // Safari 5 + // Safari 6 + 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/536.29.13 (KHTML, like Gecko) Version/6.0.4 Safari/536.29.13': { + title: 'Safari 6', + platform: 'MacIntel', + profile: { + name: 'safari', + layout: 'webkit', + layoutVersion: 536, + platform: 'mac', + version: '6.0.4', + versionBase: '6', + versionNumber: 6 + }, + wikiEditor: { + ltr: true, + rtl: true + } + }, + // Safari 6.0.5+ (doesn't have the comma in "KHTML, like Gecko") + 'Mozilla/5.0 (Macintosh; Intel Mac OS X 1084) AppleWebKit/536.30.1 (KHTML like Gecko) Version/6.0.5 Safari/536.30.1': { + title: 'Safari 6', + platform: 'MacIntel', + profile: { + name: 'safari', + layout: 'webkit', + layoutVersion: 536, + platform: 'mac', + version: '6.0.5', + versionBase: '6', + versionNumber: 6 + }, + wikiEditor: { + ltr: true, + rtl: true + } + }, + // Opera 10+ + 'Opera/9.80 (Windows NT 5.1)': { + title: 'Opera 10+ (exact version unspecified)', + platform: 'Win32', + profile: { + name: 'opera', + layout: 'presto', + layoutVersion: 'unknown', + platform: 'win', + version: '10', + versionBase: '10', + versionNumber: 10 + }, + wikiEditor: { + ltr: true, + rtl: true + } + }, + // Opera 12 + 'Opera/9.80 (Windows NT 5.1) Presto/2.12.388 Version/12.11': { + title: 'Opera 12', + platform: 'Win32', + profile: { + name: 'opera', + layout: 'presto', + layoutVersion: 'unknown', + platform: 'win', + version: '12.11', + versionBase: '12', + versionNumber: 12.11 + }, + wikiEditor: { + ltr: true, + rtl: true + } + }, + // Opera 15 (WebKit-based) + 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.52 Safari/537.36 OPR/15.0.1147.130': { + title: 'Opera 15', + platform: 'Win32', + profile: { + name: 'opera', + layout: 'webkit', + layoutVersion: 537, + platform: 'win', + version: '15.0.1147.130', + versionBase: '15', + versionNumber: 15 + }, + wikiEditor: { + ltr: true, + rtl: true + } + }, + // Chrome 5 + // Chrome 6 + // Chrome 7 + // Chrome 8 + // Chrome 9 + // Chrome 10 + // Chrome 11 + // Chrome 12 + 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_5_8) AppleWebKit/534.30 (KHTML, like Gecko) Chrome/12.0.742.112 Safari/534.30': { + title: 'Chrome 12', + platform: 'MacIntel', + profile: { + name: 'chrome', + layout: 'webkit', + layoutVersion: 534, + platform: 'mac', + version: '12.0.742.112', + versionBase: '12', + versionNumber: 12 + }, + wikiEditor: { + ltr: true, + rtl: true + } + }, + 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/534.30 (KHTML, like Gecko) Chrome/12.0.742.68 Safari/534.30': { + title: 'Chrome 12', + platform: 'Linux i686', + profile: { + name: 'chrome', + layout: 'webkit', + layoutVersion: 534, + platform: 'linux', + version: '12.0.742.68', + versionBase: '12', + versionNumber: 12 + }, + wikiEditor: { + ltr: true, + rtl: true + } + }, + // Android WebKit Browser 2.3 + 'Mozilla/5.0 (Linux; U; Android 2.3.5; en-us; HTC Vision Build/GRI40) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1': { + title: 'Android WebKit Browser 2.3', + platform: 'Linux armv7l', + profile: { + name: 'android', + layout: 'webkit', + layoutVersion: 533, + platform: 'linux', + version: '2.3.5', + versionBase: '2', + versionNumber: 2.3 + }, + wikiEditor: { + ltr: true, + rtl: true + } + }, + // Rekonq (bug 34924) + 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/534.34 (KHTML, like Gecko) rekonq Safari/534.34': { + title: 'Rekonq', + platform: 'Linux i686', + profile: { + name: 'rekonq', + layout: 'webkit', + layoutVersion: 534, + platform: 'linux', + version: '534.34', + versionBase: '534', + versionNumber: 534.34 + }, + wikiEditor: { + ltr: true, + rtl: true + } + }, + // Konqueror + 'Mozilla/5.0 (X11; Linux i686) KHTML/4.9.1 (like Gecko) Konqueror/4.9': { + title: 'Konqueror', + platform: 'Linux i686', + profile: { + name: 'konqueror', + layout: 'khtml', + layoutVersion: 'unknown', + platform: 'linux', + version: '4.9.1', + versionBase: '4', + versionNumber: 4.9 + }, + wikiEditor: { + // '4.9' is less than '4.11'. + ltr: false, + rtl: false + }, + wikiEditorLegacy: { + // The check is missing in legacyTestMap + ltr: true, + rtl: true + } + }, + // Amazon Silk + 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_3; en-us; Silk/1.0.13.81_10003810) AppleWebKit/533.16 (KHTML, like Gecko) Version/5.0 Safari/533.16 Silk-Accelerated=true': { + title: 'Silk', + platform: 'Desktop', + profile: { + name: 'silk', + layout: 'webkit', + layoutVersion: 533, + platform: 'unknown', + version: '1.0.13.81_10003810', + versionBase: '1', + versionNumber: 1 + }, + wikiEditor: { + ltr: true, + rtl: true + } + }, + 'Mozilla/5.0 (Linux; U; Android 4.0.3; en-us; KFTT Build/IML74K) AppleWebKit/535.19 (KHTML, like Gecko) Silk/2.1 Mobile Safari/535.19 Silk-Accelerated=true': { + title: 'Silk', + platform: 'Mobile', + profile: { + name: 'silk', + layout: 'webkit', + layoutVersion: 535, + platform: 'unknown', + version: '2.1', + versionBase: '2', + versionNumber: 2.1 + }, + wikiEditor: { + ltr: true, + rtl: true + } + } + }, + testMap = { + // Example from WikiEditor, modified to provide version identifiers as strings and with + // Konqueror 4.11 check added. + 'ltr': { + 'msie': [['>=', '7.0']], + 'firefox': [['>=', '2']], + 'opera': [['>=', '9.6']], + 'safari': [['>=', '3']], + 'chrome': [['>=', '3']], + 'netscape': [['>=', '9']], + 'konqueror': [['>=', '4.11']], + 'blackberry': false, + 'ipod': false, + 'iphone': false + }, + 'rtl': { + 'msie': [['>=', '8']], + 'firefox': [['>=', '2']], + 'opera': [['>=', '9.6']], + 'safari': [['>=', '3']], + 'chrome': [['>=', '3']], + 'netscape': [['>=', '9']], + 'konqueror': [['>=', '4.11']], + 'blackberry': false, + 'ipod': false, + 'iphone': false + } + }, + legacyTestMap = { + // Original example from WikiEditor. + // This is using the old, but still supported way of providing version identifiers as numbers + // instead of strings; with this method, 4.9 would be considered larger than 4.11. + 'ltr': { + 'msie': [['>=', 7.0]], + 'firefox': [['>=', 2]], + 'opera': [['>=', 9.6]], + 'safari': [['>=', 3]], + 'chrome': [['>=', 3]], + 'netscape': [['>=', 9]], + 'blackberry': false, + 'ipod': false, + 'iphone': false + }, + 'rtl': { + 'msie': [['>=', 8]], + 'firefox': [['>=', 2]], + 'opera': [['>=', 9.6]], + 'safari': [['>=', 3]], + 'chrome': [['>=', 3]], + 'netscape': [['>=', 9]], + 'blackberry': false, + 'ipod': false, + 'iphone': false + } + } + ; + + // Count test cases + $.each( uas, function () { + uacount++; + } ); + + QUnit.test( 'profile( navObject )', 7, function ( assert ) { + var p = $.client.profile(); + + function unknownOrType( val, type, summary ) { + assert.ok( typeof val === type || val === 'unknown', summary ); + } + + assert.equal( typeof p, 'object', 'profile returns an object' ); + unknownOrType( p.layout, 'string', 'p.layout is a string (or "unknown")' ); + unknownOrType( p.layoutVersion, 'number', 'p.layoutVersion is a number (or "unknown")' ); + unknownOrType( p.platform, 'string', 'p.platform is a string (or "unknown")' ); + unknownOrType( p.version, 'string', 'p.version is a string (or "unknown")' ); + unknownOrType( p.versionBase, 'string', 'p.versionBase is a string (or "unknown")' ); + assert.equal( typeof p.versionNumber, 'number', 'p.versionNumber is a number' ); + } ); + + QUnit.test( 'profile( navObject ) - samples', uacount, function ( assert ) { + // Loop through and run tests + $.each( uas, function ( rawUserAgent, data ) { + // Generate a client profile object and compare recursively + var ret = $.client.profile( { + userAgent: rawUserAgent, + platform: data.platform + } ); + assert.deepEqual( ret, data.profile, 'Client profile support check for ' + data.title + ' (' + data.platform + '): ' + rawUserAgent ); + } ); + } ); + + QUnit.test( 'test( testMap )', 4, function ( assert ) { + // .test() uses eval, make sure no exceptions are thrown + // then do a basic return value type check + var testMatch = $.client.test( testMap ), + ie7Profile = $.client.profile( { + 'userAgent': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)', + 'platform': '' + } ); + + assert.equal( typeof testMatch, 'boolean', 'map with ltr/rtl split returns a boolean value' ); + + testMatch = $.client.test( testMap.ltr ); + + assert.equal( typeof testMatch, 'boolean', 'simple map (without ltr/rtl split) returns a boolean value' ); + + assert.equal( $.client.test( { + 'msie': null + }, ie7Profile ), true, 'returns true if any version of a browser are allowed (null)' ); + + assert.equal( $.client.test( { + 'msie': false + }, ie7Profile ), false, 'returns false if all versions of a browser are not allowed (false)' ); + } ); + + QUnit.test( 'test( testMap, exactMatchOnly )', 2, function ( assert ) { + var ie7Profile = $.client.profile( { + 'userAgent': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)', + 'platform': '' + } ); + + assert.equal( $.client.test( { + 'firefox': [['>=', 2]] + }, ie7Profile, false ), true, 'returns true if browser not found and exactMatchOnly not set' ); + + assert.equal( $.client.test( { + 'firefox': [['>=', 2]] + }, ie7Profile, true ), false, 'returns false if browser not found and exactMatchOnly is set' ); + } ); + + QUnit.test( 'test( testMap ), test( legacyTestMap ) - WikiEditor sample', uacount * 2 * 2, function ( assert ) { + var $body = $( 'body' ), + bodyClasses = $body.attr( 'class' ); + + // Loop through and run tests + $.each( uas, function ( agent, data ) { + $.each( ['ltr', 'rtl'], function ( i, dir ) { + var profile, testMatch, legacyTestMatch; + $body.removeClass( 'ltr rtl' ).addClass( dir ); + profile = $.client.profile( { + userAgent: agent, + platform: data.platform + } ); + testMatch = $.client.test( testMap, profile ); + legacyTestMatch = $.client.test( legacyTestMap, profile ); + $body.removeClass( dir ); + + assert.equal( + testMatch, + data.wikiEditor[dir], + 'testing comparison based on ' + dir + ', ' + agent + ); + assert.equal( + legacyTestMatch, + data.wikiEditorLegacy ? data.wikiEditorLegacy[dir] : data.wikiEditor[dir], + 'testing comparison based on ' + dir + ', ' + agent + ' (legacyTestMap)' + ); + } ); + } ); + + // Restore body classes + $body.attr( 'class', bodyClasses ); + } ); +}( jQuery ) ); diff --git a/tests/qunit/suites/resources/jquery/jquery.color.test.js b/tests/qunit/suites/resources/jquery/jquery.color.test.js new file mode 100644 index 00000000..c8e8ac70 --- /dev/null +++ b/tests/qunit/suites/resources/jquery/jquery.color.test.js @@ -0,0 +1,18 @@ +( function ( $ ) { + QUnit.module( 'jquery.color', QUnit.newMwEnvironment( { + setup: function () { + this.clock = this.sandbox.useFakeTimers(); + } + } ) ); + + QUnit.test( 'animate', 1, function ( assert ) { + var $canvas = $( '<div>' ).css( 'background-color', '#fff' ); + + $canvas.animate( { backgroundColor: '#000' }, 10 ).promise().then( function () { + var endColors = $.colorUtil.getRGB( $canvas.css( 'background-color' ) ); + assert.deepEqual( endColors, [0, 0, 0], 'end state' ); + } ); + + this.clock.tick( 20 ); + } ); +}( jQuery ) ); diff --git a/tests/qunit/suites/resources/jquery/jquery.colorUtil.test.js b/tests/qunit/suites/resources/jquery/jquery.colorUtil.test.js new file mode 100644 index 00000000..39ae363c --- /dev/null +++ b/tests/qunit/suites/resources/jquery/jquery.colorUtil.test.js @@ -0,0 +1,63 @@ +( function ( $ ) { + QUnit.module( 'jquery.colorUtil', QUnit.newMwEnvironment() ); + + QUnit.test( 'getRGB', 18, function ( assert ) { + assert.strictEqual( $.colorUtil.getRGB(), undefined, 'No arguments' ); + assert.strictEqual( $.colorUtil.getRGB( '' ), undefined, 'Empty string' ); + assert.deepEqual( $.colorUtil.getRGB( [0, 100, 255] ), [0, 100, 255], 'Parse array of rgb values' ); + assert.deepEqual( $.colorUtil.getRGB( 'rgb(0,100,255)' ), [0, 100, 255], 'Parse simple rgb string' ); + assert.deepEqual( $.colorUtil.getRGB( 'rgb(0, 100, 255)' ), [0, 100, 255], 'Parse simple rgb string with spaces' ); + assert.deepEqual( $.colorUtil.getRGB( 'rgb(0%,20%,40%)' ), [0, 51, 102], 'Parse rgb string with percentages' ); + assert.deepEqual( $.colorUtil.getRGB( 'rgb(0%, 20%, 40%)' ), [0, 51, 102], 'Parse rgb string with percentages and spaces' ); + assert.deepEqual( $.colorUtil.getRGB( '#f2ddee' ), [242, 221, 238], 'Hex string: 6 char lowercase' ); + assert.deepEqual( $.colorUtil.getRGB( '#f2DDEE' ), [242, 221, 238], 'Hex string: 6 char uppercase' ); + assert.deepEqual( $.colorUtil.getRGB( '#f2DdEe' ), [242, 221, 238], 'Hex string: 6 char mixed' ); + assert.deepEqual( $.colorUtil.getRGB( '#eee' ), [238, 238, 238], 'Hex string: 3 char lowercase' ); + assert.deepEqual( $.colorUtil.getRGB( '#EEE' ), [238, 238, 238], 'Hex string: 3 char uppercase' ); + assert.deepEqual( $.colorUtil.getRGB( '#eEe' ), [238, 238, 238], 'Hex string: 3 char mixed' ); + assert.deepEqual( $.colorUtil.getRGB( 'rgba(0, 0, 0, 0)' ), [255, 255, 255], 'Zero rgba for Safari 3; Transparent (whitespace)' ); + + // Perhaps this is a bug in colorUtil, but it is the current behavior so, let's keep + // track of it, so we will know in case it would ever change. + assert.strictEqual( $.colorUtil.getRGB( 'rgba(0,0,0,0)' ), undefined, 'Zero rgba without whitespace' ); + + assert.deepEqual( $.colorUtil.getRGB( 'lightGreen' ), [144, 238, 144], 'Color names (lightGreen)' ); + assert.deepEqual( $.colorUtil.getRGB( 'transparent' ), [255, 255, 255], 'Color names (transparent)' ); + assert.strictEqual( $.colorUtil.getRGB( 'mediaWiki' ), undefined, 'Inexisting color name' ); + } ); + + QUnit.test( 'rgbToHsl', 1, function ( assert ) { + var hsl, ret; + + // Cross-browser differences in decimals... + // Round to two decimals so they can be more reliably checked. + function dualDecimals( a ) { + return Math.round( a * 100 ) / 100; + } + + // Re-create the rgbToHsl return array items, limited to two decimals. + hsl = $.colorUtil.rgbToHsl( 144, 238, 144 ); + ret = [ dualDecimals( hsl[0] ), dualDecimals( hsl[1] ), dualDecimals( hsl[2] ) ]; + + assert.deepEqual( ret, [0.33, 0.73, 0.75], 'rgb(144, 238, 144): hsl(0.33, 0.73, 0.75)' ); + } ); + + QUnit.test( 'hslToRgb', 1, function ( assert ) { + var rgb, ret; + rgb = $.colorUtil.hslToRgb( 0.3, 0.7, 0.8 ); + + // Re-create the hslToRgb return array items, rounded to whole numbers. + ret = [ Math.round( rgb[0] ), Math.round( rgb[1] ), Math.round( rgb[2] ) ]; + + assert.deepEqual( ret, [183, 240, 168], 'hsl(0.3, 0.7, 0.8): rgb(183, 240, 168)' ); + } ); + + QUnit.test( 'getColorBrightness', 2, function ( assert ) { + var a, b; + a = $.colorUtil.getColorBrightness( 'red', +0.1 ); + assert.equal( a, 'rgb(255,50,50)', 'Start with named color "red", brighten 10%' ); + + b = $.colorUtil.getColorBrightness( 'rgb(200,50,50)', -0.2 ); + assert.equal( b, 'rgb(118,29,29)', 'Start with rgb string "rgb(200,50,50)", darken 20%' ); + } ); +}( jQuery ) ); diff --git a/tests/qunit/suites/resources/jquery/jquery.getAttrs.test.js b/tests/qunit/suites/resources/jquery/jquery.getAttrs.test.js new file mode 100644 index 00000000..0b7e87ee --- /dev/null +++ b/tests/qunit/suites/resources/jquery/jquery.getAttrs.test.js @@ -0,0 +1,13 @@ +( function ( $ ) { + QUnit.module( 'jquery.getAttrs', QUnit.newMwEnvironment() ); + + QUnit.test( 'Check', 1, function ( assert ) { + var attrs = { + foo: 'bar', + 'class': 'lorem' + }, + $el = $( '<div>' ).attr( attrs ); + + assert.deepEqual( $el.getAttrs(), attrs, 'getAttrs() return object should match the attributes set, no more, no less' ); + } ); +}( jQuery ) ); diff --git a/tests/qunit/suites/resources/jquery/jquery.hidpi.test.js b/tests/qunit/suites/resources/jquery/jquery.hidpi.test.js new file mode 100644 index 00000000..906369ee --- /dev/null +++ b/tests/qunit/suites/resources/jquery/jquery.hidpi.test.js @@ -0,0 +1,22 @@ +( function ( $ ) { + QUnit.module( 'jquery.hidpi', QUnit.newMwEnvironment() ); + + QUnit.test( 'devicePixelRatio', 1, function ( assert ) { + var devicePixelRatio = $.devicePixelRatio(); + assert.equal( typeof devicePixelRatio, 'number', '$.devicePixelRatio() returns a number' ); + } ); + + QUnit.test( 'matchSrcSet', 6, function ( assert ) { + var srcset = 'onefive.png 1.5x, two.png 2x'; + + // Nice exact matches + assert.equal( $.matchSrcSet( 1, srcset ), null, '1.0 gives no match' ); + assert.equal( $.matchSrcSet( 1.5, srcset ), 'onefive.png', '1.5 gives match' ); + assert.equal( $.matchSrcSet( 2, srcset ), 'two.png', '2 gives match' ); + + // Non-exact matches; should return the next-biggest specified + assert.equal( $.matchSrcSet( 1.25, srcset ), null, '1.25 gives no match' ); + assert.equal( $.matchSrcSet( 1.75, srcset ), 'onefive.png', '1.75 gives match to 1.5' ); + assert.equal( $.matchSrcSet( 2.25, srcset ), 'two.png', '2.25 gives match to 2' ); + } ); +}( jQuery ) ); diff --git a/tests/qunit/suites/resources/jquery/jquery.highlightText.test.js b/tests/qunit/suites/resources/jquery/jquery.highlightText.test.js new file mode 100644 index 00000000..e1fb96dc --- /dev/null +++ b/tests/qunit/suites/resources/jquery/jquery.highlightText.test.js @@ -0,0 +1,235 @@ +( function ( $ ) { + QUnit.module( 'jquery.highlightText', QUnit.newMwEnvironment() ); + + QUnit.test( 'Check', function ( assert ) { + var $fixture, cases = [ + { + desc: 'Test 001', + text: 'Blue Öyster Cult', + highlight: 'Blue', + expected: '<span class="highlight">Blue</span> Öyster Cult' + }, + { + desc: 'Test 002', + text: 'Blue Öyster Cult', + highlight: 'Blue ', + expected: '<span class="highlight">Blue</span> Öyster Cult' + }, + { + desc: 'Test 003', + text: 'Blue Öyster Cult', + highlight: 'Blue Ö', + expected: '<span class="highlight">Blue</span> <span class="highlight">Ö</span>yster Cult' + }, + { + desc: 'Test 004', + text: 'Blue Öyster Cult', + highlight: 'Blue Öy', + expected: '<span class="highlight">Blue</span> <span class="highlight">Öy</span>ster Cult' + }, + { + desc: 'Test 005', + text: 'Blue Öyster Cult', + highlight: ' Blue', + expected: '<span class="highlight">Blue</span> Öyster Cult' + }, + { + desc: 'Test 006', + text: 'Blue Öyster Cult', + highlight: ' Blue ', + expected: '<span class="highlight">Blue</span> Öyster Cult' + }, + { + desc: 'Test 007', + text: 'Blue Öyster Cult', + highlight: ' Blue Ö', + expected: '<span class="highlight">Blue</span> <span class="highlight">Ö</span>yster Cult' + }, + { + desc: 'Test 008', + text: 'Blue Öyster Cult', + highlight: ' Blue Öy', + expected: '<span class="highlight">Blue</span> <span class="highlight">Öy</span>ster Cult' + }, + { + desc: 'Test 009: Highlighter broken on starting Umlaut?', + text: 'Österreich', + highlight: 'Österreich', + expected: '<span class="highlight">Österreich</span>' + }, + { + desc: 'Test 010: Highlighter broken on starting Umlaut?', + text: 'Österreich', + highlight: 'Ö', + expected: '<span class="highlight">Ö</span>sterreich' + }, + { + desc: 'Test 011: Highlighter broken on starting Umlaut?', + text: 'Österreich', + highlight: 'Öst', + expected: '<span class="highlight">Öst</span>erreich' + }, + { + desc: 'Test 012: Highlighter broken on starting Umlaut?', + text: 'Österreich', + highlight: 'Oe', + expected: 'Österreich' + }, + { + desc: 'Test 013: Highlighter broken on punctuation mark?', + text: 'So good. To be there', + highlight: 'good', + expected: 'So <span class="highlight">good</span>. To be there' + }, + { + desc: 'Test 014: Highlighter broken on space?', + text: 'So good. To be there', + highlight: 'be', + expected: 'So good. To <span class="highlight">be</span> there' + }, + { + desc: 'Test 015: Highlighter broken on space?', + text: 'So good. To be there', + highlight: ' be', + expected: 'So good. To <span class="highlight">be</span> there' + }, + { + desc: 'Test 016: Highlighter broken on space?', + text: 'So good. To be there', + highlight: 'be ', + expected: 'So good. To <span class="highlight">be</span> there' + }, + { + desc: 'Test 017: Highlighter broken on space?', + text: 'So good. To be there', + highlight: ' be ', + expected: 'So good. To <span class="highlight">be</span> there' + }, + { + desc: 'Test 018: en de Highlighter broken on special character at the end?', + text: 'So good. xbß', + highlight: 'xbß', + expected: 'So good. <span class="highlight">xbß</span>' + }, + { + desc: 'Test 019: en de Highlighter broken on special character at the end?', + text: 'So good. xbß.', + highlight: 'xbß.', + expected: 'So good. <span class="highlight">xbß.</span>' + }, + { + desc: 'Test 020: RTL he Hebrew', + text: 'חסיד אומות העולם', + highlight: 'חסיד אומות העולם', + expected: '<span class="highlight">חסיד</span> <span class="highlight">אומות</span> <span class="highlight">העולם</span>' + }, + { + desc: 'Test 021: RTL he Hebrew', + text: 'חסיד אומות העולם', + highlight: 'חסי', + expected: '<span class="highlight">חסי</span>ד אומות העולם' + }, + { + desc: 'Test 022: ja Japanese', + text: '諸国民の中の正義の人', + highlight: '諸国民の中の正義の人', + expected: '<span class="highlight">諸国民の中の正義の人</span>' + }, + { + desc: 'Test 023: ja Japanese', + text: '諸国民の中の正義の人', + highlight: '諸国', + expected: '<span class="highlight">諸国</span>民の中の正義の人' + }, + { + desc: 'Test 024: fr French text and « french quotes » (guillemets)', + text: '« L\'oiseau est sur l’île »', + highlight: '« L\'oiseau est sur l’île »', + expected: '<span class="highlight">«</span> <span class="highlight">L\'oiseau</span> <span class="highlight">est</span> <span class="highlight">sur</span> <span class="highlight">l’île</span> <span class="highlight">»</span>' + }, + { + desc: 'Test 025: fr French text and « french quotes » (guillemets)', + text: '« L\'oiseau est sur l’île »', + highlight: '« L\'oise', + expected: '<span class="highlight">«</span> <span class="highlight">L\'oise</span>au est sur l’île »' + }, + { + desc: 'Test 025a: fr French text and « french quotes » (guillemets) - does it match the single strings "«" and "L" separately?', + text: '« L\'oiseau est sur l’île »', + highlight: '« L', + expected: '<span class="highlight">«</span> <span class="highlight">L</span>\'oiseau est sur <span class="highlight">l</span>’île »' + }, + { + desc: 'Test 026: ru Russian', + text: 'Праведники мира', + highlight: 'Праведники мира', + expected: '<span class="highlight">Праведники</span> <span class="highlight">мира</span>' + }, + { + desc: 'Test 027: ru Russian', + text: 'Праведники мира', + highlight: 'Праве', + expected: '<span class="highlight">Праве</span>дники мира' + }, + { + desc: 'Test 028 ka Georgian', + text: 'მთავარი გვერდი', + highlight: 'მთავარი გვერდი', + expected: '<span class="highlight">მთავარი</span> <span class="highlight">გვერდი</span>' + }, + { + desc: 'Test 029 ka Georgian', + text: 'მთავარი გვერდი', + highlight: 'მთა', + expected: '<span class="highlight">მთა</span>ვარი გვერდი' + }, + { + desc: 'Test 030 hy Armenian', + text: 'Նոնա Գափրինդաշվիլի', + highlight: 'Նոնա Գափրինդաշվիլի', + expected: '<span class="highlight">Նոնա</span> <span class="highlight">Գափրինդաշվիլի</span>' + }, + { + desc: 'Test 031 hy Armenian', + text: 'Նոնա Գափրինդաշվիլի', + highlight: 'Նոն', + expected: '<span class="highlight">Նոն</span>ա Գափրինդաշվիլի' + }, + { + desc: 'Test 032: th Thai', + text: 'พอล แอร์ดิช', + highlight: 'พอล แอร์ดิช', + expected: '<span class="highlight">พอล</span> <span class="highlight">แอร์ดิช</span>' + }, + { + desc: 'Test 033: th Thai', + text: 'พอล แอร์ดิช', + highlight: 'พอ', + expected: '<span class="highlight">พอ</span>ล แอร์ดิช' + }, + { + desc: 'Test 034: RTL ar Arabic', + text: 'بول إيردوس', + highlight: 'بول إيردوس', + expected: '<span class="highlight">بول</span> <span class="highlight">إيردوس</span>' + }, + { + desc: 'Test 035: RTL ar Arabic', + text: 'بول إيردوس', + highlight: 'بو', + expected: '<span class="highlight">بو</span>ل إيردوس' + } + ]; + QUnit.expect( cases.length ); + + $.each( cases, function ( i, item ) { + $fixture = $( '<p>' ).text( item.text ).highlightText( item.highlight ); + assert.equal( + $fixture.html(), + // Re-parse to normalize + $( '<p>' ).html( item.expected ).html(), + item.desc || undefined + ); + } ); + } ); +}( jQuery ) ); diff --git a/tests/qunit/suites/resources/jquery/jquery.localize.test.js b/tests/qunit/suites/resources/jquery/jquery.localize.test.js new file mode 100644 index 00000000..3ef27903 --- /dev/null +++ b/tests/qunit/suites/resources/jquery/jquery.localize.test.js @@ -0,0 +1,135 @@ +( function ( $, mw ) { + QUnit.module( 'jquery.localize', QUnit.newMwEnvironment() ); + + QUnit.test( 'Handle basic replacements', 4, function ( assert ) { + var html, $lc; + mw.messages.set( 'basic', 'Basic stuff' ); + + // Tag: html:msg + html = '<div><span><html:msg key="basic" /></span></div>'; + $lc = $( html ).localize().find( 'span' ); + + assert.strictEqual( $lc.text(), 'Basic stuff', 'Tag: html:msg' ); + + // Attribute: title-msg + html = '<div><span title-msg="basic"></span></div>'; + $lc = $( html ).localize().find( 'span' ); + + assert.strictEqual( $lc.attr( 'title' ), 'Basic stuff', 'Attribute: title-msg' ); + + // Attribute: alt-msg + html = '<div><span alt-msg="basic"></span></div>'; + $lc = $( html ).localize().find( 'span' ); + + assert.strictEqual( $lc.attr( 'alt' ), 'Basic stuff', 'Attribute: alt-msg' ); + + // Attribute: placeholder-msg + html = '<div><input placeholder-msg="basic" /></div>'; + $lc = $( html ).localize().find( 'input' ); + + assert.strictEqual( $lc.attr( 'placeholder' ), 'Basic stuff', 'Attribute: placeholder-msg' ); + } ); + + QUnit.test( 'Proper escaping', 2, function ( assert ) { + var html, $lc; + mw.messages.set( 'properfoo', '<proper esc="test">' ); + + // This is handled by jQuery inside $.fn.localize, just a simple sanity checked + // making sure it is actually using text() and attr() (or something with the same effect) + + // Text escaping + html = '<div><span><html:msg key="properfoo" /></span></div>'; + $lc = $( html ).localize().find( 'span' ); + + assert.strictEqual( $lc.text(), mw.msg( 'properfoo' ), 'Content is inserted as text, not as html.' ); + + // Attribute escaping + html = '<div><span title-msg="properfoo"></span></div>'; + $lc = $( html ).localize().find( 'span' ); + + assert.strictEqual( $lc.attr( 'title' ), mw.msg( 'properfoo' ), 'Attributes are not inserted raw.' ); + } ); + + QUnit.test( 'Options', 7, function ( assert ) { + mw.messages.set( { + 'foo-lorem': 'Lorem', + 'foo-ipsum': 'Ipsum', + 'foo-bar-title': 'Read more about bars', + 'foo-bar-label': 'The Bars', + 'foo-bazz-title': 'Read more about bazz at $1 (last modified: $2)', + 'foo-bazz-label': 'The Bazz ($1)', + 'foo-welcome': 'Welcome to $1! (last visit: $2)' + } ); + var html, $lc, x, sitename = 'Wikipedia'; + + // Message key prefix + html = '<div><span title-msg="lorem"><html:msg key="ipsum" /></span></div>'; + $lc = $( html ).localize( { + prefix: 'foo-' + } ).find( 'span' ); + + assert.strictEqual( $lc.attr( 'title' ), 'Lorem', 'Message key prefix - attr' ); + assert.strictEqual( $lc.text(), 'Ipsum', 'Message key prefix - text' ); + + // Variable keys mapping + x = 'bar'; + html = '<div><span title-msg="title"><html:msg key="label" /></span></div>'; + $lc = $( html ).localize( { + keys: { + 'title': 'foo-' + x + '-title', + 'label': 'foo-' + x + '-label' + } + } ).find( 'span' ); + + assert.strictEqual( $lc.attr( 'title' ), 'Read more about bars', 'Variable keys mapping - attr' ); + assert.strictEqual( $lc.text(), 'The Bars', 'Variable keys mapping - text' ); + + // Passing parameteters to mw.msg + html = '<div><span><html:msg key="foo-welcome" /></span></div>'; + $lc = $( html ).localize( { + params: { + 'foo-welcome': [sitename, 'yesterday'] + } + } ).find( 'span' ); + + assert.strictEqual( $lc.text(), 'Welcome to Wikipedia! (last visit: yesterday)', 'Passing parameteters to mw.msg' ); + + // Combination of options prefix, params and keys + x = 'bazz'; + html = '<div><span title-msg="title"><html:msg key="label" /></span></div>'; + $lc = $( html ).localize( { + prefix: 'foo-', + keys: { + 'title': x + '-title', + 'label': x + '-label' + }, + params: { + 'title': [sitename, '3 minutes ago'], + 'label': [sitename, '3 minutes ago'] + + } + } ).find( 'span' ); + + assert.strictEqual( $lc.text(), 'The Bazz (Wikipedia)', 'Combination of options prefix, params and keys - text' ); + assert.strictEqual( $lc.attr( 'title' ), 'Read more about bazz at Wikipedia (last modified: 3 minutes ago)', 'Combination of options prefix, params and keys - attr' ); + } ); + + QUnit.test( 'Handle data text', 2, function ( assert ) { + var html, $lc; + mw.messages.set( 'option-one', 'Item 1' ); + mw.messages.set( 'option-two', 'Item 2' ); + html = '<select><option data-msg-text="option-one"></option><option data-msg-text="option-two"></option></select>'; + $lc = $( html ).localize().find( 'option' ); + assert.strictEqual( $lc.eq( 0 ).text(), mw.msg( 'option-one' ), 'data-msg-text becomes text of options' ); + assert.strictEqual( $lc.eq( 1 ).text(), mw.msg( 'option-two' ), 'data-msg-text becomes text of options' ); + } ); + + QUnit.test( 'Handle data html', 2, function ( assert ) { + var html, $lc; + mw.messages.set( 'html', 'behold... there is a <a>link</a> here!!' ); + html = '<div><div data-msg-html="html"></div></div>'; + $lc = $( html ).localize().find( 'a' ); + assert.strictEqual( $lc.length, 1, 'link is created' ); + assert.strictEqual( $lc.text(), 'link', 'the link text got added' ); + } ); +}( jQuery, mediaWiki ) ); diff --git a/tests/qunit/suites/resources/jquery/jquery.makeCollapsible.test.js b/tests/qunit/suites/resources/jquery/jquery.makeCollapsible.test.js new file mode 100644 index 00000000..80405819 --- /dev/null +++ b/tests/qunit/suites/resources/jquery/jquery.makeCollapsible.test.js @@ -0,0 +1,339 @@ +( function ( mw, $ ) { + var loremIpsum = 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit.'; + + QUnit.module( 'jquery.makeCollapsible', QUnit.newMwEnvironment( { + setup: function () { + this.clock = this.sandbox.useFakeTimers(); + } + } ) ); + + function prepareCollapsible( html, options ) { + return $( $.parseHTML( html ) ) + .appendTo( '#qunit-fixture' ) + // options might be undefined here - this is okay + .makeCollapsible( options ); + } + + // This test is first because if it fails, then almost all of the latter tests are meaningless. + QUnit.test( 'testing hooks/triggers', 4, function ( assert ) { + var test = this, + $collapsible = prepareCollapsible( + '<div class="mw-collapsible">' + loremIpsum + '</div>' + ), + $content = $collapsible.find( '.mw-collapsible-content' ), + $toggle = $collapsible.find( '.mw-collapsible-toggle' ); + + // In one full collapse-expand cycle, each event will be fired once + + // On collapse... + $collapsible.on( 'beforeCollapse.mw-collapsible', function () { + assert.assertTrue( $content.is( ':visible' ), 'first beforeCollapseExpand: content is visible' ); + } ); + $collapsible.on( 'afterCollapse.mw-collapsible', function () { + assert.assertTrue( $content.is( ':hidden' ), 'first afterCollapseExpand: content is hidden' ); + + // On expand... + $collapsible.on( 'beforeExpand.mw-collapsible', function () { + assert.assertTrue( $content.is( ':hidden' ), 'second beforeCollapseExpand: content is hidden' ); + } ); + $collapsible.on( 'afterExpand.mw-collapsible', function () { + assert.assertTrue( $content.is( ':visible' ), 'second afterCollapseExpand: content is visible' ); + } ); + + // ...expanding happens here + $toggle.trigger( 'click' ); + test.clock.tick( 500 ); + } ); + + // ...collapsing happens here + $toggle.trigger( 'click' ); + test.clock.tick( 500 ); + } ); + + QUnit.test( 'basic operation (<div>)', 5, function ( assert ) { + var test = this, + $collapsible = prepareCollapsible( + '<div class="mw-collapsible">' + loremIpsum + '</div>' + ), + $content = $collapsible.find( '.mw-collapsible-content' ), + $toggle = $collapsible.find( '.mw-collapsible-toggle' ); + + assert.equal( $content.length, 1, 'content is present' ); + assert.equal( $content.find( $toggle ).length, 0, 'toggle is not a descendant of content' ); + + assert.assertTrue( $content.is( ':visible' ), 'content is visible' ); + + $collapsible.on( 'afterCollapse.mw-collapsible', function () { + assert.assertTrue( $content.is( ':hidden' ), 'after collapsing: content is hidden' ); + + $collapsible.on( 'afterExpand.mw-collapsible', function () { + assert.assertTrue( $content.is( ':visible' ), 'after expanding: content is visible' ); + } ); + + $toggle.trigger( 'click' ); + test.clock.tick( 500 ); + } ); + + $toggle.trigger( 'click' ); + test.clock.tick( 500 ); + } ); + + QUnit.test( 'basic operation (<table>)', 7, function ( assert ) { + var test = this, + $collapsible = prepareCollapsible( + '<table class="mw-collapsible">' + + '<tr><td>' + loremIpsum + '</td><td>' + loremIpsum + '</td></tr>' + + '<tr><td>' + loremIpsum + '</td><td>' + loremIpsum + '</td></tr>' + + '<tr><td>' + loremIpsum + '</td><td>' + loremIpsum + '</td></tr>' + + '</table>' + ), + $headerRow = $collapsible.find( 'tr:first' ), + $contentRow = $collapsible.find( 'tr:last' ), + $toggle = $headerRow.find( 'td:last .mw-collapsible-toggle' ); + + assert.equal( $toggle.length, 1, 'toggle is added to last cell of first row' ); + + assert.assertTrue( $headerRow.is( ':visible' ), 'headerRow is visible' ); + assert.assertTrue( $contentRow.is( ':visible' ), 'contentRow is visible' ); + + $collapsible.on( 'afterCollapse.mw-collapsible', function () { + assert.assertTrue( $headerRow.is( ':visible' ), 'after collapsing: headerRow is still visible' ); + assert.assertTrue( $contentRow.is( ':hidden' ), 'after collapsing: contentRow is hidden' ); + + $collapsible.on( 'afterExpand.mw-collapsible', function () { + assert.assertTrue( $headerRow.is( ':visible' ), 'after expanding: headerRow is still visible' ); + assert.assertTrue( $contentRow.is( ':visible' ), 'after expanding: contentRow is visible' ); + } ); + + $toggle.trigger( 'click' ); + test.clock.tick( 500 ); + } ); + + $toggle.trigger( 'click' ); + test.clock.tick( 500 ); + } ); + + function tableWithCaptionTest( $collapsible, test, assert ) { + var $caption = $collapsible.find( 'caption' ), + $headerRow = $collapsible.find( 'tr:first' ), + $contentRow = $collapsible.find( 'tr:last' ), + $toggle = $caption.find( '.mw-collapsible-toggle' ); + + assert.equal( $toggle.length, 1, 'toggle is added to the end of the caption' ); + + assert.assertTrue( $caption.is( ':visible' ), 'caption is visible' ); + assert.assertTrue( $headerRow.is( ':visible' ), 'headerRow is visible' ); + assert.assertTrue( $contentRow.is( ':visible' ), 'contentRow is visible' ); + + $collapsible.on( 'afterCollapse.mw-collapsible', function () { + assert.assertTrue( $caption.is( ':visible' ), 'after collapsing: caption is still visible' ); + assert.assertTrue( $headerRow.is( ':hidden' ), 'after collapsing: headerRow is hidden' ); + assert.assertTrue( $contentRow.is( ':hidden' ), 'after collapsing: contentRow is hidden' ); + + $collapsible.on( 'afterExpand.mw-collapsible', function () { + assert.assertTrue( $caption.is( ':visible' ), 'after expanding: caption is still visible' ); + assert.assertTrue( $headerRow.is( ':visible' ), 'after expanding: headerRow is visible' ); + assert.assertTrue( $contentRow.is( ':visible' ), 'after expanding: contentRow is visible' ); + } ); + + $toggle.trigger( 'click' ); + test.clock.tick( 500 ); + } ); + + $toggle.trigger( 'click' ); + test.clock.tick( 500 ); + } + + QUnit.test( 'basic operation (<table> with caption)', 10, function ( assert ) { + tableWithCaptionTest( prepareCollapsible( + '<table class="mw-collapsible">' + + '<caption>' + loremIpsum + '</caption>' + + '<tr><th>' + loremIpsum + '</th><th>' + loremIpsum + '</th></tr>' + + '<tr><td>' + loremIpsum + '</td><td>' + loremIpsum + '</td></tr>' + + '<tr><td>' + loremIpsum + '</td><td>' + loremIpsum + '</td></tr>' + + '</table>' + ), this, assert ); + } ); + + QUnit.test( 'basic operation (<table> with caption and <thead>)', 10, function ( assert ) { + tableWithCaptionTest( prepareCollapsible( + '<table class="mw-collapsible">' + + '<caption>' + loremIpsum + '</caption>' + + '<thead><tr><th>' + loremIpsum + '</th><th>' + loremIpsum + '</th></tr></thead>' + + '<tr><td>' + loremIpsum + '</td><td>' + loremIpsum + '</td></tr>' + + '<tr><td>' + loremIpsum + '</td><td>' + loremIpsum + '</td></tr>' + + '</table>' + ), this, assert ); + } ); + + function listTest( listType, test, assert ) { + var $collapsible = prepareCollapsible( + '<' + listType + ' class="mw-collapsible">' + + '<li>' + loremIpsum + '</li>' + + '<li>' + loremIpsum + '</li>' + + '</' + listType + '>' + ), + $toggleItem = $collapsible.find( 'li.mw-collapsible-toggle-li:first-child' ), + $contentItem = $collapsible.find( 'li:last' ), + $toggle = $toggleItem.find( '.mw-collapsible-toggle' ); + + assert.equal( $toggle.length, 1, 'toggle is present, added inside new zeroth list item' ); + + assert.assertTrue( $toggleItem.is( ':visible' ), 'toggleItem is visible' ); + assert.assertTrue( $contentItem.is( ':visible' ), 'contentItem is visible' ); + + $collapsible.on( 'afterCollapse.mw-collapsible', function () { + assert.assertTrue( $toggleItem.is( ':visible' ), 'after collapsing: toggleItem is still visible' ); + assert.assertTrue( $contentItem.is( ':hidden' ), 'after collapsing: contentItem is hidden' ); + + $collapsible.on( 'afterExpand.mw-collapsible', function () { + assert.assertTrue( $toggleItem.is( ':visible' ), 'after expanding: toggleItem is still visible' ); + assert.assertTrue( $contentItem.is( ':visible' ), 'after expanding: contentItem is visible' ); + } ); + + $toggle.trigger( 'click' ); + test.clock.tick( 500 ); + } ); + + $toggle.trigger( 'click' ); + test.clock.tick( 500 ); + } + + QUnit.test( 'basic operation (<ul>)', 7, function ( assert ) { + listTest( 'ul', this, assert ); + } ); + + QUnit.test( 'basic operation (<ol>)', 7, function ( assert ) { + listTest( 'ol', this, assert ); + } ); + + QUnit.test( 'basic operation when synchronous (options.instantHide)', 2, function ( assert ) { + var $collapsible = prepareCollapsible( + '<div class="mw-collapsible">' + loremIpsum + '</div>', + { instantHide: true } + ), + $content = $collapsible.find( '.mw-collapsible-content' ); + + assert.assertTrue( $content.is( ':visible' ), 'content is visible' ); + + $collapsible.find( '.mw-collapsible-toggle' ).trigger( 'click' ); + + assert.assertTrue( $content.is( ':hidden' ), 'after collapsing: content is hidden' ); + } ); + + QUnit.test( 'mw-made-collapsible data added', 1, function ( assert ) { + var $collapsible = prepareCollapsible( + '<div>' + loremIpsum + '</div>' + ); + + assert.equal( $collapsible.data( 'mw-made-collapsible' ), true, 'mw-made-collapsible data present' ); + } ); + + QUnit.test( 'mw-collapsible added when missing', 1, function ( assert ) { + var $collapsible = prepareCollapsible( + '<div>' + loremIpsum + '</div>' + ); + + assert.assertTrue( $collapsible.hasClass( 'mw-collapsible' ), 'mw-collapsible class present' ); + } ); + + QUnit.test( 'mw-collapsed added when missing', 1, function ( assert ) { + var $collapsible = prepareCollapsible( + '<div>' + loremIpsum + '</div>', + { collapsed: true } + ); + + assert.assertTrue( $collapsible.hasClass( 'mw-collapsed' ), 'mw-collapsed class present' ); + } ); + + QUnit.test( 'initial collapse (mw-collapsed class)', 2, function ( assert ) { + var $collapsible = prepareCollapsible( + '<div class="mw-collapsible mw-collapsed">' + loremIpsum + '</div>' + ), + $content = $collapsible.find( '.mw-collapsible-content' ); + + // Synchronous - mw-collapsed should cause instantHide: true to be used on initial collapsing + assert.assertTrue( $content.is( ':hidden' ), 'content is hidden' ); + + $collapsible.on( 'afterExpand.mw-collapsible', function () { + assert.assertTrue( $content.is( ':visible' ), 'after expanding: content is visible' ); + } ); + + $collapsible.find( '.mw-collapsible-toggle' ).trigger( 'click' ); + this.clock.tick( 500 ); + } ); + + QUnit.test( 'initial collapse (options.collapsed)', 2, function ( assert ) { + var $collapsible = prepareCollapsible( + '<div class="mw-collapsible">' + loremIpsum + '</div>', + { collapsed: true } + ), + $content = $collapsible.find( '.mw-collapsible-content' ); + + // Synchronous - collapsed: true should cause instantHide: true to be used on initial collapsing + assert.assertTrue( $content.is( ':hidden' ), 'content is hidden' ); + + $collapsible.on( 'afterExpand.mw-collapsible', function () { + assert.assertTrue( $content.is( ':visible' ), 'after expanding: content is visible' ); + } ); + + $collapsible.find( '.mw-collapsible-toggle' ).trigger( 'click' ); + this.clock.tick( 500 ); + } ); + + QUnit.test( 'clicks on links inside toggler pass through (options.linksPassthru)', 2, function ( assert ) { + var $collapsible = prepareCollapsible( + '<div class="mw-collapsible">' + + '<div class="mw-collapsible-toggle">' + + 'Toggle <a href="#top">toggle</a> toggle <b>toggle</b>' + + '</div>' + + '<div class="mw-collapsible-content">' + loremIpsum + '</div>' + + '</div>', + // Can't do asynchronous because we're testing that the event *doesn't* happen + { instantHide: true } + ), + $content = $collapsible.find( '.mw-collapsible-content' ); + + $collapsible.find( '.mw-collapsible-toggle a' ).trigger( 'click' ); + assert.assertTrue( $content.is( ':visible' ), 'click event on link inside toggle passes through (content not toggled)' ); + + $collapsible.find( '.mw-collapsible-toggle b' ).trigger( 'click' ); + assert.assertTrue( $content.is( ':hidden' ), 'click event on non-link inside toggle toggles content' ); + } ); + + QUnit.test( 'collapse/expand text (data-collapsetext, data-expandtext)', 2, function ( assert ) { + var $collapsible = prepareCollapsible( + '<div class="mw-collapsible" data-collapsetext="Collapse me!" data-expandtext="Expand me!">' + + loremIpsum + + '</div>' + ), + $toggleLink = $collapsible.find( '.mw-collapsible-toggle a' ); + + assert.equal( $toggleLink.text(), 'Collapse me!', 'data-collapsetext is respected' ); + + $collapsible.on( 'afterCollapse.mw-collapsible', function () { + assert.equal( $toggleLink.text(), 'Expand me!', 'data-expandtext is respected' ); + } ); + + $collapsible.find( '.mw-collapsible-toggle' ).trigger( 'click' ); + this.clock.tick( 500 ); + } ); + + QUnit.test( 'collapse/expand text (options.collapseText, options.expandText)', 2, function ( assert ) { + var $collapsible = prepareCollapsible( + '<div class="mw-collapsible">' + loremIpsum + '</div>', + { collapseText: 'Collapse me!', expandText: 'Expand me!' } + ), + $toggleLink = $collapsible.find( '.mw-collapsible-toggle a' ); + + assert.equal( $toggleLink.text(), 'Collapse me!', 'options.collapseText is respected' ); + + $collapsible.on( 'afterCollapse.mw-collapsible', function () { + assert.equal( $toggleLink.text(), 'Expand me!', 'options.expandText is respected' ); + } ); + + $collapsible.find( '.mw-collapsible-toggle' ).trigger( 'click' ); + this.clock.tick( 500 ); + } ); + +}( mediaWiki, jQuery ) ); diff --git a/tests/qunit/suites/resources/jquery/jquery.mwExtension.test.js b/tests/qunit/suites/resources/jquery/jquery.mwExtension.test.js new file mode 100644 index 00000000..795c2bbb --- /dev/null +++ b/tests/qunit/suites/resources/jquery/jquery.mwExtension.test.js @@ -0,0 +1,55 @@ +( function ( $ ) { + QUnit.module( 'jquery.mwExtension', QUnit.newMwEnvironment() ); + + QUnit.test( 'String functions', 7, function ( assert ) { + assert.equal( $.trimLeft( ' foo bar ' ), 'foo bar ', 'trimLeft' ); + assert.equal( $.trimRight( ' foo bar ' ), ' foo bar', 'trimRight' ); + assert.equal( $.ucFirst( 'foo' ), 'Foo', 'ucFirst' ); + + assert.equal( $.escapeRE( '<!-- ([{+mW+}]) $^|?>' ), + '<!\\-\\- \\(\\[\\{\\+mW\\+\\}\\]\\) \\$\\^\\|\\?>', 'escapeRE - Escape specials' ); + assert.equal( $.escapeRE( 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' ), + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'escapeRE - Leave uppercase alone' ); + assert.equal( $.escapeRE( 'abcdefghijklmnopqrstuvwxyz' ), + 'abcdefghijklmnopqrstuvwxyz', 'escapeRE - Leave lowercase alone' ); + assert.equal( $.escapeRE( '0123456789' ), '0123456789', 'escapeRE - Leave numbers alone' ); + } ); + + QUnit.test( 'isDomElement', 6, function ( assert ) { + assert.strictEqual( $.isDomElement( document.createElement( 'div' ) ), true, + 'isDomElement: HTMLElement' ); + assert.strictEqual( $.isDomElement( document.createTextNode( '' ) ), true, + 'isDomElement: TextNode' ); + assert.strictEqual( $.isDomElement( null ), false, + 'isDomElement: null' ); + assert.strictEqual( $.isDomElement( document.getElementsByTagName( 'div' ) ), false, + 'isDomElement: NodeList' ); + assert.strictEqual( $.isDomElement( $( 'div' ) ), false, + 'isDomElement: jQuery' ); + assert.strictEqual( $.isDomElement( { foo: 1 } ), false, + 'isDomElement: Plain Object' ); + } ); + + QUnit.test( 'isEmpty', 7, function ( assert ) { + assert.strictEqual( $.isEmpty( 'string' ), false, 'isEmpty: "string"' ); + assert.strictEqual( $.isEmpty( '0' ), true, 'isEmpty: "0"' ); + assert.strictEqual( $.isEmpty( '' ), true, 'isEmpty: ""' ); + assert.strictEqual( $.isEmpty( 1 ), false, 'isEmpty: 1' ); + assert.strictEqual( $.isEmpty( [] ), true, 'isEmpty: []' ); + assert.strictEqual( $.isEmpty( {} ), true, 'isEmpty: {}' ); + + // Documented behavior + assert.strictEqual( $.isEmpty( { length: 0 } ), true, 'isEmpty: { length: 0 }' ); + } ); + + QUnit.test( 'Comparison functions', 5, function ( assert ) { + assert.ok( $.compareArray( [0, 'a', [], [2, 'b'] ], [0, 'a', [], [2, 'b'] ] ), + 'compareArray: Two deep arrays that are excactly the same' ); + assert.ok( !$.compareArray( [1], [2] ), 'compareArray: Two different arrays (false)' ); + + assert.ok( $.compareObject( {}, {} ), 'compareObject: Two empty objects' ); + assert.ok( $.compareObject( { foo: 1 }, { foo: 1 } ), 'compareObject: Two the same objects' ); + assert.ok( !$.compareObject( { bar: true }, { baz: false } ), + 'compareObject: Two different objects (false)' ); + } ); +}( jQuery ) ); diff --git a/tests/qunit/suites/resources/jquery/jquery.placeholder.test.js b/tests/qunit/suites/resources/jquery/jquery.placeholder.test.js new file mode 100644 index 00000000..bbea8297 --- /dev/null +++ b/tests/qunit/suites/resources/jquery/jquery.placeholder.test.js @@ -0,0 +1,145 @@ +(function ($) { + + QUnit.module('jquery.placeholder', QUnit.newMwEnvironment()); + + QUnit.test('caches results of feature tests', 2, function (assert) { + assert.strictEqual(typeof $.fn.placeholder.input, 'boolean', '$.fn.placeholder.input'); + assert.strictEqual(typeof $.fn.placeholder.textarea, 'boolean', '$.fn.placeholder.textarea'); + }); + + if ($.fn.placeholder.input && $.fn.placeholder.textarea) { + return; + } + + var html = '<form>' + + '<input id="input-type-search" type="search" placeholder="Search this site...">' + + '<input id="input-type-text" type="text" placeholder="e.g. John Doe">' + + '<input id="input-type-email" type="email" placeholder="e.g. address@example.ext">' + + '<input id="input-type-url" type="url" placeholder="e.g. http://mathiasbynens.be/">' + + '<input id="input-type-tel" type="tel" placeholder="e.g. +32 472 77 69 88">' + + '<input id="input-type-password" type="password" placeholder="e.g. hunter2">' + + '<textarea id="textarea" name="message" placeholder="Your message goes here"></textarea>' + + '</form>', + testElement = function ($el, assert) { + + var el = $el[0], + placeholder = el.getAttribute('placeholder'); + + assert.strictEqual($el.placeholder(), $el, 'should be chainable'); + + assert.strictEqual(el.value, placeholder, 'should set `placeholder` text as `value`'); + assert.strictEqual($el.prop('value'), '', 'propHooks works properly'); + assert.strictEqual($el.val(), '', 'valHooks works properly'); + assert.ok($el.hasClass('placeholder'), 'should have `placeholder` class'); + + // test on focus + $el.focus(); + assert.strictEqual(el.value, '', '`value` should be the empty string on focus'); + assert.strictEqual($el.prop('value'), '', 'propHooks works properly'); + assert.strictEqual($el.val(), '', 'valHooks works properly'); + assert.ok(!$el.hasClass('placeholder'), 'should not have `placeholder` class on focus'); + + // and unfocus (blur) again + $el.blur(); + + assert.strictEqual(el.value, placeholder, 'should set `placeholder` text as `value`'); + assert.strictEqual($el.prop('value'), '', 'propHooks works properly'); + assert.strictEqual($el.val(), '', 'valHooks works properly'); + assert.ok($el.hasClass('placeholder'), 'should have `placeholder` class'); + + // change the value + $el.val('lorem ipsum'); + assert.strictEqual($el.prop('value'), 'lorem ipsum', '`$el.val(string)` should change the `value` property'); + assert.strictEqual(el.value, 'lorem ipsum', '`$el.val(string)` should change the `value` attribute'); + assert.ok(!$el.hasClass('placeholder'), '`$el.val(string)` should remove `placeholder` class'); + + // and clear it again + $el.val(''); + assert.strictEqual($el.prop('value'), '', '`$el.val("")` should change the `value` property'); + assert.strictEqual(el.value, placeholder, '`$el.val("")` should change the `value` attribute'); + assert.ok($el.hasClass('placeholder'), '`$el.val("")` should re-enable `placeholder` class'); + + // make sure the placeholder property works as expected. + assert.strictEqual($el.prop('placeholder'), placeholder, '$el.prop(`placeholder`) should return the placeholder value'); + $el.placeholder('new placeholder'); + assert.strictEqual(el.getAttribute('placeholder'), 'new placeholder', '$el.placeholder(<string>) should set the placeholder value'); + assert.strictEqual(el.value, 'new placeholder', '$el.placeholder(<string>) should update the displayed placeholder value'); + $el.placeholder(placeholder); + }; + + QUnit.test('emulates placeholder for <input type=text>', 22, function (assert) { + $('<div>').html(html).appendTo($('#qunit-fixture')); + testElement($('#input-type-text'), assert); + }); + + QUnit.test('emulates placeholder for <input type=search>', 22, function (assert) { + $('<div>').html(html).appendTo($('#qunit-fixture')); + testElement($('#input-type-search'), assert); + }); + + QUnit.test('emulates placeholder for <input type=email>', 22, function (assert) { + $('<div>').html(html).appendTo($('#qunit-fixture')); + testElement($('#input-type-email'), assert); + }); + + QUnit.test('emulates placeholder for <input type=url>', 22, function (assert) { + $('<div>').html(html).appendTo($('#qunit-fixture')); + testElement($('#input-type-url'), assert); + }); + + QUnit.test('emulates placeholder for <input type=tel>', 22, function (assert) { + $('<div>').html(html).appendTo($('#qunit-fixture')); + testElement($('#input-type-tel'), assert); + }); + + QUnit.test('emulates placeholder for <input type=password>', 13, function (assert) { + $('<div>').html(html).appendTo($('#qunit-fixture')); + + var selector = '#input-type-password', + $el = $(selector), + el = $el[0], + placeholder = el.getAttribute('placeholder'); + + assert.strictEqual($el.placeholder(), $el, 'should be chainable'); + + // Re-select the element, as it gets replaced by another one in some browsers + $el = $(selector); + el = $el[0]; + + assert.strictEqual(el.value, placeholder, 'should set `placeholder` text as `value`'); + assert.strictEqual($el.prop('value'), '', 'propHooks works properly'); + assert.strictEqual($el.val(), '', 'valHooks works properly'); + assert.ok($el.hasClass('placeholder'), 'should have `placeholder` class'); + + // test on focus + $el.focus(); + + // Re-select the element, as it gets replaced by another one in some browsers + $el = $(selector); + el = $el[0]; + + assert.strictEqual(el.value, '', '`value` should be the empty string on focus'); + assert.strictEqual($el.prop('value'), '', 'propHooks works properly'); + assert.strictEqual($el.val(), '', 'valHooks works properly'); + assert.ok(!$el.hasClass('placeholder'), 'should not have `placeholder` class on focus'); + + // and unfocus (blur) again + $el.blur(); + + // Re-select the element, as it gets replaced by another one in some browsers + $el = $(selector); + el = $el[0]; + + assert.strictEqual(el.value, placeholder, 'should set `placeholder` text as `value`'); + assert.strictEqual($el.prop('value'), '', 'propHooks works properly'); + assert.strictEqual($el.val(), '', 'valHooks works properly'); + assert.ok($el.hasClass('placeholder'), 'should have `placeholder` class'); + + }); + + QUnit.test('emulates placeholder for <textarea></textarea>', 22, function (assert) { + $('<div>').html(html).appendTo($('#qunit-fixture')); + testElement($('#textarea'), assert); + }); + +}(jQuery)); diff --git a/tests/qunit/suites/resources/jquery/jquery.tabIndex.test.js b/tests/qunit/suites/resources/jquery/jquery.tabIndex.test.js new file mode 100644 index 00000000..12137931 --- /dev/null +++ b/tests/qunit/suites/resources/jquery/jquery.tabIndex.test.js @@ -0,0 +1,35 @@ +( function ( $ ) { + QUnit.module( 'jquery.tabIndex', QUnit.newMwEnvironment() ); + + QUnit.test( 'firstTabIndex', 2, function ( assert ) { + var html, $testA, $testB; + html = '<form>' + + '<input tabindex="7" />' + + '<input tabindex="9" />' + + '<textarea tabindex="2">Foobar</textarea>' + + '<textarea tabindex="5">Foobar</textarea>' + + '</form>'; + + $testA = $( '<div>' ).html( html ).appendTo( '#qunit-fixture' ); + assert.strictEqual( $testA.firstTabIndex(), 2, 'First tabindex should be 2 within this context.' ); + + $testB = $( '<div>' ); + assert.strictEqual( $testB.firstTabIndex(), null, 'Return null if none available.' ); + } ); + + QUnit.test( 'lastTabIndex', 2, function ( assert ) { + var html, $testA, $testB; + html = '<form>' + + '<input tabindex="7" />' + + '<input tabindex="9" />' + + '<textarea tabindex="2">Foobar</textarea>' + + '<textarea tabindex="5">Foobar</textarea>' + + '</form>'; + + $testA = $( '<div>' ).html( html ).appendTo( '#qunit-fixture' ); + assert.strictEqual( $testA.lastTabIndex(), 9, 'Last tabindex should be 9 within this context.' ); + + $testB = $( '<div>' ); + assert.strictEqual( $testB.lastTabIndex(), null, 'Return null if none available.' ); + } ); +}( jQuery ) ); diff --git a/tests/qunit/suites/resources/jquery/jquery.tablesorter.test.js b/tests/qunit/suites/resources/jquery/jquery.tablesorter.test.js new file mode 100644 index 00000000..92dad9ff --- /dev/null +++ b/tests/qunit/suites/resources/jquery/jquery.tablesorter.test.js @@ -0,0 +1,1327 @@ +( function ( $, mw ) { + var header, + + // Data set "simple" + a1 = [ 'A', '1' ], + a2 = [ 'A', '2' ], + a3 = [ 'A', '3' ], + b1 = [ 'B', '1' ], + b2 = [ 'B', '2' ], + b3 = [ 'B', '3' ], + simple = [a2, b3, a1, a3, b2, b1], + simpleAsc = [a1, a2, a3, b1, b2, b3], + simpleDescasc = [b1, b2, b3, a1, a2, a3], + + // Data set "colspan" + aaa1 = [ 'A', 'A', 'A', '1' ], + aab5 = [ 'A', 'A', 'B', '5' ], + abc3 = [ 'A', 'B', 'C', '3' ], + bbc2 = [ 'B', 'B', 'C', '2' ], + caa4 = [ 'C', 'A', 'A', '4' ], + colspanInitial = [ aab5, aaa1, abc3, bbc2, caa4 ], + + // Data set "planets" + mercury = [ 'Mercury', '2439.7' ], + venus = [ 'Venus', '6051.8' ], + earth = [ 'Earth', '6371.0' ], + mars = [ 'Mars', '3390.0' ], + jupiter = [ 'Jupiter', '69911' ], + saturn = [ 'Saturn', '58232' ], + planets = [mercury, venus, earth, mars, jupiter, saturn], + planetsAscName = [earth, jupiter, mars, mercury, saturn, venus], + planetsAscRadius = [mercury, mars, venus, earth, saturn, jupiter], + planetsRowspan, + planetsRowspanII, + planetsAscNameLegacy, + + // Data set "ipv4" + ipv4 = [ + // Some randomly generated fake IPs + ['45.238.27.109'], + ['44.172.9.22'], + ['247.240.82.209'], + ['204.204.132.158'], + ['170.38.91.162'], + ['197.219.164.9'], + ['45.68.154.72'], + ['182.195.149.80'] + ], + ipv4Sorted = [ + // Sort order should go octet by octet + ['44.172.9.22'], + ['45.68.154.72'], + ['45.238.27.109'], + ['170.38.91.162'], + ['182.195.149.80'], + ['197.219.164.9'], + ['204.204.132.158'], + ['247.240.82.209'] + ], + + // Data set "umlaut" + umlautWords = [ + ['Günther'], + ['Peter'], + ['Björn'], + ['Bjorn'], + ['Apfel'], + ['Äpfel'], + ['Strasse'], + ['Sträßschen'] + ], + umlautWordsSorted = [ + ['Äpfel'], + ['Apfel'], + ['Björn'], + ['Bjorn'], + ['Günther'], + ['Peter'], + ['Sträßschen'], + ['Strasse'] + ], + + complexMDYDates = [ + ['January, 19 2010'], + ['April 21 1991'], + ['04 22 1991'], + ['5.12.1990'], + ['December 12 \'10'] + ], + complexMDYSorted = [ + ['5.12.1990'], + ['April 21 1991'], + ['04 22 1991'], + ['January, 19 2010'], + ['December 12 \'10'] + ], + + currencyUnsorted = [ + ['1.02 $'], + ['$ 3.00'], + ['€ 2,99'], + ['$ 1.00'], + ['$3.50'], + ['$ 1.50'], + ['€ 0.99'] + ], + currencySorted = [ + ['€ 0.99'], + ['$ 1.00'], + ['1.02 $'], + ['$ 1.50'], + ['$ 3.00'], + ['$3.50'], + // Comma's sort after dots + // Not intentional but test to detect changes + ['€ 2,99'] + ], + + numbers = [ + [ '12' ], + [ '7' ], + [ '13,000'], + [ '9' ], + [ '14' ], + [ '8.0' ] + ], + numbersAsc = [ + [ '7' ], + [ '8.0' ], + [ '9' ], + [ '12' ], + [ '14' ], + [ '13,000'] + ], + + correctDateSorting1 = [ + ['01 January 2010'], + ['05 February 2010'], + ['16 January 2010'] + ], + correctDateSortingSorted1 = [ + ['01 January 2010'], + ['16 January 2010'], + ['05 February 2010'] + ], + + correctDateSorting2 = [ + ['January 01 2010'], + ['February 05 2010'], + ['January 16 2010'] + ], + correctDateSortingSorted2 = [ + ['January 01 2010'], + ['January 16 2010'], + ['February 05 2010'] + ]; + + QUnit.module( 'jquery.tablesorter', QUnit.newMwEnvironment( { + config: { + wgMonthNames: ['', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], + wgMonthNamesShort: ['', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], + wgDefaultDateFormat: 'dmy', + wgSeparatorTransformTable: ['', ''], + wgDigitTransformTable: ['', ''], + wgContentLanguage: 'en' + } + } ) ); + + /** + * Create an HTML table from an array of row arrays containing text strings. + * First row will be header row. No fancy rowspan/colspan stuff. + * + * @param {String[]} header + * @param {String[][]} data + * @return jQuery + */ + function tableCreate( header, data ) { + var i, + $table = $( '<table class="sortable"><thead></thead><tbody></tbody></table>' ), + $thead = $table.find( 'thead' ), + $tbody = $table.find( 'tbody' ), + $tr = $( '<tr>' ); + + $.each( header, function ( i, str ) { + var $th = $( '<th>' ); + $th.text( str ).appendTo( $tr ); + } ); + $tr.appendTo( $thead ); + + for ( i = 0; i < data.length; i++ ) { + /*jshint loopfunc: true */ + $tr = $( '<tr>' ); + $.each( data[i], function ( j, str ) { + var $td = $( '<td>' ); + $td.text( str ).appendTo( $tr ); + } ); + $tr.appendTo( $tbody ); + } + return $table; + } + + /** + * Extract text from table. + * + * @param {jQuery} $table + * @return String[][] + */ + function tableExtract( $table ) { + var data = []; + + $table.find( 'tbody' ).find( 'tr' ).each( function ( i, tr ) { + var row = []; + $( tr ).find( 'td,th' ).each( function ( i, td ) { + row.push( $( td ).text() ); + } ); + data.push( row ); + } ); + return data; + } + + /** + * Run a table test by building a table with the given data, + * running some callback on it, then checking the results. + * + * @param {String} msg text to pass on to qunit for the comparison + * @param {String[]} header cols to make the table + * @param {String[][]} data rows/cols to make the table + * @param {String[][]} expected rows/cols to compare against at end + * @param {function($table)} callback something to do with the table before we compare + */ + function tableTest( msg, header, data, expected, callback ) { + QUnit.test( msg, 1, function ( assert ) { + var extracted, + $table = tableCreate( header, data ); + + // Give caller a chance to set up sorting and manipulate the table. + callback( $table ); + + // Table sorting is done synchronously; if it ever needs to change back + // to asynchronous, we'll need a timeout or a callback here. + extracted = tableExtract( $table ); + assert.deepEqual( extracted, expected, msg ); + } ); + } + + /** + * Run a table test by building a table with the given HTML, + * running some callback on it, then checking the results. + * + * @param {String} msg text to pass on to qunit for the comparison + * @param {String} HTML to make the table + * @param {String[][]} expected rows/cols to compare against at end + * @param {function($table)} callback something to do with the table before we compare + */ + function tableTestHTML( msg, html, expected, callback ) { + QUnit.test( msg, 1, function ( assert ) { + var extracted, + $table = $( html ); + + // Give caller a chance to set up sorting and manipulate the table. + if ( callback ) { + callback( $table ); + } else { + $table.tablesorter(); + $table.find( '#sortme' ).click(); + } + + // Table sorting is done synchronously; if it ever needs to change back + // to asynchronous, we'll need a timeout or a callback here. + extracted = tableExtract( $table ); + assert.deepEqual( extracted, expected, msg ); + } ); + } + + function reversed( arr ) { + // Clone array + var arr2 = arr.slice( 0 ); + + arr2.reverse(); + + return arr2; + } + + // Sample data set using planets named and their radius + header = [ 'Planet', 'Radius (km)']; + + tableTest( + 'Basic planet table: sorting initially - ascending by name', + header, + planets, + planetsAscName, + function ( $table ) { + $table.tablesorter( { sortList: [ + { 0: 'asc' } + ] } ); + } + ); + tableTest( + 'Basic planet table: sorting initially - descending by radius', + header, + planets, + reversed( planetsAscRadius ), + function ( $table ) { + $table.tablesorter( { sortList: [ + { 1: 'desc' } + ] } ); + } + ); + tableTest( + 'Basic planet table: ascending by name', + header, + planets, + planetsAscName, + function ( $table ) { + $table.tablesorter(); + $table.find( '.headerSort:eq(0)' ).click(); + } + ); + tableTest( + 'Basic planet table: ascending by name a second time', + header, + planets, + planetsAscName, + function ( $table ) { + $table.tablesorter(); + $table.find( '.headerSort:eq(0)' ).click(); + } + ); + tableTest( + 'Basic planet table: ascending by name (multiple clicks)', + header, + planets, + planetsAscName, + function ( $table ) { + $table.tablesorter(); + $table.find( '.headerSort:eq(0)' ).click(); + $table.find( '.headerSort:eq(1)' ).click(); + $table.find( '.headerSort:eq(0)' ).click(); + } + ); + tableTest( + 'Basic planet table: descending by name', + header, + planets, + reversed( planetsAscName ), + function ( $table ) { + $table.tablesorter(); + $table.find( '.headerSort:eq(0)' ).click().click(); + } + ); + tableTest( + 'Basic planet table: ascending radius', + header, + planets, + planetsAscRadius, + function ( $table ) { + $table.tablesorter(); + $table.find( '.headerSort:eq(1)' ).click(); + } + ); + tableTest( + 'Basic planet table: descending radius', + header, + planets, + reversed( planetsAscRadius ), + function ( $table ) { + $table.tablesorter(); + $table.find( '.headerSort:eq(1)' ).click().click(); + } + ); + + header = [ 'column1', 'column2' ]; + + tableTest( + 'Sorting multiple columns by passing sort list', + header, + simple, + simpleAsc, + function ( $table ) { + $table.tablesorter( + { sortList: [ + { 0: 'asc' }, + { 1: 'asc' } + ] } + ); + } + ); + tableTest( + 'Sorting multiple columns by programmatically triggering sort()', + header, + simple, + simpleDescasc, + function ( $table ) { + $table.tablesorter(); + $table.data( 'tablesorter' ).sort( + [ + { 0: 'desc' }, + { 1: 'asc' } + ] + ); + } + ); + tableTest( + 'Reset to initial sorting by triggering sort() without any parameters', + header, + simple, + simpleAsc, + function ( $table ) { + $table.tablesorter( + { sortList: [ + { 0: 'asc' }, + { 1: 'asc' } + ] } + ); + $table.data( 'tablesorter' ).sort( + [ + { 0: 'desc' }, + { 1: 'asc' } + ] + ); + $table.data( 'tablesorter' ).sort(); + } + ); + tableTest( + 'Sort via click event after having initialized the tablesorter with initial sorting', + header, + simple, + simpleDescasc, + function ( $table ) { + $table.tablesorter( + { sortList: [ { 0: 'asc' }, { 1: 'asc' } ] } + ); + $table.find( '.headerSort:eq(0)' ).click(); + } + ); + tableTest( + 'Multi-sort via click event after having initialized the tablesorter with initial sorting', + header, + simple, + simpleAsc, + function ( $table ) { + $table.tablesorter( + { sortList: [ { 0: 'desc' }, { 1: 'desc' } ] } + ); + $table.find( '.headerSort:eq(0)' ).click(); + + // Pretend to click while pressing the multi-sort key + var event = $.Event( 'click' ); + event[$table.data( 'tablesorter' ).config.sortMultiSortKey] = true; + $table.find( '.headerSort:eq(1)' ).trigger( event ); + } + ); + QUnit.test( 'Reset sorting making table appear unsorted', 3, function ( assert ) { + var $table = tableCreate( header, simple ); + $table.tablesorter( + { sortList: [ + { 0: 'desc' }, + { 1: 'asc' } + ] } + ); + $table.data( 'tablesorter' ).sort( [] ); + + assert.equal( + $table.find( 'th.headerSortUp' ).length + $table.find( 'th.headerSortDown' ).length, + 0, + 'No sort specific sort classes addign to header cells' + ); + + assert.equal( + $table.find( 'th' ).first().attr( 'title' ), + mw.msg( 'sort-ascending' ), + 'First header cell has default title' + ); + + assert.equal( + $table.find( 'th' ).first().attr( 'title' ), + $table.find( 'th' ).last().attr( 'title' ), + 'Both header cells\' titles match' + ); + } ); + + // Sorting with colspans + header = [ 'column1a', 'column1b', 'column1c', 'column2' ]; + + tableTest( 'Sorting with colspanned headers: spanned column', + header, + colspanInitial, + [ aaa1, aab5, abc3, bbc2, caa4 ], + function ( $table ) { + // Make colspanned header for test + $table.find( 'tr:eq(0) th:eq(1), tr:eq(0) th:eq(2)' ).remove(); + $table.find( 'tr:eq(0) th:eq(0)' ).attr( 'colspan', '3' ); + + $table.tablesorter(); + $table.find( '.headerSort:eq(0)' ).click(); + } + ); + tableTest( 'Sorting with colspanned headers: sort spanned column twice', + header, + colspanInitial, + [ caa4, bbc2, abc3, aab5, aaa1 ], + function ( $table ) { + // Make colspanned header for test + $table.find( 'tr:eq(0) th:eq(1), tr:eq(0) th:eq(2)' ).remove(); + $table.find( 'tr:eq(0) th:eq(0)' ).attr( 'colspan', '3' ); + + $table.tablesorter(); + $table.find( '.headerSort:eq(0)' ).click(); + $table.find( '.headerSort:eq(0)' ).click(); + } + ); + tableTest( 'Sorting with colspanned headers: subsequent column', + header, + colspanInitial, + [ aaa1, bbc2, abc3, caa4, aab5 ], + function ( $table ) { + // Make colspanned header for test + $table.find( 'tr:eq(0) th:eq(1), tr:eq(0) th:eq(2)' ).remove(); + $table.find( 'tr:eq(0) th:eq(0)' ).attr( 'colspan', '3' ); + + $table.tablesorter(); + $table.find( '.headerSort:eq(1)' ).click(); + } + ); + tableTest( 'Sorting with colspanned headers: sort subsequent column twice', + header, + colspanInitial, + [ aab5, caa4, abc3, bbc2, aaa1 ], + function ( $table ) { + // Make colspanned header for test + $table.find( 'tr:eq(0) th:eq(1), tr:eq(0) th:eq(2)' ).remove(); + $table.find( 'tr:eq(0) th:eq(0)' ).attr( 'colspan', '3' ); + + $table.tablesorter(); + $table.find( '.headerSort:eq(1)' ).click(); + $table.find( '.headerSort:eq(1)' ).click(); + } + ); + + tableTest( + 'Basic planet table: one unsortable column', + header, + planets, + planets, + function ( $table ) { + $table.find( 'tr:eq(0) > th:eq(0)' ).addClass( 'unsortable' ); + + $table.tablesorter(); + $table.find( 'tr:eq(0) > th:eq(0)' ).click(); + } + ); + + // Regression tests! + tableTest( + 'Bug 28775: German-style (dmy) short numeric dates', + ['Date'], + [ + // German-style dates are day-month-year + ['11.11.2011'], + ['01.11.2011'], + ['02.10.2011'], + ['03.08.2011'], + ['09.11.2011'] + ], + [ + // Sorted by ascending date + ['03.08.2011'], + ['02.10.2011'], + ['01.11.2011'], + ['09.11.2011'], + ['11.11.2011'] + ], + function ( $table ) { + mw.config.set( 'wgDefaultDateFormat', 'dmy' ); + mw.config.set( 'wgContentLanguage', 'de' ); + + $table.tablesorter(); + $table.find( '.headerSort:eq(0)' ).click(); + } + ); + + tableTest( + 'Bug 28775: American-style (mdy) short numeric dates', + ['Date'], + [ + // American-style dates are month-day-year + ['11.11.2011'], + ['01.11.2011'], + ['02.10.2011'], + ['03.08.2011'], + ['09.11.2011'] + ], + [ + // Sorted by ascending date + ['01.11.2011'], + ['02.10.2011'], + ['03.08.2011'], + ['09.11.2011'], + ['11.11.2011'] + ], + function ( $table ) { + mw.config.set( 'wgDefaultDateFormat', 'mdy' ); + + $table.tablesorter(); + $table.find( '.headerSort:eq(0)' ).click(); + } + ); + + tableTest( + 'Bug 17141: IPv4 address sorting', + ['IP'], + ipv4, + ipv4Sorted, + function ( $table ) { + $table.tablesorter(); + $table.find( '.headerSort:eq(0)' ).click(); + } + ); + tableTest( + 'Bug 17141: IPv4 address sorting (reverse)', + ['IP'], + ipv4, + reversed( ipv4Sorted ), + function ( $table ) { + $table.tablesorter(); + $table.find( '.headerSort:eq(0)' ).click().click(); + } + ); + + tableTest( + 'Accented Characters with custom collation', + ['Name'], + umlautWords, + umlautWordsSorted, + function ( $table ) { + mw.config.set( 'tableSorterCollation', { + 'ä': 'ae', + 'ö': 'oe', + 'ß': 'ss', + 'ü': 'ue' + } ); + + $table.tablesorter(); + $table.find( '.headerSort:eq(0)' ).click(); + } + ); + + QUnit.test( 'Rowspan not exploded on init', 1, function ( assert ) { + var $table = tableCreate( header, planets ); + + // Modify the table to have a multiple-row-spanning cell: + // - Remove 2nd cell of 4th row, and, 2nd cell or 5th row. + $table.find( 'tr:eq(3) td:eq(1), tr:eq(4) td:eq(1)' ).remove(); + // - Set rowspan for 2nd cell of 3rd row to 3. + // This covers the removed cell in the 4th and 5th row. + $table.find( 'tr:eq(2) td:eq(1)' ).attr( 'rowspan', '3' ); + + $table.tablesorter(); + + assert.equal( + $table.find( 'tr:eq(2) td:eq(1)' ).prop( 'rowSpan' ), + 3, + 'Rowspan not exploded' + ); + } ); + + planetsRowspan = [ + [ 'Earth', '6051.8' ], + jupiter, + [ 'Mars', '6051.8' ], + mercury, + saturn, + venus + ]; + planetsRowspanII = [ jupiter, mercury, saturn, venus, [ 'Venus', '6371.0' ], [ 'Venus', '3390.0' ] ]; + + tableTest( + 'Basic planet table: same value for multiple rows via rowspan', + header, + planets, + planetsRowspan, + function ( $table ) { + // Modify the table to have a multiple-row-spanning cell: + // - Remove 2nd cell of 4th row, and, 2nd cell or 5th row. + $table.find( 'tr:eq(3) td:eq(1), tr:eq(4) td:eq(1)' ).remove(); + // - Set rowspan for 2nd cell of 3rd row to 3. + // This covers the removed cell in the 4th and 5th row. + $table.find( 'tr:eq(2) td:eq(1)' ).attr( 'rowspan', '3' ); + + $table.tablesorter(); + $table.find( '.headerSort:eq(0)' ).click(); + } + ); + tableTest( + 'Basic planet table: same value for multiple rows via rowspan (sorting initially)', + header, + planets, + planetsRowspan, + function ( $table ) { + // Modify the table to have a multiple-row-spanning cell: + // - Remove 2nd cell of 4th row, and, 2nd cell or 5th row. + $table.find( 'tr:eq(3) td:eq(1), tr:eq(4) td:eq(1)' ).remove(); + // - Set rowspan for 2nd cell of 3rd row to 3. + // This covers the removed cell in the 4th and 5th row. + $table.find( 'tr:eq(2) td:eq(1)' ).attr( 'rowspan', '3' ); + + $table.tablesorter( { sortList: [ + { 0: 'asc' } + ] } ); + } + ); + tableTest( + 'Basic planet table: Same value for multiple rows via rowspan II', + header, + planets, + planetsRowspanII, + function ( $table ) { + // Modify the table to have a multiple-row-spanning cell: + // - Remove 1st cell of 4th row, and, 1st cell or 5th row. + $table.find( 'tr:eq(3) td:eq(0), tr:eq(4) td:eq(0)' ).remove(); + // - Set rowspan for 1st cell of 3rd row to 3. + // This covers the removed cell in the 4th and 5th row. + $table.find( 'tr:eq(2) td:eq(0)' ).attr( 'rowspan', '3' ); + + $table.tablesorter(); + $table.find( '.headerSort:eq(0)' ).click(); + } + ); + + tableTest( + 'Complex date parsing I', + ['date'], + complexMDYDates, + complexMDYSorted, + function ( $table ) { + mw.config.set( 'wgDefaultDateFormat', 'mdy' ); + + $table.tablesorter(); + $table.find( '.headerSort:eq(0)' ).click(); + } + ); + + tableTest( + 'Currency parsing I', + ['currency'], + currencyUnsorted, + currencySorted, + function ( $table ) { + $table.tablesorter(); + $table.find( '.headerSort:eq(0)' ).click(); + } + ); + + planetsAscNameLegacy = planetsAscName.slice( 0 ); + planetsAscNameLegacy[4] = planetsAscNameLegacy[5]; + planetsAscNameLegacy.pop(); + + tableTest( + 'Legacy compat with .sortbottom', + header, + planets, + planetsAscNameLegacy, + function ( $table ) { + $table.find( 'tr:last' ).addClass( 'sortbottom' ); + $table.tablesorter(); + $table.find( '.headerSort:eq(0)' ).click(); + } + ); + + QUnit.test( 'Test detection routine', 1, function ( assert ) { + var $table; + $table = $( + '<table class="sortable">' + + '<caption>CAPTION</caption>' + + '<tr><th>THEAD</th></tr>' + + '<tr><td>1</td></tr>' + + '<tr class="sortbottom"><td>text</td></tr>' + + '</table>' + ); + $table.tablesorter(); + $table.find( '.headerSort:eq(0)' ).click(); + + assert.equal( + $table.data( 'tablesorter' ).config.parsers[0].id, + 'number', + 'Correctly detected column content skipping sortbottom' + ); + } ); + + /** FIXME: the diff output is not very readeable. */ + QUnit.test( 'bug 32047 - caption must be before thead', 1, function ( assert ) { + var $table; + $table = $( + '<table class="sortable">' + + '<caption>CAPTION</caption>' + + '<tr><th>THEAD</th></tr>' + + '<tr><td>A</td></tr>' + + '<tr><td>B</td></tr>' + + '<tr class="sortbottom"><td>TFOOT</td></tr>' + + '</table>' + ); + $table.tablesorter(); + + assert.equal( + $table.children().get( 0 ).nodeName, + 'CAPTION', + 'First element after <thead> must be <caption> (bug 32047)' + ); + } ); + + QUnit.test( 'data-sort-value attribute, when available, should override sorting position', 3, function ( assert ) { + var $table, data; + + // Example 1: All cells except one cell without data-sort-value, + // which should be sorted at it's text content value. + $table = $( + '<table class="sortable"><thead><tr><th>Data</th></tr></thead>' + + '<tbody>' + + '<tr><td>Cheetah</td></tr>' + + '<tr><td data-sort-value="Apple">Bird</td></tr>' + + '<tr><td data-sort-value="Bananna">Ferret</td></tr>' + + '<tr><td data-sort-value="Drupe">Elephant</td></tr>' + + '<tr><td data-sort-value="Cherry">Dolphin</td></tr>' + + '</tbody></table>' + ); + $table.tablesorter().find( '.headerSort:eq(0)' ).click(); + + data = []; + $table.find( 'tbody > tr' ).each( function ( i, tr ) { + $( tr ).find( 'td' ).each( function ( i, td ) { + data.push( { + data: $( td ).data( 'sortValue' ), + text: $( td ).text() + } ); + } ); + } ); + + assert.deepEqual( data, [ + { + data: 'Apple', + text: 'Bird' + }, + { + data: 'Bananna', + text: 'Ferret' + }, + { + data: undefined, + text: 'Cheetah' + }, + { + data: 'Cherry', + text: 'Dolphin' + }, + { + data: 'Drupe', + text: 'Elephant' + } + ], 'Order matches expected order (based on data-sort-value attribute values)' ); + + // Example 2 + $table = $( + '<table class="sortable"><thead><tr><th>Data</th></tr></thead>' + + '<tbody>' + + '<tr><td>D</td></tr>' + + '<tr><td data-sort-value="E">A</td></tr>' + + '<tr><td>B</td></tr>' + + '<tr><td>G</td></tr>' + + '<tr><td data-sort-value="F">C</td></tr>' + + '</tbody></table>' + ); + $table.tablesorter().find( '.headerSort:eq(0)' ).click(); + + data = []; + $table.find( 'tbody > tr' ).each( function ( i, tr ) { + $( tr ).find( 'td' ).each( function ( i, td ) { + data.push( { + data: $( td ).data( 'sortValue' ), + text: $( td ).text() + } ); + } ); + } ); + + assert.deepEqual( data, [ + { + data: undefined, + text: 'B' + }, + { + data: undefined, + text: 'D' + }, + { + data: 'E', + text: 'A' + }, + { + data: 'F', + text: 'C' + }, + { + data: undefined, + text: 'G' + } + ], 'Order matches expected order (based on data-sort-value attribute values)' ); + + // Example 3: Test that live changes are used from data-sort-value, + // even if they change after the tablesorter is constructed (bug 38152). + $table = $( + '<table class="sortable"><thead><tr><th>Data</th></tr></thead>' + + '<tbody>' + + '<tr><td>D</td></tr>' + + '<tr><td data-sort-value="1">A</td></tr>' + + '<tr><td>B</td></tr>' + + '<tr><td data-sort-value="2">G</td></tr>' + + '<tr><td>C</td></tr>' + + '</tbody></table>' + ); + // initialize table sorter and sort once + $table + .tablesorter() + .find( '.headerSort:eq(0)' ).click(); + + // Change the sortValue data properties (bug 38152) + // - change data + $table.find( 'td:contains(A)' ).data( 'sortValue', 3 ); + // - add data + $table.find( 'td:contains(B)' ).data( 'sortValue', 1 ); + // - remove data, bring back attribute: 2 + $table.find( 'td:contains(G)' ).removeData( 'sortValue' ); + + // Now sort again (twice, so it is back at Ascending) + $table.find( '.headerSort:eq(0)' ).click(); + $table.find( '.headerSort:eq(0)' ).click(); + + data = []; + $table.find( 'tbody > tr' ).each( function ( i, tr ) { + $( tr ).find( 'td' ).each( function ( i, td ) { + data.push( { + data: $( td ).data( 'sortValue' ), + text: $( td ).text() + } ); + } ); + } ); + + assert.deepEqual( data, [ + { + data: 1, + text: 'B' + }, + { + data: 2, + text: 'G' + }, + { + data: 3, + text: 'A' + }, + { + data: undefined, + text: 'C' + }, + { + data: undefined, + text: 'D' + } + ], 'Order matches expected order, using the current sortValue in $.data()' ); + + } ); + + tableTest( 'bug 8115: sort numbers with commas (ascending)', + ['Numbers'], numbers, numbersAsc, + function ( $table ) { + $table.tablesorter(); + $table.find( '.headerSort:eq(0)' ).click(); + } + ); + + tableTest( 'bug 8115: sort numbers with commas (descending)', + ['Numbers'], numbers, reversed( numbersAsc ), + function ( $table ) { + $table.tablesorter(); + $table.find( '.headerSort:eq(0)' ).click().click(); + } + ); + // TODO add numbers sorting tests for bug 8115 with a different language + + QUnit.test( 'bug 32888 - Tables inside a tableheader cell', 2, function ( assert ) { + var $table; + $table = $( + '<table class="sortable" id="mw-bug-32888">' + + '<tr><th>header<table id="mw-bug-32888-2">' + + '<tr><th>1</th><th>2</th></tr>' + + '</table></th></tr>' + + '<tr><td>A</td></tr>' + + '<tr><td>B</td></tr>' + + '</table>' + ); + $table.tablesorter(); + + assert.equal( + $table.find( '> thead:eq(0) > tr > th.headerSort' ).length, + 1, + 'Child tables inside a headercell should not interfere with sortable headers (bug 32888)' + ); + assert.equal( + $( '#mw-bug-32888-2' ).find( 'th.headerSort' ).length, + 0, + 'The headers of child tables inside a headercell should not be sortable themselves (bug 32888)' + ); + } ); + + tableTest( + 'Correct date sorting I', + ['date'], + correctDateSorting1, + correctDateSortingSorted1, + function ( $table ) { + mw.config.set( 'wgDefaultDateFormat', 'mdy' ); + + $table.tablesorter(); + $table.find( '.headerSort:eq(0)' ).click(); + } + ); + + tableTest( + 'Correct date sorting II', + ['date'], + correctDateSorting2, + correctDateSortingSorted2, + function ( $table ) { + mw.config.set( 'wgDefaultDateFormat', 'dmy' ); + + $table.tablesorter(); + $table.find( '.headerSort:eq(0)' ).click(); + } + ); + + QUnit.test( 'Sorting images using alt text', 1, function ( assert ) { + var $table = $( + '<table class="sortable">' + + '<tr><th>THEAD</th></tr>' + + '<tr><td><img alt="2"/></td></tr>' + + '<tr><td>1</td></tr>' + + '</table>' + ); + $table.tablesorter().find( '.headerSort:eq(0)' ).click(); + + assert.equal( + $table.find( 'td' ).first().text(), + '1', + 'Applied correct sorting order' + ); + } ); + + QUnit.test( 'Sorting images using alt text (complex)', 1, function ( assert ) { + var $table = $( + '<table class="sortable">' + + '<tr><th>THEAD</th></tr>' + + '<tr><td><img alt="D" />A</td></tr>' + + '<tr><td>CC</td></tr>' + + '<tr><td><a><img alt="A" /></a>F</tr>' + + '<tr><td><img alt="A" /><strong>E</strong></tr>' + + '<tr><td><strong><img alt="A" />D</strong></tr>' + + '<tr><td><img alt="A" />C</tr>' + + '</table>' + ); + $table.tablesorter().find( '.headerSort:eq(0)' ).click(); + + assert.equal( + $table.find( 'td' ).text(), + 'CDEFCCA', + 'Applied correct sorting order' + ); + } ); + + QUnit.test( 'Sorting images using alt text (with format autodetection)', 1, function ( assert ) { + var $table = $( + '<table class="sortable">' + + '<tr><th>THEAD</th></tr>' + + '<tr><td><img alt="1" />7</td></tr>' + + '<tr><td>1<img alt="6" /></td></tr>' + + '<tr><td>5</td></tr>' + + '<tr><td>4</td></tr>' + + '</table>' + ); + $table.tablesorter().find( '.headerSort:eq(0)' ).click(); + + assert.equal( + $table.find( 'td' ).text(), + '4517', + 'Applied correct sorting order' + ); + } ); + + QUnit.test( 'bug 38911 - The row with the largest amount of columns should receive the sort indicators', 3, function ( assert ) { + var $table = $( + '<table class="sortable">' + + '<thead>' + + '<tr><th rowspan="2" id="A1">A1</th><th colspan="2">B2a</th></tr>' + + '<tr><th id="B2b">B2b</th><th id="C2b">C2b</th></tr>' + + '</thead>' + + '<tr><td>A</td><td>Aa</td><td>Ab</td></tr>' + + '<tr><td>B</td><td>Ba</td><td>Bb</td></tr>' + + '</table>' + ); + $table.tablesorter(); + + assert.equal( + $table.find( '#A1' ).attr( 'class' ), + 'headerSort', + 'The first column of the first row should be sortable' + ); + assert.equal( + $table.find( '#B2b' ).attr( 'class' ), + 'headerSort', + 'The th element of the 2nd row of the 2nd column should be sortable' + ); + assert.equal( + $table.find( '#C2b' ).attr( 'class' ), + 'headerSort', + 'The th element of the 2nd row of the 3rd column should be sortable' + ); + } ); + + QUnit.test( 'rowspans in table headers should prefer the last row when rows are equal in length', 2, function ( assert ) { + var $table = $( + '<table class="sortable">' + + '<thead>' + + '<tr><th rowspan="2" id="A1">A1</th><th>B2a</th></tr>' + + '<tr><th id="B2b">B2b</th></tr>' + + '</thead>' + + '<tr><td>A</td><td>Aa</td></tr>' + + '<tr><td>B</td><td>Ba</td></tr>' + + '</table>' + ); + $table.tablesorter(); + + assert.equal( + $table.find( '#A1' ).attr( 'class' ), + 'headerSort', + 'The first column of the first row should be sortable' + ); + assert.equal( + $table.find( '#B2b' ).attr( 'class' ), + 'headerSort', + 'The th element of the 2nd row of the 2nd column should be sortable' + ); + } ); + + QUnit.test( 'holes in the table headers should not throw JS errors', 2, function ( assert ) { + var $table = $( + '<table class="sortable">' + + '<thead>' + + '<tr><th id="A1">A1</th><th>B1</th><th id="C1" rowspan="2">C1</th></tr>' + + '<tr><th id="A2">A2</th></tr>' + + '</thead>' + + '<tr><td>A</td><td>Aa</td><td>Aaa</td></tr>' + + '<tr><td>B</td><td>Ba</td><td>Bbb</td></tr>' + + '</table>' + ); + $table.tablesorter(); + assert.equal( $table.find( '#A2' ).prop( 'headerIndex' ), + undefined, + 'A2 should not be a sort header' + ); + assert.equal( $table.find( '#C1' ).prop( 'headerIndex' ), + 2, + 'C1 should be a sort header' + ); + } ); + + // bug 53527 + QUnit.test( 'td cells in thead should not be taken into account for longest row calculation', 2, function ( assert ) { + var $table = $( + '<table class="sortable">' + + '<thead>' + + '<tr><th id="A1">A1</th><th>B1</th><td id="C1">C1</td></tr>' + + '<tr><th id="A2">A2</th><th>B2</th><th id="C2">C2</th></tr>' + + '</thead>' + + '</table>' + ); + $table.tablesorter(); + assert.equal( $table.find( '#C2' ).prop( 'headerIndex' ), + 2, + 'C2 should be a sort header' + ); + assert.equal( $table.find( '#C1' ).prop( 'headerIndex' ), + undefined, + 'C1 should not be a sort header' + ); + } ); + + // bug 41889 - exploding rowspans in more complex cases + tableTestHTML( + 'Rowspan exploding with row headers', + '<table class="sortable">' + + '<thead><tr><th id="sortme">n</th><th>foo</th><th>bar</th><th>baz</th></tr></thead>' + + '<tbody>' + + '<tr><td>1</td><th rowspan="2">foo</th><td rowspan="2">bar</td><td>baz</td></tr>' + + '<tr><td>2</td><td>baz</td></tr>' + + '</tbody></table>', + [ + [ '1', 'foo', 'bar', 'baz' ], + [ '2', 'foo', 'bar', 'baz' ] + ] + ); + + // bug 53211 - exploding rowspans in more complex cases + QUnit.test( + 'Rowspan exploding with row headers and colspans', 1, function ( assert ) { + var $table = $( '<table class="sortable">' + + '<thead><tr><th rowspan="2">n</th><th colspan="2">foo</th><th rowspan="2">baz</th></tr>' + + '<tr><th>foo</th><th>bar</th></tr></thead>' + + '<tbody>' + + '<tr><td>1</td><td>foo</td><td>bar</td><td>baz</td></tr>' + + '<tr><td>2</td><td>foo</td><td>bar</td><td>baz</td></tr>' + + '</tbody></table>' ); + + $table.tablesorter(); + assert.equal( $table.find( 'tr:eq(1) th:eq(1)').prop('headerIndex'), + 2, + 'Incorrect index of sort header' ); + } + ); + + tableTestHTML( + 'Rowspan exploding with colspanned cells', + '<table class="sortable">' + + '<thead><tr><th id="sortme">n</th><th>foo</th><th>bar</th><th>baz</th></tr></thead>' + + '<tbody>' + + '<tr><td>1</td><td>foo</td><td>bar</td><td rowspan="2">baz</td></tr>' + + '<tr><td>2</td><td colspan="2">foobar</td></tr>' + + '</tbody></table>', + [ + [ '1', 'foo', 'bar', 'baz' ], + [ '2', 'foobar', 'baz' ] + ] + ); + + tableTestHTML( + 'Rowspan exploding with colspanned cells (2)', + '<table class="sortable">' + + '<thead><tr><th id="sortme">n</th><th>foo</th><th>bar</th><th>baz</th><th>quux</th></tr></thead>' + + '<tbody>' + + '<tr><td>1</td><td>foo</td><td>bar</td><td rowspan="2">baz</td><td>quux</td></tr>' + + '<tr><td>2</td><td colspan="2">foobar</td><td>quux</td></tr>' + + '</tbody></table>', + [ + [ '1', 'foo', 'bar', 'baz', 'quux' ], + [ '2', 'foobar', 'baz', 'quux' ] + ] + ); + + tableTestHTML( + 'Rowspan exploding with rightmost rows spanning most', + '<table class="sortable">' + + '<thead><tr><th id="sortme">n</th><th>foo</th><th>bar</th></tr></thead>' + + '<tbody>' + + '<tr><td>1</td><td rowspan="2">foo</td><td rowspan="4">bar</td></tr>' + + '<tr><td>2</td></tr>' + + '<tr><td>3</td><td rowspan="2">foo</td></tr>' + + '<tr><td>4</td></tr>' + + '</tbody></table>', + [ + [ '1', 'foo', 'bar' ], + [ '2', 'foo', 'bar' ], + [ '3', 'foo', 'bar' ], + [ '4', 'foo', 'bar' ] + ] + ); + + tableTestHTML( + 'Rowspan exploding with rightmost rows spanning most (2)', + '<table class="sortable">' + + '<thead><tr><th id="sortme">n</th><th>foo</th><th>bar</th><th>baz</th></tr></thead>' + + '<tbody>' + + '<tr><td>1</td><td rowspan="2">foo</td><td rowspan="4">bar</td><td>baz</td></tr>' + + '<tr><td>2</td><td>baz</td></tr>' + + '<tr><td>3</td><td rowspan="2">foo</td><td>baz</td></tr>' + + '<tr><td>4</td><td>baz</td></tr>' + + '</tbody></table>', + [ + [ '1', 'foo', 'bar', 'baz' ], + [ '2', 'foo', 'bar', 'baz' ], + [ '3', 'foo', 'bar', 'baz' ], + [ '4', 'foo', 'bar', 'baz' ] + ] + ); + + tableTestHTML( + 'Rowspan exploding with row-and-colspanned cells', + '<table class="sortable">' + + '<thead><tr><th id="sortme">n</th><th>foo1</th><th>foo2</th><th>bar</th><th>baz</th></tr></thead>' + + '<tbody>' + + '<tr><td>1</td><td rowspan="2">foo1</td><td rowspan="2">foo2</td><td rowspan="4">bar</td><td>baz</td></tr>' + + '<tr><td>2</td><td>baz</td></tr>' + + '<tr><td>3</td><td colspan="2" rowspan="2">foo</td><td>baz</td></tr>' + + '<tr><td>4</td><td>baz</td></tr>' + + '</tbody></table>', + [ + [ '1', 'foo1', 'foo2', 'bar', 'baz' ], + [ '2', 'foo1', 'foo2', 'bar', 'baz' ], + [ '3', 'foo', 'bar', 'baz' ], + [ '4', 'foo', 'bar', 'baz' ] + ] + ); + + tableTestHTML( + 'Rowspan exploding with uneven rowspan layout', + '<table class="sortable">' + + '<thead><tr><th id="sortme">n</th><th>foo1</th><th>foo2</th><th>foo3</th><th>bar</th><th>baz</th></tr></thead>' + + '<tbody>' + + '<tr><td>1</td><td rowspan="2">foo1</td><td rowspan="2">foo2</td><td rowspan="2">foo3</td><td>bar</td><td>baz</td></tr>' + + '<tr><td>2</td><td rowspan="3">bar</td><td>baz</td></tr>' + + '<tr><td>3</td><td rowspan="2">foo1</td><td rowspan="2">foo2</td><td rowspan="2">foo3</td><td>baz</td></tr>' + + '<tr><td>4</td><td>baz</td></tr>' + + '</tbody></table>', + [ + [ '1', 'foo1', 'foo2', 'foo3', 'bar', 'baz' ], + [ '2', 'foo1', 'foo2', 'foo3', 'bar', 'baz' ], + [ '3', 'foo1', 'foo2', 'foo3', 'bar', 'baz' ], + [ '4', 'foo1', 'foo2', 'foo3', 'bar', 'baz' ] + ] + ); + +}( jQuery, mediaWiki ) ); diff --git a/tests/qunit/suites/resources/jquery/jquery.textSelection.test.js b/tests/qunit/suites/resources/jquery/jquery.textSelection.test.js new file mode 100644 index 00000000..56b0fa92 --- /dev/null +++ b/tests/qunit/suites/resources/jquery/jquery.textSelection.test.js @@ -0,0 +1,273 @@ +( function ( $ ) { + + QUnit.module( 'jquery.textSelection', QUnit.newMwEnvironment() ); + + /** + * Test factory for $.fn.textSelection( 'encapsulateText' ) + * + * @param options {object} associative array containing: + * description {string} + * input {string} + * output {string} + * start {int} starting char for selection + * end {int} ending char for selection + * params {object} add'l parameters for $().textSelection( 'encapsulateText' ) + */ + function encapsulateTest( options ) { + var opt = $.extend( { + description: '', + before: {}, + after: {}, + replace: {} + }, options ); + + opt.before = $.extend( { + text: '', + start: 0, + end: 0 + }, opt.before ); + opt.after = $.extend( { + text: '', + selected: null + }, opt.after ); + + QUnit.test( opt.description, function ( assert ) { + var $textarea, start, end, options, text, selected, + tests = 1; + if ( opt.after.selected !== null ) { + tests++; + } + QUnit.expect( tests ); + + $textarea = $( '<textarea>' ); + + $( '#qunit-fixture' ).append( $textarea ); + + $textarea.textSelection( 'setContents', opt.before.text ); + + start = opt.before.start; + end = opt.before.end; + + // Clone opt.replace + options = $.extend( {}, opt.replace ); + options.selectionStart = start; + options.selectionEnd = end; + $textarea.textSelection( 'encapsulateSelection', options ); + + text = $textarea.textSelection( 'getContents' ).replace( /\r\n/g, '\n' ); + + assert.equal( text, opt.after.text, 'Checking full text after encapsulation' ); + + if ( opt.after.selected !== null ) { + selected = $textarea.textSelection( 'getSelection' ); + assert.equal( selected, opt.after.selected, 'Checking selected text after encapsulation.' ); + } + + } ); + } + + var caretSample, + sig = { + pre: '--~~~~' + }, + bold = { + pre: '\'\'\'', + peri: 'Bold text', + post: '\'\'\'' + }, + h2 = { + pre: '== ', + peri: 'Heading 2', + post: ' ==', + regex: /^(\s*)(={1,6})(.*?)\2(\s*)$/, + regexReplace: '$1==$3==$4', + ownline: true + }, + ulist = { + pre: '* ', + peri: 'Bulleted list item', + post: '', + ownline: true, + splitlines: true + }; + + encapsulateTest( { + description: 'Adding sig to end of text', + before: { + text: 'Wikilove dude! ', + start: 15, + end: 15 + }, + after: { + text: 'Wikilove dude! --~~~~', + selected: '' + }, + replace: sig + } ); + + encapsulateTest( { + description: 'Adding bold to empty', + before: { + text: '', + start: 0, + end: 0 + }, + after: { + text: '\'\'\'Bold text\'\'\'', + selected: 'Bold text' // selected because it's the default + }, + replace: bold + } ); + + encapsulateTest( { + description: 'Adding bold to existing text', + before: { + text: 'Now is the time for all good men to come to the aid of their country', + start: 20, + end: 32 + }, + after: { + text: 'Now is the time for \'\'\'all good men\'\'\' to come to the aid of their country', + selected: '' // empty because it's not the default' + }, + replace: bold + } ); + + encapsulateTest( { + description: 'ownline option: adding new h2', + before: { + text: 'Before\nAfter', + start: 7, + end: 7 + }, + after: { + text: 'Before\n== Heading 2 ==\nAfter', + selected: 'Heading 2' + }, + replace: h2 + } ); + + encapsulateTest( { + description: 'ownline option: turn a whole line into new h2', + before: { + text: 'Before\nMy heading\nAfter', + start: 7, + end: 17 + }, + after: { + text: 'Before\n== My heading ==\nAfter', + selected: '' + }, + replace: h2 + } ); + + encapsulateTest( { + description: 'ownline option: turn a partial line into new h2', + before: { + text: 'BeforeMy headingAfter', + start: 6, + end: 16 + }, + after: { + text: 'Before\n== My heading ==\nAfter', + selected: '' + }, + replace: h2 + } ); + + encapsulateTest( { + description: 'splitlines option: no selection, insert new list item', + before: { + text: 'Before\nAfter', + start: 7, + end: 7 + }, + after: { + text: 'Before\n* Bulleted list item\nAfter' + }, + replace: ulist + } ); + + encapsulateTest( { + description: 'splitlines option: single partial line selection, insert new list item', + before: { + text: 'BeforeMy List ItemAfter', + start: 6, + end: 18 + }, + after: { + text: 'Before\n* My List Item\nAfter' + }, + replace: ulist + } ); + + encapsulateTest( { + description: 'splitlines option: multiple lines', + before: { + text: 'Before\nFirst\nSecond\nThird\nAfter', + start: 7, + end: 25 + }, + after: { + text: 'Before\n* First\n* Second\n* Third\nAfter' + }, + replace: ulist + } ); + + function caretTest( options ) { + QUnit.test( options.description, 2, function ( assert ) { + var pos, + $textarea = $( '<textarea>' ).text( options.text ); + + $( '#qunit-fixture' ).append( $textarea ); + + if ( options.mode === 'set' ) { + $textarea.textSelection( 'setSelection', { + start: options.start, + end: options.end + } ); + } + + function among( actual, expected, message ) { + if ( $.isArray( expected ) ) { + assert.ok( $.inArray( actual, expected ) !== -1, message + ' (got ' + actual + '; expected one of ' + expected.join( ', ' ) + ')' ); + } else { + assert.equal( actual, expected, message ); + } + } + + pos = $textarea.textSelection( 'getCaretPosition', { startAndEnd: true } ); + among( pos[0], options.start, 'Caret start should be where we set it.' ); + among( pos[1], options.end, 'Caret end should be where we set it.' ); + } ); + } + + caretSample = 'Some big text that we like to work with. Nothing fancy... you know what I mean?'; + +/* + // @broken: Disabled per bug 34820 + caretTest({ + description: 'getCaretPosition with original/empty selection - bug 31847 with IE 6/7/8', + text: caretSample, + start: [0, caretSample.length], // Opera and Firefox (prior to FF 6.0) default caret to the end of the box (caretSample.length) + end: [0, caretSample.length], // Other browsers default it to the beginning (0), so check both. + mode: 'get' + }); +*/ + + caretTest( { + description: 'set/getCaretPosition with forced empty selection', + text: caretSample, + start: 7, + end: 7, + mode: 'set' + } ); + + caretTest( { + description: 'set/getCaretPosition with small selection', + text: caretSample, + start: 6, + end: 11, + mode: 'set' + } ); +}( jQuery ) ); diff --git a/tests/qunit/suites/resources/mediawiki.api/mediawiki.api.category.test.js b/tests/qunit/suites/resources/mediawiki.api/mediawiki.api.category.test.js new file mode 100644 index 00000000..a0c7daf1 --- /dev/null +++ b/tests/qunit/suites/resources/mediawiki.api/mediawiki.api.category.test.js @@ -0,0 +1,30 @@ +( function ( mw ) { + QUnit.module( 'mediawiki.api.category', QUnit.newMwEnvironment( { + setup: function () { + this.server = this.sandbox.useFakeServer(); + } + } ) ); + + QUnit.test( '.getCategoriesByPrefix()', function ( assert ) { + QUnit.expect( 1 ); + + var api = new mw.Api(); + + api.getCategoriesByPrefix( 'Foo' ).done( function ( matches ) { + assert.deepEqual( + matches, + [ 'Food', 'Fool Supermarine S.6', 'Fools' ] + ); + } ); + + this.server.respond( function ( req ) { + req.respond( 200, { 'Content-Type': 'application/json' }, + '{ "query": { "allpages": [ ' + + '{ "title": "Category:Food" },' + + '{ "title": "Category:Fool Supermarine S.6" },' + + '{ "title": "Category:Fools" }' + + '] } }' + ); + } ); + } ); +}( mediaWiki ) ); diff --git a/tests/qunit/suites/resources/mediawiki.api/mediawiki.api.parse.test.js b/tests/qunit/suites/resources/mediawiki.api/mediawiki.api.parse.test.js new file mode 100644 index 00000000..cd0db7c9 --- /dev/null +++ b/tests/qunit/suites/resources/mediawiki.api/mediawiki.api.parse.test.js @@ -0,0 +1,25 @@ +( function ( mw ) { + QUnit.module( 'mediawiki.api.parse', QUnit.newMwEnvironment( { + setup: function () { + this.server = this.sandbox.useFakeServer(); + } + } ) ); + + QUnit.test( 'Hello world', function ( assert ) { + QUnit.expect( 1 ); + + var api = new mw.Api(); + + api.parse( '\'\'\'Hello world\'\'\'' ).done( function ( html ) { + assert.equal( html, '<p><b>Hello world</b></p>' ); + } ); + + this.server.respondWith( /action=parse.*&text='''Hello\+world'''/, function ( request ) { + request.respond( 200, { 'Content-Type': 'application/json' }, + '{ "parse": { "text": { "*": "<p><b>Hello world</b></p>" } } }' + ); + } ); + + this.server.respond(); + } ); +}( mediaWiki ) ); diff --git a/tests/qunit/suites/resources/mediawiki.api/mediawiki.api.test.js b/tests/qunit/suites/resources/mediawiki.api/mediawiki.api.test.js new file mode 100644 index 00000000..f156c728 --- /dev/null +++ b/tests/qunit/suites/resources/mediawiki.api/mediawiki.api.test.js @@ -0,0 +1,312 @@ +( function ( mw ) { + QUnit.module( 'mediawiki.api', QUnit.newMwEnvironment( { + setup: function () { + this.server = this.sandbox.useFakeServer(); + } + } ) ); + + QUnit.test( 'Basic functionality', function ( assert ) { + QUnit.expect( 2 ); + + var api = new mw.Api(); + + api.get( {} ) + .done( function ( data ) { + assert.deepEqual( data, [], 'If request succeeds without errors, resolve deferred' ); + } ); + + api.post( {} ) + .done( function ( data ) { + assert.deepEqual( data, [], 'Simple POST request' ); + } ); + + this.server.respond( function ( request ) { + request.respond( 200, { 'Content-Type': 'application/json' }, '[]' ); + } ); + } ); + + QUnit.test( 'API error', function ( assert ) { + QUnit.expect( 1 ); + + var api = new mw.Api(); + + api.get( { action: 'doesntexist' } ) + .fail( function ( errorCode ) { + assert.equal( errorCode, 'unknown_action', 'API error should reject the deferred' ); + } ); + + this.server.respond( function ( request ) { + request.respond( 200, { 'Content-Type': 'application/json' }, + '{ "error": { "code": "unknown_action" } }' + ); + } ); + } ); + + QUnit.test( 'FormData support', function ( assert ) { + QUnit.expect( 2 ); + + var api = new mw.Api(); + + api.post( { action: 'test' }, { contentType: 'multipart/form-data' } ); + + this.server.respond( function ( request ) { + if ( window.FormData ) { + assert.ok( !request.url.match( /action=/), 'Request has no query string' ); + assert.ok( request.requestBody instanceof FormData, 'Request uses FormData body' ); + } else { + assert.ok( !request.url.match( /action=test/), 'Request has no query string' ); + assert.equal( request.requestBody, 'action=test&format=json', 'Request uses query string body' ); + } + request.respond( 200, { 'Content-Type': 'application/json' }, '[]' ); + } ); + } ); + + QUnit.test( 'Deprecated callback methods', function ( assert ) { + QUnit.expect( 3 ); + + var api = new mw.Api(); + + this.suppressWarnings(); + + api.get( {}, function () { + assert.ok( true, 'Function argument treated as success callback.' ); + } ); + + api.get( {}, { + ok: function () { + assert.ok( true, '"ok" property treated as success callback.' ); + } + } ); + + api.get( { action: 'doesntexist' }, { + err: function () { + assert.ok( true, '"err" property treated as error callback.' ); + } + } ); + + this.restoreWarnings(); + + this.server.respondWith( /action=query/, function ( request ) { + request.respond( 200, { 'Content-Type': 'application/json' }, '[]' ); + } ); + + this.server.respondWith( /action=doesntexist/, function ( request ) { + request.respond( 200, { 'Content-Type': 'application/json' }, + '{ "error": { "code": "unknown_action" } }' + ); + } ); + + this.server.respond(); + } ); + + QUnit.test( 'getToken( pre-populated )', function ( assert ) { + QUnit.expect( 2 ); + + var api = new mw.Api(); + + // Get editToken for local wiki, this should not make + // a request as it should be retrieved from user.tokens. + api.getToken( 'edit' ) + .done( function ( token ) { + assert.ok( token.length, 'Got a token' ); + } ) + .fail( function ( err ) { + assert.equal( '', err, 'API error' ); + } ); + + assert.equal( this.server.requests.length, 0, 'Requests made' ); + } ); + + QUnit.test( 'getToken()', function ( assert ) { + QUnit.expect( 5 ); + + var test = this, + api = new mw.Api(); + + // Get a token of a type that isn't prepopulated by user.tokens. + // Could use "block" or "delete" here, but those could in theory + // be added to user.tokens, use a fake one instead. + api.getToken( 'testaction' ) + .done( function ( token ) { + assert.ok( token.length, 'Got testaction token' ); + } ) + .fail( function ( err ) { + assert.equal( err, '', 'API error' ); + } ); + api.getToken( 'testaction' ) + .done( function ( token ) { + assert.ok( token.length, 'Got testaction token (cached)' ); + } ) + .fail( function ( err ) { + assert.equal( err, '', 'API error' ); + } ); + + // Don't cache error (bug 65268) + api.getToken( 'testaction2' ) + .fail( function ( err ) { + assert.equal( err, 'bite-me', 'Expected error' ); + } ) + .always( function () { + // Make this request after the first one has finished. + // If we make it simultaneously we still want it to share + // the cache, but as soon as it is fulfilled as error we + // reject it so that the next one tries fresh. + api.getToken( 'testaction2' ) + .done( function ( token ) { + assert.ok( token.length, 'Got testaction2 token (error was not be cached)' ); + } ) + .fail( function ( err ) { + assert.equal( err, '', 'API error' ); + } ); + + assert.equal( test.server.requests.length, 3, 'Requests made' ); + + test.server.requests[2].respond( 200, { 'Content-Type': 'application/json' }, + '{ "tokens": { "testaction2token": "0123abc" } }' + ); + } ); + + this.server.requests[0].respond( 200, { 'Content-Type': 'application/json' }, + '{ "tokens": { "testactiontoken": "0123abc" } }' + ); + + this.server.requests[1].respond( 200, { 'Content-Type': 'application/json' }, + '{ "error": { "code": "bite-me", "info": "Smite me, O Mighty Smiter" } }' + ); + } ); + + QUnit.test( 'postWithToken( tokenType, params )', function ( assert ) { + QUnit.expect( 1 ); + + var api = new mw.Api( { ajax: { url: '/postWithToken/api.php' } } ); + + // - Requests token + // - Performs action=example + api.postWithToken( 'testsimpletoken', { action: 'example', key: 'foo' } ) + .done( function ( data ) { + assert.deepEqual( data, { example: { foo: 'quux' } } ); + } ); + + this.server.requests[0].respond( 200, { 'Content-Type': 'application/json' }, + '{ "tokens": { "testsimpletokentoken": "a-bad-token" } }' + ); + + this.server.requests[1].respond( 200, { 'Content-Type': 'application/json' }, + '{ "example": { "foo": "quux" } }' + ); + } ); + + QUnit.test( 'postWithToken( tokenType, params, ajaxOptions )', function ( assert ) { + QUnit.expect( 3 ); + + var api = new mw.Api(); + + api.postWithToken( + 'edit', + { + action: 'example' + }, + { + headers: { + 'X-Foo': 'Bar' + } + } + ); + + api.postWithToken( + 'edit', + { + action: 'example' + }, + function () { + assert.ok( false, 'This parameter cannot be a callback' ); + } + ) + .always( function ( data ) { + assert.equal( data.example, 'quux' ); + } ); + + assert.equal( this.server.requests.length, 2, 'Request made' ); + assert.equal( this.server.requests[0].requestHeaders['X-Foo'], 'Bar', 'Header sent' ); + + this.server.respond( function ( request ) { + request.respond( 200, { 'Content-Type': 'application/json' }, '{ "example": "quux" }' ); + } ); + } ); + + QUnit.test( 'postWithToken() - badtoken', function ( assert ) { + QUnit.expect( 1 ); + + var api = new mw.Api(); + + // - Request: token + // - Request: action=example -> badtoken error + // - Request: new token + // - Request: action=example + api.postWithToken( 'testbadtoken', { action: 'example', key: 'foo' } ) + .done( function ( data ) { + assert.deepEqual( data, { example: { foo: 'quux' } } ); + } ); + + this.server.requests[0].respond( 200, { 'Content-Type': 'application/json' }, + '{ "tokens": { "testbadtokentoken": "a-bad-token" } }' + ); + + this.server.requests[1].respond( 200, { 'Content-Type': 'application/json' }, + '{ "error": { "code": "badtoken" } }' + ); + + this.server.requests[2].respond( 200, { 'Content-Type': 'application/json' }, + '{ "tokens": { "testbadtokentoken": "a-good-token" } }' + ); + + this.server.requests[3].respond( 200, { 'Content-Type': 'application/json' }, + '{ "example": { "foo": "quux" } }' + ); + + } ); + + QUnit.test( 'postWithToken() - badtoken-cached', function ( assert ) { + QUnit.expect( 2 ); + + var api = new mw.Api(); + + // - Request: token + // - Request: action=example + api.postWithToken( 'testbadtokencache', { action: 'example', key: 'foo' } ) + .done( function ( data ) { + assert.deepEqual( data, { example: { foo: 'quux' } } ); + } ); + + // - Cache: Try previously cached token + // - Request: action=example -> badtoken error + // - Request: new token + // - Request: action=example + api.postWithToken( 'testbadtokencache', { action: 'example', key: 'bar' } ) + .done( function ( data ) { + assert.deepEqual( data, { example: { bar: 'quux' } } ); + } ); + + this.server.requests[0].respond( 200, { 'Content-Type': 'application/json' }, + '{ "tokens": { "testbadtokencachetoken": "a-good-token-once" } }' + ); + + this.server.requests[1].respond( 200, { 'Content-Type': 'application/json' }, + '{ "example": { "foo": "quux" } }' + ); + + this.server.requests[2].respond( 200, { 'Content-Type': 'application/json' }, + '{ "error": { "code": "badtoken" } }' + ); + + this.server.requests[3].respond( 200, { 'Content-Type': 'application/json' }, + '{ "tokens": { "testbadtokencachetoken": "a-good-new-token" } }' + ); + + this.server.requests[4].respond( 200, { 'Content-Type': 'application/json' }, + '{ "example": { "bar": "quux" } }' + ); + + } ); + +}( mediaWiki ) ); diff --git a/tests/qunit/suites/resources/mediawiki.api/mediawiki.api.watch.test.js b/tests/qunit/suites/resources/mediawiki.api/mediawiki.api.watch.test.js new file mode 100644 index 00000000..5965ab7b --- /dev/null +++ b/tests/qunit/suites/resources/mediawiki.api/mediawiki.api.watch.test.js @@ -0,0 +1,46 @@ +( function ( mw ) { + QUnit.module( 'mediawiki.api.watch', QUnit.newMwEnvironment( { + setup: function () { + this.server = this.sandbox.useFakeServer(); + } + } ) ); + + QUnit.test( '.watch()', function ( assert ) { + QUnit.expect( 4 ); + + var api = new mw.Api(); + + // Ensure we don't mistake a single item array for a single item and vice versa. + // The query parameter in request is the same either way (separated by pipe). + api.watch( 'Foo' ).done( function ( item ) { + assert.equal( item.title, 'Foo' ); + } ); + + api.watch( [ 'Foo' ] ).done( function ( items ) { + assert.equal( items[0].title, 'Foo' ); + } ); + + api.watch( [ 'Foo', 'Bar' ] ).done( function ( items ) { + assert.equal( items[0].title, 'Foo' ); + assert.equal( items[1].title, 'Bar' ); + } ); + + // Requests are POST, match requestBody instead of url + this.server.respond( function ( req ) { + if ( /action=watch.*&titles=Foo(&|$)/.test( req.requestBody ) ) { + req.respond( 200, { 'Content-Type': 'application/json' }, + '{ "watch": [ { "title": "Foo", "watched": true, "message": "<b>Added</b>" } ] }' + ); + } + + if ( /action=watch.*&titles=Foo%7CBar/.test( req.requestBody ) ) { + req.respond( 200, { 'Content-Type': 'application/json' }, + '{ "watch": [ ' + + '{ "title": "Foo", "watched": true, "message": "<b>Added</b>" },' + + '{ "title": "Bar", "watched": true, "message": "<b>Added</b>" }' + + '] }' + ); + } + } ); + } ); +}( mediaWiki ) ); diff --git a/tests/qunit/suites/resources/mediawiki.special/mediawiki.special.recentchanges.test.js b/tests/qunit/suites/resources/mediawiki.special/mediawiki.special.recentchanges.test.js new file mode 100644 index 00000000..ee854aef --- /dev/null +++ b/tests/qunit/suites/resources/mediawiki.special/mediawiki.special.recentchanges.test.js @@ -0,0 +1,63 @@ +( function ( mw, $ ) { + QUnit.module( 'mediawiki.special.recentchanges', QUnit.newMwEnvironment() ); + + // TODO: verify checkboxes == [ 'nsassociated', 'nsinvert' ] + + QUnit.test( '"all" namespace disable checkboxes', 8, function ( assert ) { + var selectHtml, $env, $options; + + // from Special:Recentchanges + selectHtml = '<select id="namespace" name="namespace" class="namespaceselector">' + + '<option value="" selected="selected">all</option>' + + '<option value="0">(Main)</option>' + + '<option value="1">Talk</option>' + + '<option value="2">User</option>' + + '<option value="3">User talk</option>' + + '<option value="4">ProjectName</option>' + + '<option value="5">ProjectName talk</option>' + + '</select>' + + '<input name="invert" type="checkbox" value="1" id="nsinvert" title="no title" />' + + '<label for="nsinvert" title="no title">Invert selection</label>' + + '<input name="associated" type="checkbox" value="1" id="nsassociated" title="no title" />' + + '<label for="nsassociated" title="no title">Associated namespace</label>' + + '<input type="submit" value="Go" />' + + '<input type="hidden" value="Special:RecentChanges" name="title" />'; + + $env = $( '<div>' ).html( selectHtml ).appendTo( 'body' ); + + // TODO abstract the double strictEquals + + // At first checkboxes are enabled + assert.strictEqual( $( '#nsinvert' ).prop( 'disabled' ), false ); + assert.strictEqual( $( '#nsassociated' ).prop( 'disabled' ), false ); + + // Initiate the recentchanges module + mw.special.recentchanges.init(); + + // By default + assert.strictEqual( $( '#nsinvert' ).prop( 'disabled' ), true ); + assert.strictEqual( $( '#nsassociated' ).prop( 'disabled' ), true ); + + // select second option... + $options = $( '#namespace' ).find( 'option' ); + $options.eq( 0 ).removeProp( 'selected' ); + $options.eq( 1 ).prop( 'selected', true ); + $( '#namespace' ).change(); + + // ... and checkboxes should be enabled again + assert.strictEqual( $( '#nsinvert' ).prop( 'disabled' ), false ); + assert.strictEqual( $( '#nsassociated' ).prop( 'disabled' ), false ); + + // select first option ( 'all' namespace)... + $options.eq( 1 ).removeProp( 'selected' ); + $options.eq( 0 ).prop( 'selected', true ); + $( '#namespace' ).change(); + + // ... and checkboxes should now be disabled + assert.strictEqual( $( '#nsinvert' ).prop( 'disabled' ), true ); + assert.strictEqual( $( '#nsassociated' ).prop( 'disabled' ), true ); + + // DOM cleanup + $env.remove(); + } ); +}( mediaWiki, jQuery ) ); diff --git a/tests/qunit/suites/resources/mediawiki/mediawiki.Title.test.js b/tests/qunit/suites/resources/mediawiki/mediawiki.Title.test.js new file mode 100644 index 00000000..7ab309aa --- /dev/null +++ b/tests/qunit/suites/resources/mediawiki/mediawiki.Title.test.js @@ -0,0 +1,650 @@ +/*jshint -W024 */ +( function ( mw, $ ) { + var repeat = function ( input, multiplier ) { + return new Array( multiplier + 1 ).join( input ); + }, + cases = { + // See also TitleTest.php#testSecureAndSplit + valid: [ + 'Sandbox', + 'A "B"', + 'A \'B\'', + '.com', + '~', + '"', + '\'', + 'Talk:Sandbox', + 'Talk:Foo:Sandbox', + 'File:Example.svg', + 'File_talk:Example.svg', + 'Foo/.../Sandbox', + 'Sandbox/...', + 'A~~', + ':A', + // Length is 256 total, but only title part matters + 'Category:' + repeat( 'x', 248 ), + repeat( 'x', 252 ) + ], + invalid: [ + '', + ':', + '__ __', + ' __ ', + // Bad characters forbidden regardless of wgLegalTitleChars + 'A [ B', + 'A ] B', + 'A { B', + 'A } B', + 'A < B', + 'A > B', + 'A | B', + // URL encoding + 'A%20B', + 'A%23B', + 'A%2523B', + // XML/HTML character entity references + // Note: The ones with # are commented out as those are interpreted as fragment and + // as such end up being valid. + 'A é B', + //'A é B', + //'A é B', + // Subject of NS_TALK does not roundtrip to NS_MAIN + 'Talk:File:Example.svg', + // Directory navigation + '.', + '..', + './Sandbox', + '../Sandbox', + 'Foo/./Sandbox', + 'Foo/../Sandbox', + 'Sandbox/.', + 'Sandbox/..', + // Tilde + 'A ~~~ Name', + 'A ~~~~ Signature', + 'A ~~~~~ Timestamp', + repeat( 'x', 256 ), + // Extension separation is a js invention, for length + // purposes it is part of the title + repeat( 'x', 252 ) + '.json', + // Namespace prefix without actual title + 'Talk:', + 'Category: ', + 'Category: #bar' + ] + }; + + QUnit.module( 'mediawiki.Title', QUnit.newMwEnvironment( { + // mw.Title relies on these three config vars + // Restore them after each test run + config: { + wgFormattedNamespaces: { + '-2': 'Media', + '-1': 'Special', + 0: '', + 1: 'Talk', + 2: 'User', + 3: 'User talk', + 4: 'Wikipedia', + 5: 'Wikipedia talk', + 6: 'File', + 7: 'File talk', + 8: 'MediaWiki', + 9: 'MediaWiki talk', + 10: 'Template', + 11: 'Template talk', + 12: 'Help', + 13: 'Help talk', + 14: 'Category', + 15: 'Category talk', + // testing custom / localized namespace + 100: 'Penguins' + }, + wgNamespaceIds: { + 'media': -2, + 'special': -1, + '': 0, + 'talk': 1, + 'user': 2, + 'user_talk': 3, + 'wikipedia': 4, + 'wikipedia_talk': 5, + 'file': 6, + 'file_talk': 7, + 'mediawiki': 8, + 'mediawiki_talk': 9, + 'template': 10, + 'template_talk': 11, + 'help': 12, + 'help_talk': 13, + 'category': 14, + 'category_talk': 15, + 'image': 6, + 'image_talk': 7, + 'project': 4, + 'project_talk': 5, + // Testing custom namespaces and aliases + 'penguins': 100, + 'antarctic_waterfowl': 100 + }, + wgCaseSensitiveNamespaces: [] + } + } ) ); + + QUnit.test( 'constructor', cases.invalid.length, function ( assert ) { + var i, title; + for ( i = 0; i < cases.valid.length; i++ ) { + title = new mw.Title( cases.valid[i] ); + } + for ( i = 0; i < cases.invalid.length; i++ ) { + /*jshint loopfunc:true */ + title = cases.invalid[i]; + assert.throws( function () { + return new mw.Title( title ); + }, cases.invalid[i] ); + } + } ); + + QUnit.test( 'newFromText', cases.valid.length + cases.invalid.length, function ( assert ) { + var i; + for ( i = 0; i < cases.valid.length; i++ ) { + assert.equal( + $.type( mw.Title.newFromText( cases.valid[i] ) ), + 'object', + cases.valid[i] + ); + } + for ( i = 0; i < cases.invalid.length; i++ ) { + assert.equal( + $.type( mw.Title.newFromText( cases.invalid[i] ) ), + 'null', + cases.invalid[i] + ); + } + } ); + + QUnit.test( 'Basic parsing', 12, function ( assert ) { + var title; + title = new mw.Title( 'File:Foo_bar.JPG' ); + + assert.equal( title.getNamespaceId(), 6 ); + assert.equal( title.getNamespacePrefix(), 'File:' ); + assert.equal( title.getName(), 'Foo_bar' ); + assert.equal( title.getNameText(), 'Foo bar' ); + assert.equal( title.getExtension(), 'JPG' ); + assert.equal( title.getDotExtension(), '.JPG' ); + assert.equal( title.getMain(), 'Foo_bar.JPG' ); + assert.equal( title.getMainText(), 'Foo bar.JPG' ); + assert.equal( title.getPrefixedDb(), 'File:Foo_bar.JPG' ); + assert.equal( title.getPrefixedText(), 'File:Foo bar.JPG' ); + + title = new mw.Title( 'Foo#bar' ); + assert.equal( title.getPrefixedText(), 'Foo' ); + assert.equal( title.getFragment(), 'bar' ); + } ); + + QUnit.test( 'Transformation', 11, function ( assert ) { + var title; + + title = new mw.Title( 'File:quux pif.jpg' ); + assert.equal( title.getNameText(), 'Quux pif', 'First character of title' ); + + title = new mw.Title( 'File:Glarg_foo_glang.jpg' ); + assert.equal( title.getNameText(), 'Glarg foo glang', 'Underscores' ); + + title = new mw.Title( 'User:ABC.DEF' ); + assert.equal( title.toText(), 'User:ABC.DEF', 'Round trip text' ); + assert.equal( title.getNamespaceId(), 2, 'Parse canonical namespace prefix' ); + + title = new mw.Title( 'Image:quux pix.jpg' ); + assert.equal( title.getNamespacePrefix(), 'File:', 'Transform alias to canonical namespace' ); + + title = new mw.Title( 'uSEr:hAshAr' ); + assert.equal( title.toText(), 'User:HAshAr' ); + assert.equal( title.getNamespaceId(), 2, 'Case-insensitive namespace prefix' ); + + // Don't ask why, it's the way the backend works. One space is kept of each set. + title = new mw.Title( 'Foo __ \t __ bar' ); + assert.equal( title.getMain(), 'Foo_bar', 'Merge multiple types of whitespace/underscores into a single underscore' ); + + // Regression test: Previously it would only detect an extension if there is no space after it + title = new mw.Title( 'Example.js ' ); + assert.equal( title.getExtension(), 'js', 'Space after an extension is stripped' ); + + title = new mw.Title( 'Example#foo' ); + assert.equal( title.getFragment(), 'foo', 'Fragment' ); + + title = new mw.Title( 'Example#_foo_bar baz_' ); + assert.equal( title.getFragment(), ' foo bar baz', 'Fragment' ); + } ); + + QUnit.test( 'Namespace detection and conversion', 10, function ( assert ) { + var title; + + title = new mw.Title( 'File:User:Example' ); + assert.equal( title.getNamespaceId(), 6, 'Titles can contain namespace prefixes, which are otherwise ignored' ); + + title = new mw.Title( 'Example', 6 ); + assert.equal( title.getNamespaceId(), 6, 'Default namespace passed is used' ); + + title = new mw.Title( 'User:Example', 6 ); + assert.equal( title.getNamespaceId(), 2, 'Included namespace prefix overrides the given default' ); + + title = new mw.Title( ':Example', 6 ); + assert.equal( title.getNamespaceId(), 0, 'Colon forces main namespace' ); + + title = new mw.Title( 'something.PDF', 6 ); + assert.equal( title.toString(), 'File:Something.PDF' ); + + title = new mw.Title( 'NeilK', 3 ); + assert.equal( title.toString(), 'User_talk:NeilK' ); + assert.equal( title.toText(), 'User talk:NeilK' ); + + title = new mw.Title( 'Frobisher', 100 ); + assert.equal( title.toString(), 'Penguins:Frobisher' ); + + title = new mw.Title( 'antarctic_waterfowl:flightless_yet_cute.jpg' ); + assert.equal( title.toString(), 'Penguins:Flightless_yet_cute.jpg' ); + + title = new mw.Title( 'Penguins:flightless_yet_cute.jpg' ); + assert.equal( title.toString(), 'Penguins:Flightless_yet_cute.jpg' ); + } ); + + QUnit.test( 'Throw error on invalid title', 1, function ( assert ) { + assert.throws( function () { + return new mw.Title( '' ); + }, 'Throw error on empty string' ); + } ); + + QUnit.test( 'Case-sensivity', 3, function ( assert ) { + var title; + + // Default config + mw.config.set( 'wgCaseSensitiveNamespaces', [] ); + + title = new mw.Title( 'article' ); + assert.equal( title.toString(), 'Article', 'Default config: No sensitive namespaces by default. First-letter becomes uppercase' ); + + // $wgCapitalLinks = false; + mw.config.set( 'wgCaseSensitiveNamespaces', [0, -2, 1, 4, 5, 6, 7, 10, 11, 12, 13, 14, 15] ); + + title = new mw.Title( 'article' ); + assert.equal( title.toString(), 'article', '$wgCapitalLinks=false: Article namespace is sensitive, first-letter case stays lowercase' ); + + title = new mw.Title( 'john', 2 ); + assert.equal( title.toString(), 'User:John', '$wgCapitalLinks=false: User namespace is insensitive, first-letter becomes uppercase' ); + } ); + + QUnit.test( 'toString / toText', 2, function ( assert ) { + var title = new mw.Title( 'Some random page' ); + + assert.equal( title.toString(), title.getPrefixedDb() ); + assert.equal( title.toText(), title.getPrefixedText() ); + } ); + + QUnit.test( 'getExtension', 7, function ( assert ) { + function extTest( pagename, ext, description ) { + var title = new mw.Title( pagename ); + assert.equal( title.getExtension(), ext, description || pagename ); + } + + extTest( 'MediaWiki:Vector.js', 'js' ); + extTest( 'User:Example/common.css', 'css' ); + extTest( 'File:Example.longextension', 'longextension', 'Extension parsing not limited (bug 36151)' ); + extTest( 'Example/information.json', 'json', 'Extension parsing not restricted from any namespace' ); + extTest( 'Foo.', null, 'Trailing dot is not an extension' ); + extTest( 'Foo..', null, 'Trailing dots are not an extension' ); + extTest( 'Foo.a.', null, 'Page name with dots and ending in a dot does not have an extension' ); + + // @broken: Throws an exception + // extTest( '.NET', null, 'Leading dot is (or is not?) an extension' ); + } ); + + QUnit.test( 'exists', 3, function ( assert ) { + var title; + + // Empty registry, checks default to null + + title = new mw.Title( 'Some random page', 4 ); + assert.strictEqual( title.exists(), null, 'Return null with empty existance registry' ); + + // Basic registry, checks default to boolean + mw.Title.exist.set( ['Does_exist', 'User_talk:NeilK', 'Wikipedia:Sandbox_rules'], true ); + mw.Title.exist.set( ['Does_not_exist', 'User:John', 'Foobar'], false ); + + title = new mw.Title( 'Project:Sandbox rules' ); + assert.assertTrue( title.exists(), 'Return true for page titles marked as existing' ); + title = new mw.Title( 'Foobar' ); + assert.assertFalse( title.exists(), 'Return false for page titles marked as nonexistent' ); + + } ); + + QUnit.test( 'getUrl', 3, function ( assert ) { + var title; + + // Config + mw.config.set( 'wgArticlePath', '/wiki/$1' ); + + title = new mw.Title( 'Foobar' ); + assert.equal( title.getUrl(), '/wiki/Foobar', 'Basic functionality, getUrl uses mw.util.getUrl' ); + assert.equal( title.getUrl({ action: 'edit' }), '/wiki/Foobar?action=edit', 'Basic functionality, \'params\' parameter' ); + + title = new mw.Title( 'John Doe', 3 ); + assert.equal( title.getUrl(), '/wiki/User_talk:John_Doe', 'Escaping in title and namespace for urls' ); + } ); + + QUnit.test( 'newFromImg', 40, function ( assert ) { + var title, i, thisCase, prefix, + cases = [ + { + 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', + typeOfUrl: 'Hashed thumb with shortened path', + nameText: '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)', + prefixedText: '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' + }, + { + url: '/wiki/images/thumb/9/91/Anticlockwise_heliotrope%27s.jpg/99px-Anticlockwise_heliotrope%27s.jpg', + typeOfUrl: 'Normal hashed directory thumbnail', + nameText: 'Anticlockwise heliotrope\'s', + prefixedText: 'File:Anticlockwise heliotrope\'s.jpg' + }, + + { + url: '/wiki/images/thumb/8/80/Wikipedia-logo-v2.svg/langde-150px-Wikipedia-logo-v2.svg.png', + typeOfUrl: 'Normal hashed directory thumbnail with complex thumbnail parameters', + nameText: 'Wikipedia-logo-v2', + prefixedText: 'File:Wikipedia-logo-v2.svg' + }, + + { + url: '//upload.wikimedia.org/wikipedia/commons/thumb/8/80/Wikipedia-logo-v2.svg/150px-Wikipedia-logo-v2.svg.png', + typeOfUrl: 'Commons thumbnail', + nameText: 'Wikipedia-logo-v2', + prefixedText: 'File:Wikipedia-logo-v2.svg' + }, + + { + url: '/wiki/images/9/91/Anticlockwise_heliotrope%27s.jpg', + typeOfUrl: 'Full image', + nameText: 'Anticlockwise heliotrope\'s', + prefixedText: 'File:Anticlockwise heliotrope\'s.jpg' + }, + + { + url: 'http://localhost/thumb.php?f=Stuffless_Figaro%27s.jpg&width=180', + typeOfUrl: 'thumb.php-based thumbnail', + nameText: 'Stuffless Figaro\'s', + prefixedText: 'File:Stuffless Figaro\'s.jpg' + }, + + { + url: '/wikipedia/commons/thumb/Wikipedia-logo-v2.svg/150px-Wikipedia-logo-v2.svg.png', + typeOfUrl: 'Commons unhashed thumbnail', + nameText: 'Wikipedia-logo-v2', + prefixedText: 'File:Wikipedia-logo-v2.svg' + }, + + { + url: '/wikipedia/commons/thumb/Wikipedia-logo-v2.svg/langde-150px-Wikipedia-logo-v2.svg.png', + typeOfUrl: 'Commons unhashed thumbnail with complex thumbnail parameters', + nameText: 'Wikipedia-logo-v2', + prefixedText: 'File:Wikipedia-logo-v2.svg' + }, + + { + url: '/wiki/images/Anticlockwise_heliotrope%27s.jpg', + typeOfUrl: 'Unhashed local file', + nameText: 'Anticlockwise heliotrope\'s', + prefixedText: 'File:Anticlockwise heliotrope\'s.jpg' + }, + + { + url: '', + typeOfUrl: 'Empty string' + }, + + { + url: 'foo', + typeOfUrl: 'String with only alphabet characters' + }, + + { + url: 'foobar.foobar', + typeOfUrl: 'Not a file path' + }, + + { + url: '/a/a0/blah blah blah', + typeOfUrl: 'Space characters' + } + ]; + + for ( i = 0; i < cases.length; i++ ) { + thisCase = cases[i]; + title = mw.Title.newFromImg( { src: thisCase.url } ); + + if ( thisCase.nameText !== undefined ) { + prefix = '[' + thisCase.typeOfUrl + ' URL' + '] '; + + assert.notStrictEqual( title, null, prefix + 'Parses successfully' ); + assert.equal( title.getNameText(), thisCase.nameText, prefix + 'Filename matches original' ); + assert.equal( title.getPrefixedText(), thisCase.prefixedText, prefix + 'File page title matches original' ); + assert.equal( title.getNamespaceId(), 6, prefix + 'Namespace ID matches File namespace' ); + } else { + assert.strictEqual( title, null, thisCase.typeOfUrl + ', should not produce an mw.Title object' ); + } + } + } ); + + QUnit.test( 'getRelativeText', 5, function ( assert ) { + var cases = [ + { + text: 'asd', + relativeTo: 123, + expectedResult: ':Asd' + }, + { + text: 'dfg', + relativeTo: 0, + expectedResult: 'Dfg' + }, + { + text: 'Template:Ghj', + relativeTo: 0, + expectedResult: 'Template:Ghj' + }, + { + text: 'Template:1', + relativeTo: 10, + expectedResult: '1' + }, + { + text: 'User:Hi', + relativeTo: 10, + expectedResult: 'User:Hi' + } + ], i, thisCase, title; + + for ( i = 0; i < cases.length; i++ ) { + thisCase = cases[i]; + + title = mw.Title.newFromText( thisCase.text ); + assert.equal( title.getRelativeText( thisCase.relativeTo ), thisCase.expectedResult ); + } + } ); + + QUnit.test( 'newFromUserInput', 8, function ( assert ) { + var title, i, thisCase, prefix, + cases = [ + { + title: 'DCS0001557854455.JPG', + defaultNamespace: 0, + options: { + fileExtension: 'PNG' + }, + expected: 'DCS0001557854455.JPG', + description: 'Title in normal namespace without anything invalid but with "file extension"' + }, + { + title: 'MediaWiki:Msg-awesome', + defaultNamespace: undefined, + expected: 'MediaWiki:Msg-awesome', + description: 'Full title (page in MediaWiki namespace) supplied as string' + }, + { + title: 'The/Mw/Sound.flac', + defaultNamespace: -2, + expected: 'Media:The-Mw-Sound.flac', + description: 'Page in Media-namespace without explicit options' + }, + { + title: 'File:The/Mw/Sound.kml', + defaultNamespace: 6, + options: { + forUploading: false + }, + expected: 'File:The/Mw/Sound.kml', + description: 'Page in File-namespace without explicit options' + } + ]; + + for ( i = 0; i < cases.length; i++ ) { + thisCase = cases[i]; + title = mw.Title.newFromUserInput( thisCase.title, thisCase.defaultNamespace, thisCase.options ); + + if ( thisCase.expected !== undefined ) { + prefix = '[' + thisCase.description + '] '; + + assert.notStrictEqual( title, null, prefix + 'Parses successfully' ); + assert.equal( title.toText(), thisCase.expected, prefix + 'Title as expected' ); + } else { + assert.strictEqual( title, null, thisCase.description + ', should not produce an mw.Title object' ); + } + } + } ); + + QUnit.test( 'newFromFileName', 62, function ( assert ) { + var title, i, thisCase, prefix, + cases = [ + { + fileName: 'DCS0001557854455.JPG', + typeOfName: 'Standard camera output', + nameText: 'DCS0001557854455', + prefixedText: 'File:DCS0001557854455.JPG', + extensionDesired: 'jpg' + }, + { + fileName: 'File:Sample.png', + typeOfName: 'Carrying namespace', + nameText: 'File-Sample', + prefixedText: 'File:File-Sample.png' + }, + { + fileName: 'Treppe 2222 Test upload.jpg', + typeOfName: 'File name with spaces in it and lower case file extension', + nameText: 'Treppe 2222 Test upload', + prefixedText: 'File:Treppe 2222 Test upload.jpg', + extensionDesired: 'JPG' + }, + { + fileName: 'I contain a \ttab.jpg', + typeOfName: 'Name containing a tab character', + nameText: 'I contain a tab', + prefixedText: 'File:I contain a tab.jpg' + }, + { + fileName: 'I_contain multiple__ ___ _underscores.jpg', + typeOfName: 'Name containing multiple underscores', + nameText: 'I contain multiple underscores', + prefixedText: 'File:I contain multiple underscores.jpg' + }, + { + fileName: 'I like ~~~~~~~~es.jpg', + typeOfName: 'Name containing more than three consecutive tilde characters', + nameText: 'I like ~~es', + prefixedText: 'File:I like ~~es.jpg' + }, + { + fileName: 'BI\u200EDI.jpg', + typeOfName: 'Name containing BIDI overrides', + nameText: 'BIDI', + prefixedText: 'File:BIDI.jpg' + }, + { + fileName: '100%ab progress.jpg', + typeOfName: 'File name with URL encoding', + nameText: '100% ab progress', + prefixedText: 'File:100% ab progress.jpg' + }, + { + fileName: '<([>]):/#.jpg', + typeOfName: 'File name with characters not permitted in titles that are replaced', + nameText: '((()))---', + prefixedText: 'File:((()))---.jpg' + }, + { + fileName: 'spaces\u0009\u2000\u200A\u200Bx.djvu', + typeOfName: 'File name with different kind of spaces', + nameText: 'Spaces \u200Bx', + prefixedText: 'File:Spaces \u200Bx.djvu' + }, + { + fileName: 'dot.dot.dot.dot.dotdot', + typeOfName: 'File name with a lot of dots', + nameText: 'Dot.dot.dot.dot', + prefixedText: 'File:Dot.dot.dot.dot.dotdot' + }, + { + fileName: 'dot. dot ._dot', + typeOfName: 'File name with multiple dots and spaces', + nameText: 'Dot. dot', + prefixedText: 'File:Dot. dot. dot' + }, + { + fileName: 'dot. dot ._dot', + typeOfName: 'File name with different file extension desired', + nameText: 'Dot. dot . dot', + prefixedText: 'File:Dot. dot . dot.png', + extensionDesired: 'png' + }, + { + fileName: 'fileWOExt', + typeOfName: 'File W/O extension with extension desired', + nameText: 'FileWOExt', + prefixedText: 'File:FileWOExt.png', + extensionDesired: 'png' + }, + { + fileName: '𠜎𠜱𠝹𠱓𠱸𠲖𠳏𠳕𠴕𠵼𠵿𠸎𠸏𠹷𠺝𠺢𠻗𠻹𠻺𠼭𠼮𠽌𠾴𠾼𠿪𡁜𡁯𡁵𡁶𡁻𡃁𡃉𡇙𢃇𢞵𢫕𢭃𢯊𢱑𢱕𢳂𠻹𠻺𠼭𠼮𠽌𠾴𠾼𠿪𡁜𡁯𡁵𡁶𡁻𡃁𡃉𡇙𢃇𢞵𢫕𢭃𢯊𢱑𢱕𢳂.png', + typeOfName: 'File name longer than 240 bytes', + nameText: '𠜎𠜱𠝹𠱓𠱸𠲖𠳏𠳕𠴕𠵼𠵿𠸎𠸏𠹷𠺝𠺢𠻗𠻹𠻺𠼭𠼮𠽌𠾴𠾼𠿪𡁜𡁯𡁵𡁶𡁻𡃁𡃉𡇙𢃇𢞵𢫕𢭃𢯊𢱑𢱕𢳂𠻹𠻺𠼭𠼮𠽌𠾴𠾼𠿪𡁜𡁯𡁵𡁶𡁻𡃁𡃉𡇙𢃇𢞵', + prefixedText: 'File:𠜎𠜱𠝹𠱓𠱸𠲖𠳏𠳕𠴕𠵼𠵿𠸎𠸏𠹷𠺝𠺢𠻗𠻹𠻺𠼭𠼮𠽌𠾴𠾼𠿪𡁜𡁯𡁵𡁶𡁻𡃁𡃉𡇙𢃇𢞵𢫕𢭃𢯊𢱑𢱕𢳂𠻹𠻺𠼭𠼮𠽌𠾴𠾼𠿪𡁜𡁯𡁵𡁶𡁻𡃁𡃉𡇙𢃇𢞵.png' + }, + { + fileName: '', + typeOfName: 'Empty string' + }, + { + fileName: 'foo', + typeOfName: 'String with only alphabet characters' + } + ]; + + for ( i = 0; i < cases.length; i++ ) { + thisCase = cases[i]; + title = mw.Title.newFromFileName( thisCase.fileName, thisCase.extensionDesired ); + + if ( thisCase.nameText !== undefined ) { + prefix = '[' + thisCase.typeOfName + '] '; + + assert.notStrictEqual( title, null, prefix + 'Parses successfully' ); + assert.equal( title.getNameText(), thisCase.nameText, prefix + 'Filename matches original' ); + assert.equal( title.getPrefixedText(), thisCase.prefixedText, prefix + 'File page title matches original' ); + assert.equal( title.getNamespaceId(), 6, prefix + 'Namespace ID matches File namespace' ); + } else { + assert.strictEqual( title, null, thisCase.typeOfName + ', should not produce an mw.Title object' ); + } + } + } ); + +}( mediaWiki, jQuery ) ); diff --git a/tests/qunit/suites/resources/mediawiki/mediawiki.Uri.test.js b/tests/qunit/suites/resources/mediawiki/mediawiki.Uri.test.js new file mode 100644 index 00000000..7a58d38d --- /dev/null +++ b/tests/qunit/suites/resources/mediawiki/mediawiki.Uri.test.js @@ -0,0 +1,434 @@ +/*jshint -W024 */ +( function ( mw, $ ) { + QUnit.module( 'mediawiki.Uri', QUnit.newMwEnvironment( { + setup: function () { + this.mwUriOrg = mw.Uri; + mw.Uri = mw.UriRelative( 'http://example.org/w/index.php' ); + }, + teardown: function () { + mw.Uri = this.mwUriOrg; + delete this.mwUriOrg; + } + } ) ); + + $.each( [true, false], function ( i, strictMode ) { + QUnit.test( 'Basic construction and properties (' + ( strictMode ? '' : 'non-' ) + 'strict mode)', 2, function ( assert ) { + var uriString, uri; + uriString = 'http://www.ietf.org/rfc/rfc2396.txt'; + uri = new mw.Uri( uriString, { + strictMode: strictMode + } ); + + assert.deepEqual( + { + protocol: uri.protocol, + host: uri.host, + port: uri.port, + path: uri.path, + query: uri.query, + fragment: uri.fragment + }, { + protocol: 'http', + host: 'www.ietf.org', + port: undefined, + path: '/rfc/rfc2396.txt', + query: {}, + fragment: undefined + }, + 'basic object properties' + ); + + assert.deepEqual( + { + userInfo: uri.getUserInfo(), + authority: uri.getAuthority(), + hostPort: uri.getHostPort(), + queryString: uri.getQueryString(), + relativePath: uri.getRelativePath(), + toString: uri.toString() + }, + { + userInfo: '', + authority: 'www.ietf.org', + hostPort: 'www.ietf.org', + queryString: '', + relativePath: '/rfc/rfc2396.txt', + toString: uriString + }, + 'construct composite components of URI on request' + ); + } ); + } ); + + QUnit.test( 'Constructor( String[, Object ] )', 10, function ( assert ) { + var uri; + + uri = new mw.Uri( 'http://www.example.com/dir/?m=foo&m=bar&n=1', { + overrideKeys: true + } ); + + // Strict comparison to assert that numerical values stay strings + assert.strictEqual( uri.query.n, '1', 'Simple parameter with overrideKeys:true' ); + assert.strictEqual( uri.query.m, 'bar', 'Last key overrides earlier keys with overrideKeys:true' ); + + uri = new mw.Uri( 'http://www.example.com/dir/?m=foo&m=bar&n=1', { + overrideKeys: false + } ); + + assert.strictEqual( uri.query.n, '1', 'Simple parameter with overrideKeys:false' ); + assert.strictEqual( uri.query.m[0], 'foo', 'Order of multi-value parameters with overrideKeys:true' ); + assert.strictEqual( uri.query.m[1], 'bar', 'Order of multi-value parameters with overrideKeys:true' ); + assert.strictEqual( uri.query.m.length, 2, 'Number of mult-value field is correct' ); + + uri = new mw.Uri( 'ftp://usr:pwd@192.0.2.16/' ); + + assert.deepEqual( + { + protocol: uri.protocol, + user: uri.user, + password: uri.password, + host: uri.host, + port: uri.port, + path: uri.path, + query: uri.query, + fragment: uri.fragment + }, + { + protocol: 'ftp', + user: 'usr', + password: 'pwd', + host: '192.0.2.16', + port: undefined, + path: '/', + query: {}, + fragment: undefined + }, + 'Parse an ftp URI correctly with user and password' + ); + + assert.throws( + function () { + return new mw.Uri( 'glaswegian penguins' ); + }, + function ( e ) { + return e.message === 'Bad constructor arguments'; + }, + 'throw error on non-URI as argument to constructor' + ); + + assert.throws( + function () { + return new mw.Uri( 'example.com/bar/baz', { + strictMode: true + } ); + }, + function ( e ) { + return e.message === 'Bad constructor arguments'; + }, + 'throw error on URI without protocol or // or leading / in strict mode' + ); + + uri = new mw.Uri( 'example.com/bar/baz', { + strictMode: false + } ); + assert.equal( uri.toString(), 'http://example.com/bar/baz', 'normalize URI without protocol or // in loose mode' ); + } ); + + QUnit.test( 'Constructor( Object )', 3, function ( assert ) { + var uri = new mw.Uri( { + protocol: 'http', + host: 'www.foo.local', + path: '/this' + } ); + assert.equal( uri.toString(), 'http://www.foo.local/this', 'Basic properties' ); + + uri = new mw.Uri( { + protocol: 'http', + host: 'www.foo.local', + path: '/this', + query: { hi: 'there' }, + fragment: 'blah' + } ); + assert.equal( uri.toString(), 'http://www.foo.local/this?hi=there#blah', 'More complex properties' ); + + assert.throws( + function () { + return new mw.Uri( { + protocol: 'http', + host: 'www.foo.local' + } ); + }, + function ( e ) { + return e.message === 'Bad constructor arguments'; + }, + 'Construction failed when missing required properties' + ); + } ); + + QUnit.test( 'Constructor( empty )', 4, function ( assert ) { + var testuri, MyUri, uri; + + testuri = 'http://example.org/w/index.php'; + MyUri = mw.UriRelative( testuri ); + + uri = new MyUri(); + assert.equal( uri.toString(), testuri, 'no arguments' ); + + uri = new MyUri( undefined ); + assert.equal( uri.toString(), testuri, 'undefined' ); + + uri = new MyUri( null ); + assert.equal( uri.toString(), testuri, 'null' ); + + uri = new MyUri( '' ); + assert.equal( uri.toString(), testuri, 'empty string' ); + } ); + + QUnit.test( 'Properties', 8, function ( assert ) { + var uriBase, uri; + + uriBase = new mw.Uri( 'http://en.wiki.local/w/api.php' ); + + uri = uriBase.clone(); + uri.fragment = 'frag'; + assert.equal( uri.toString(), 'http://en.wiki.local/w/api.php#frag', 'add a fragment' ); + + uri = uriBase.clone(); + uri.host = 'fr.wiki.local'; + uri.port = '8080'; + assert.equal( uri.toString(), 'http://fr.wiki.local:8080/w/api.php', 'change host and port' ); + + uri = uriBase.clone(); + uri.query.foo = 'bar'; + assert.equal( uri.toString(), 'http://en.wiki.local/w/api.php?foo=bar', 'add query arguments' ); + + delete uri.query.foo; + assert.equal( uri.toString(), 'http://en.wiki.local/w/api.php', 'delete query arguments' ); + + uri = uriBase.clone(); + uri.query.foo = 'bar'; + assert.equal( uri.toString(), 'http://en.wiki.local/w/api.php?foo=bar', 'extend query arguments' ); + uri.extend( { + foo: 'quux', + pif: 'paf' + } ); + assert.ok( uri.toString().indexOf( 'foo=quux' ) >= 0, 'extend query arguments' ); + assert.ok( uri.toString().indexOf( 'foo=bar' ) === -1, 'extend query arguments' ); + assert.ok( uri.toString().indexOf( 'pif=paf' ) >= 0, 'extend query arguments' ); + } ); + + QUnit.test( '.getQueryString()', 2, function ( assert ) { + var uri = new mw.Uri( 'http://search.example.com/?q=uri' ); + + assert.deepEqual( + { + protocol: uri.protocol, + host: uri.host, + port: uri.port, + path: uri.path, + query: uri.query, + fragment: uri.fragment, + queryString: uri.getQueryString() + }, + { + protocol: 'http', + host: 'search.example.com', + port: undefined, + path: '/', + query: { q: 'uri' }, + fragment: undefined, + queryString: 'q=uri' + }, + 'basic object properties' + ); + + uri = new mw.Uri( 'https://example.com/mw/index.php?title=Sandbox/7&other=Sandbox/7&foo' ); + assert.equal( + uri.getQueryString(), + 'title=Sandbox/7&other=Sandbox%2F7&foo', + 'title parameter is escaped the wiki-way' + ); + + } ); + + QUnit.test( '.clone()', 6, function ( assert ) { + var original, clone; + + original = new mw.Uri( 'http://foo.example.org/index.php?one=1&two=2' ); + clone = original.clone(); + + assert.deepEqual( clone, original, 'clone has equivalent properties' ); + assert.equal( original.toString(), clone.toString(), 'toString matches original' ); + + assert.notStrictEqual( clone, original, 'clone is a different object when compared by reference' ); + + clone.host = 'bar.example.org'; + assert.notEqual( original.host, clone.host, 'manipulating clone did not effect original' ); + assert.notEqual( original.toString(), clone.toString(), 'Stringified url no longer matches original' ); + + clone.query.three = 3; + + assert.deepEqual( + original.query, + { 'one': '1', 'two': '2' }, + 'Properties is deep cloned (bug 37708)' + ); + } ); + + QUnit.test( '.toString() after query manipulation', 8, function ( assert ) { + var uri; + + uri = new mw.Uri( 'http://www.example.com/dir/?m=foo&m=bar&n=1', { + overrideKeys: true + } ); + + uri.query.n = [ 'x', 'y', 'z' ]; + + // Verify parts and total length instead of entire string because order + // of iteration can vary. + assert.ok( uri.toString().indexOf( 'm=bar' ), 'toString preserves other values' ); + assert.ok( uri.toString().indexOf( 'n=x&n=y&n=z' ), 'toString parameter includes all values of an array query parameter' ); + assert.equal( uri.toString().length, 'http://www.example.com/dir/?m=bar&n=x&n=y&n=z'.length, 'toString matches expected string' ); + + uri = new mw.Uri( 'http://www.example.com/dir/?m=foo&m=bar&n=1', { + overrideKeys: false + } ); + + // Change query values + uri.query.n = [ 'x', 'y', 'z' ]; + + // Verify parts and total length instead of entire string because order + // of iteration can vary. + assert.ok( uri.toString().indexOf( 'm=foo&m=bar' ) >= 0, 'toString preserves other values' ); + assert.ok( uri.toString().indexOf( 'n=x&n=y&n=z' ) >= 0, 'toString parameter includes all values of an array query parameter' ); + assert.equal( uri.toString().length, 'http://www.example.com/dir/?m=foo&m=bar&n=x&n=y&n=z'.length, 'toString matches expected string' ); + + // Remove query values + uri.query.m.splice( 0, 1 ); + delete uri.query.n; + + assert.equal( uri.toString(), 'http://www.example.com/dir/?m=bar', 'deletion properties' ); + + // Remove more query values, leaving an empty array + uri.query.m.splice( 0, 1 ); + assert.equal( uri.toString(), 'http://www.example.com/dir/', 'empty array value is ommitted' ); + } ); + + QUnit.test( 'Advanced URL', 11, function ( assert ) { + var uri, queryString, relativePath; + + uri = new mw.Uri( 'http://auth@www.example.com:81/dir/dir.2/index.htm?q1=0&&test1&test2=value+%28escaped%29#top' ); + + assert.deepEqual( + { + protocol: uri.protocol, + user: uri.user, + password: uri.password, + host: uri.host, + port: uri.port, + path: uri.path, + query: uri.query, + fragment: uri.fragment + }, + { + protocol: 'http', + user: 'auth', + password: undefined, + host: 'www.example.com', + port: '81', + path: '/dir/dir.2/index.htm', + query: { q1: '0', test1: null, test2: 'value (escaped)' }, + fragment: 'top' + }, + 'basic object properties' + ); + + assert.equal( uri.getUserInfo(), 'auth', 'user info' ); + + assert.equal( uri.getAuthority(), 'auth@www.example.com:81', 'authority equal to auth@hostport' ); + + assert.equal( uri.getHostPort(), 'www.example.com:81', 'hostport equal to host:port' ); + + queryString = uri.getQueryString(); + assert.ok( queryString.indexOf( 'q1=0' ) >= 0, 'query param with numbers' ); + assert.ok( queryString.indexOf( 'test1' ) >= 0, 'query param with null value is included' ); + assert.ok( queryString.indexOf( 'test1=' ) === -1, 'query param with null value does not generate equals sign' ); + assert.ok( queryString.indexOf( 'test2=value+%28escaped%29' ) >= 0, 'query param is url escaped' ); + + relativePath = uri.getRelativePath(); + assert.ok( relativePath.indexOf( uri.path ) >= 0, 'path in relative path' ); + assert.ok( relativePath.indexOf( uri.getQueryString() ) >= 0, 'query string in relative path' ); + assert.ok( relativePath.indexOf( uri.fragment ) >= 0, 'fragement in relative path' ); + } ); + + QUnit.test( 'Parse a uri with an @ symbol in the path and query', 1, function ( assert ) { + var uri = new mw.Uri( 'http://www.example.com/test@test?x=@uri&y@=uri&z@=@' ); + + assert.deepEqual( + { + protocol: uri.protocol, + user: uri.user, + password: uri.password, + host: uri.host, + port: uri.port, + path: uri.path, + query: uri.query, + fragment: uri.fragment, + queryString: uri.getQueryString() + }, + { + protocol: 'http', + user: undefined, + password: undefined, + host: 'www.example.com', + port: undefined, + path: '/test@test', + query: { x: '@uri', 'y@': 'uri', 'z@': '@' }, + fragment: undefined, + queryString: 'x=%40uri&y%40=uri&z%40=%40' + }, + 'basic object properties' + ); + } ); + + QUnit.test( 'Handle protocol-relative URLs', 5, function ( assert ) { + var UriRel, uri; + + UriRel = mw.UriRelative( 'glork://en.wiki.local/foo.php' ); + + uri = new UriRel( '//en.wiki.local/w/api.php' ); + assert.equal( uri.protocol, 'glork', 'create protocol-relative URLs with same protocol as document' ); + + uri = new UriRel( '/foo.com' ); + assert.equal( uri.toString(), 'glork://en.wiki.local/foo.com', 'handle absolute paths by supplying protocol and host from document in loose mode' ); + + uri = new UriRel( 'http:/foo.com' ); + assert.equal( uri.toString(), 'http://en.wiki.local/foo.com', 'handle absolute paths by supplying host from document in loose mode' ); + + uri = new UriRel( '/foo.com', true ); + assert.equal( uri.toString(), 'glork://en.wiki.local/foo.com', 'handle absolute paths by supplying protocol and host from document in strict mode' ); + + uri = new UriRel( 'http:/foo.com', true ); + assert.equal( uri.toString(), 'http://en.wiki.local/foo.com', 'handle absolute paths by supplying host from document in strict mode' ); + } ); + + QUnit.test( 'bug 35658', 2, function ( assert ) { + var testProtocol, testServer, testPort, testPath, UriClass, uri, href; + + testProtocol = 'https://'; + testServer = 'foo.example.org'; + testPort = '3004'; + testPath = '/!1qy'; + + UriClass = mw.UriRelative( testProtocol + testServer + '/some/path/index.html' ); + uri = new UriClass( testPath ); + href = uri.toString(); + assert.equal( href, testProtocol + testServer + testPath, 'Root-relative URL gets host & protocol supplied' ); + + UriClass = mw.UriRelative( testProtocol + testServer + ':' + testPort + '/some/path.php' ); + uri = new UriClass( testPath ); + href = uri.toString(); + assert.equal( href, testProtocol + testServer + ':' + testPort + testPath, 'Root-relative URL gets host, protocol, and port supplied' ); + + } ); +}( mediaWiki, jQuery ) ); diff --git a/tests/qunit/suites/resources/mediawiki/mediawiki.cldr.test.js b/tests/qunit/suites/resources/mediawiki/mediawiki.cldr.test.js new file mode 100644 index 00000000..779a0ed4 --- /dev/null +++ b/tests/qunit/suites/resources/mediawiki/mediawiki.cldr.test.js @@ -0,0 +1,81 @@ +( function ( mw, $ ) { + QUnit.module( 'mediawiki.cldr', QUnit.newMwEnvironment() ); + + var pluralTestcases = { + /* + * Sample: + * languagecode : [ + * [ number, [ 'form1', 'form2', ... ], 'expected', 'description' ] + * ]; + */ + en: [ + [ 0, [ 'one', 'other' ], 'other', 'English plural test- 0 is other' ], + [ 1, [ 'one', 'other' ], 'one', 'English plural test- 1 is one' ] + ], + fa: [ + [ 0, [ 'one', 'other' ], 'other', 'Persian plural test- 0 is other' ], + [ 1, [ 'one', 'other' ], 'one', 'Persian plural test- 1 is one' ], + [ 2, [ 'one', 'other' ], 'other', 'Persian plural test- 2 is other' ] + ], + fr: [ + [ 0, [ 'one', 'other' ], 'other', 'French plural test- 0 is other' ], + [ 1, [ 'one', 'other' ], 'one', 'French plural test- 1 is one' ] + ], + hi: [ + [ 0, [ 'one', 'other' ], 'one', 'Hindi plural test- 0 is one' ], + [ 1, [ 'one', 'other' ], 'one', 'Hindi plural test- 1 is one' ], + [ 2, [ 'one', 'other' ], 'other', 'Hindi plural test- 2 is other' ] + ], + he: [ + [ 0, [ 'one', 'other' ], 'other', 'Hebrew plural test- 0 is other' ], + [ 1, [ 'one', 'other' ], 'one', 'Hebrew plural test- 1 is one' ], + [ 2, [ 'one', 'other' ], 'other', 'Hebrew plural test- 2 is other with 2 forms' ], + [ 2, [ 'one', 'dual', 'other' ], 'dual', 'Hebrew plural test- 2 is dual with 3 forms' ] + ], + hu: [ + [ 0, [ 'one', 'other' ], 'other', 'Hungarian plural test- 0 is other' ], + [ 1, [ 'one', 'other' ], 'one', 'Hungarian plural test- 1 is one' ], + [ 2, [ 'one', 'other' ], 'other', 'Hungarian plural test- 2 is other' ] + ], + hy: [ + [ 0, [ 'one', 'other' ], 'other', 'Armenian plural test- 0 is other' ], + [ 1, [ 'one', 'other' ], 'one', 'Armenian plural test- 1 is one' ], + [ 2, [ 'one', 'other' ], 'other', 'Armenian plural test- 2 is other' ] + ], + ar: [ + [ 0, [ 'zero', 'one', 'two', 'few', 'many', 'other' ], 'zero', 'Arabic plural test - 0 is zero' ], + [ 1, [ 'zero', 'one', 'two', 'few', 'many', 'other' ], 'one', 'Arabic plural test - 1 is one' ], + [ 2, [ 'zero', 'one', 'two', 'few', 'many', 'other' ], 'two', 'Arabic plural test - 2 is two' ], + [ 3, [ 'zero', 'one', 'two', 'few', 'many', 'other' ], 'few', 'Arabic plural test - 3 is few' ], + [ 9, [ 'zero', 'one', 'two', 'few', 'many', 'other' ], 'few', 'Arabic plural test - 9 is few' ], + [ '9', [ 'zero', 'one', 'two', 'few', 'many', 'other' ], 'few', 'Arabic plural test - 9 is few' ], + [ 110, [ 'zero', 'one', 'two', 'few', 'many', 'other' ], 'few', 'Arabic plural test - 110 is few' ], + [ 11, [ 'zero', 'one', 'two', 'few', 'many', 'other' ], 'many', 'Arabic plural test - 11 is many' ], + [ 15, [ 'zero', 'one', 'two', 'few', 'many', 'other' ], 'many', 'Arabic plural test - 15 is many' ], + [ 99, [ 'zero', 'one', 'two', 'few', 'many', 'other' ], 'many', 'Arabic plural test - 99 is many' ], + [ 9999, [ 'zero', 'one', 'two', 'few', 'many', 'other' ], 'many', 'Arabic plural test - 9999 is many' ], + [ 100, [ 'zero', 'one', 'two', 'few', 'many', 'other' ], 'other', 'Arabic plural test - 100 is other' ], + [ 102, [ 'zero', 'one', 'two', 'few', 'many', 'other' ], 'other', 'Arabic plural test - 102 is other' ], + [ 1000, [ 'zero', 'one', 'two', 'few', 'many', 'other' ], 'other', 'Arabic plural test - 1000 is other' ], + [ 1.7, [ 'zero', 'one', 'two', 'few', 'many', 'other' ], 'other', 'Arabic plural test - 1.7 is other' ] + ] + }; + + function pluralTest( langCode, tests ) { + QUnit.test( 'Plural Test for ' + langCode, tests.length, function ( assert ) { + for ( var i = 0; i < tests.length; i++ ) { + assert.equal( + mw.language.convertPlural( tests[i][0], tests[i][1] ), + tests[i][2], + tests[i][3] + ); + } + } ); + } + + $.each( pluralTestcases, function ( langCode, tests ) { + if ( langCode === mw.config.get( 'wgUserLanguage' ) ) { + pluralTest( langCode, tests ); + } + } ); +}( mediaWiki, jQuery ) ); diff --git a/tests/qunit/suites/resources/mediawiki/mediawiki.cookie.test.js b/tests/qunit/suites/resources/mediawiki/mediawiki.cookie.test.js new file mode 100644 index 00000000..c9653dab --- /dev/null +++ b/tests/qunit/suites/resources/mediawiki/mediawiki.cookie.test.js @@ -0,0 +1,172 @@ +( function ( mw, $ ) { + + var NOW = 9012, // miliseconds + DEFAULT_DURATION = 5678, // seconds + expiryDate = new Date(); + + expiryDate.setTime( NOW + ( DEFAULT_DURATION * 1000 ) ); + + QUnit.module( 'mediawiki.cookie', QUnit.newMwEnvironment( { + setup: function () { + this.stub( $, 'cookie' ).returns( null ); + + this.sandbox.useFakeTimers( NOW ); + }, + config: { + wgCookiePrefix: 'mywiki', + wgCookieDomain: 'example.org', + wgCookiePath: '/path', + wgCookieExpiration: DEFAULT_DURATION + } + } ) ); + + QUnit.test( 'set( key, value )', 7, function ( assert ) { + var call; + + // Simple case + mw.cookie.set( 'foo', 'bar' ); + + call = $.cookie.lastCall.args; + assert.strictEqual( call[ 0 ], 'mywikifoo' ); + assert.strictEqual( call[ 1 ], 'bar' ); + assert.deepEqual( call[ 2 ], { + expires: expiryDate, + domain: 'example.org', + path: '/path', + secure: false + } ); + + mw.cookie.set( 'foo', null ); + call = $.cookie.lastCall.args; + assert.strictEqual( call[ 1 ], null, 'null removes cookie' ); + + mw.cookie.set( 'foo', undefined ); + call = $.cookie.lastCall.args; + assert.strictEqual( call[ 1 ], 'undefined', 'undefined is value' ); + + mw.cookie.set( 'foo', false ); + call = $.cookie.lastCall.args; + assert.strictEqual( call[ 1 ], 'false', 'false is a value' ); + + mw.cookie.set( 'foo', 0 ); + call = $.cookie.lastCall.args; + assert.strictEqual( call[ 1 ], '0', '0 is value' ); + } ); + + QUnit.test( 'set( key, value, expires )', 5, function ( assert ) { + var date, options; + + date = new Date(); + date.setTime( 1234 ); + + mw.cookie.set( 'foo', 'bar' ); + options = $.cookie.lastCall.args[ 2 ]; + assert.deepEqual( options.expires, expiryDate, 'Default cookie expiration is used' ); + + mw.cookie.set( 'foo', 'bar', date ); + options = $.cookie.lastCall.args[ 2 ]; + assert.strictEqual( options.expires, date, 'Custom expiration date' ); + + mw.cookie.set( 'foo', 'bar', null ); + options = $.cookie.lastCall.args[ 2 ]; + assert.strictEqual( options.expires, undefined, 'Expiry null forces session cookie' ); + + // Per DefaultSettings.php, when wgCookieExpiration is 0, the default should + // be session cookies + mw.config.set( 'wgCookieExpiration', 0 ); + + mw.cookie.set( 'foo', 'bar' ); + options = $.cookie.lastCall.args[ 2 ]; + assert.strictEqual( options.expires, undefined, 'wgCookieExpiration=0 results in session cookies by default' ); + + mw.cookie.set( 'foo', 'bar', date ); + options = $.cookie.lastCall.args[ 2 ]; + assert.strictEqual( options.expires, date, 'Custom expiration when default is session cookies' ); + } ); + + QUnit.test( 'set( key, value, options )', 4, function ( assert ) { + var date, call; + + mw.cookie.set( 'foo', 'bar', { + prefix: 'myPrefix', + domain: 'myDomain', + path: 'myPath', + secure: true + } ); + + call = $.cookie.lastCall.args; + assert.strictEqual( call[0], 'myPrefixfoo' ); + assert.deepEqual( call[ 2 ], { + expires: expiryDate, + domain: 'myDomain', + path: 'myPath', + secure: true + }, 'Options (without expires)' ); + + date = new Date(); + date.setTime( 1234 ); + + mw.cookie.set( 'foo', 'bar', { + expires: date, + prefix: 'myPrefix', + domain: 'myDomain', + path: 'myPath', + secure: true + } ); + + call = $.cookie.lastCall.args; + assert.strictEqual( call[0], 'myPrefixfoo' ); + assert.deepEqual( call[ 2 ], { + expires: date, + domain: 'myDomain', + path: 'myPath', + secure: true + }, 'Options (incl. expires)' ); + } ); + + QUnit.test( 'get( key ) - no values', 6, function ( assert ) { + var key, value; + + mw.cookie.get( 'foo' ); + + key = $.cookie.lastCall.args[ 0 ]; + assert.strictEqual( key, 'mywikifoo', 'Default prefix' ); + + mw.cookie.get( 'foo', undefined ); + key = $.cookie.lastCall.args[ 0 ]; + assert.strictEqual( key, 'mywikifoo', 'Use default prefix for undefined' ); + + mw.cookie.get( 'foo', null ); + key = $.cookie.lastCall.args[ 0 ]; + assert.strictEqual( key, 'mywikifoo', 'Use default prefix for null' ); + + mw.cookie.get( 'foo', '' ); + key = $.cookie.lastCall.args[ 0 ]; + assert.strictEqual( key, 'foo', 'Don\'t use default prefix for empty string' ); + + value = mw.cookie.get( 'foo' ); + assert.strictEqual( value, null, 'Return null by default' ); + + value = mw.cookie.get( 'foo', null, 'bar' ); + assert.strictEqual( value, 'bar', 'Custom default value' ); + } ); + + QUnit.test( 'get( key ) - with value', 1, function ( assert ) { + var value; + + $.cookie.returns( 'bar' ); + + value = mw.cookie.get( 'foo' ); + assert.strictEqual( value, 'bar', 'Return value of cookie' ); + } ); + + QUnit.test( 'get( key, prefix )', 1, function ( assert ) { + var key; + + mw.cookie.get( 'foo', 'bar' ); + + key = $.cookie.lastCall.args[ 0 ]; + assert.strictEqual( key, 'barfoo' ); + } ); + +} ( mediaWiki, jQuery ) ); diff --git a/tests/qunit/suites/resources/mediawiki/mediawiki.jqueryMsg.test.js b/tests/qunit/suites/resources/mediawiki/mediawiki.jqueryMsg.test.js new file mode 100644 index 00000000..6b3be43b --- /dev/null +++ b/tests/qunit/suites/resources/mediawiki/mediawiki.jqueryMsg.test.js @@ -0,0 +1,798 @@ +( function ( mw, $ ) { + var formatText, formatParse, formatnumTests, specialCharactersPageName, expectedListUsers, expectedEntrypoints, + mwLanguageCache = {}, + hasOwn = Object.hasOwnProperty; + + // When the expected result is the same in both modes + function assertBothModes( assert, parserArguments, expectedResult, assertMessage ) { + assert.equal( formatText.apply( null, parserArguments ), expectedResult, assertMessage + ' when format is \'text\'' ); + assert.equal( formatParse.apply( null, parserArguments ), expectedResult, assertMessage + ' when format is \'parse\'' ); + } + + QUnit.module( 'mediawiki.jqueryMsg', QUnit.newMwEnvironment( { + setup: function () { + this.originalMwLanguage = mw.language; + + specialCharactersPageName = '"Who" wants to be a millionaire & live on \'Exotic Island\'?'; + + expectedListUsers = '注册<a title="Special:ListUsers" href="/wiki/Special:ListUsers">用户</a>'; + + expectedEntrypoints = '<a href="https://www.mediawiki.org/wiki/Manual:index.php">index.php</a>'; + + formatText = mw.jqueryMsg.getMessageFunction( { + format: 'text' + } ); + + formatParse = mw.jqueryMsg.getMessageFunction( { + format: 'parse' + } ); + }, + teardown: function () { + mw.language = this.originalMwLanguage; + }, + config: { + wgArticlePath: '/wiki/$1' + }, + // Messages that are reused in multiple tests + messages: { + // The values for gender are not significant, + // what matters is which of the values is choosen by the parser + 'gender-msg': '$1: {{GENDER:$2|blue|pink|green}}', + 'gender-msg-currentuser': '{{GENDER:|blue|pink|green}}', + + 'plural-msg': 'Found $1 {{PLURAL:$1|item|items}}', + // See https://bugzilla.wikimedia.org/69993 + 'plural-msg-explicit-forms-nested': 'Found {{PLURAL:$1|$1 results|0=no results in {{SITENAME}}|1=$1 result}}', + // Assume the grammar form grammar_case_foo is not valid in any language + 'grammar-msg': 'Przeszukaj {{GRAMMAR:grammar_case_foo|{{SITENAME}}}}', + + 'formatnum-msg': '{{formatnum:$1}}', + + 'portal-url': 'Project:Community portal', + 'see-portal-url': '{{Int:portal-url}} is an important community page.', + + 'jquerymsg-test-statistics-users': '注册[[Special:ListUsers|用户]]', + + 'jquerymsg-test-version-entrypoints-index-php': '[https://www.mediawiki.org/wiki/Manual:index.php index.php]', + + 'external-link-replace': 'Foo [$1 bar]' + } + } ) ); + + /** + * Be careful to no run this in parallel as it uses a global identifier (mw.language) + * to transport the module back to the test. It musn't be overwritten concurrentely. + * + * This function caches the mw.language data to avoid having to request the same module + * multiple times. There is more than one test case for any given language. + */ + function getMwLanguage( langCode ) { + if ( !hasOwn.call( mwLanguageCache, langCode ) ) { + mwLanguageCache[langCode] = $.ajax( { + url: mw.util.wikiScript( 'load' ), + data: { + skin: mw.config.get( 'skin' ), + lang: langCode, + debug: mw.config.get( 'debug' ), + modules: [ + 'mediawiki.language.data', + 'mediawiki.language' + ].join( '|' ), + only: 'scripts' + }, + dataType: 'script', + cache: true + } ).then( function () { + return mw.language; + } ); + } + return mwLanguageCache[langCode]; + } + + /** + * @param {Function[]} tasks List of functions that perform tasks + * that may be asynchronous. Invoke the callback parameter when done. + * @param {Function} done When all tasks are done. + * @return + */ + function process( tasks, done ) { + function run() { + var task = tasks.shift(); + if ( task ) { + task( run ); + } else { + done(); + } + } + run(); + } + + QUnit.test( 'Replace', 9, function ( assert ) { + mw.messages.set( 'simple', 'Foo $1 baz $2' ); + + assert.equal( formatParse( 'simple' ), 'Foo $1 baz $2', 'Replacements with no substitutes' ); + assert.equal( formatParse( 'simple', 'bar' ), 'Foo bar baz $2', 'Replacements with less substitutes' ); + assert.equal( formatParse( 'simple', 'bar', 'quux' ), 'Foo bar baz quux', 'Replacements with all substitutes' ); + + mw.messages.set( 'plain-input', '<foo foo="foo">x$1y<</foo>z' ); + + assert.equal( + formatParse( 'plain-input', 'bar' ), + '<foo foo="foo">xbary&lt;</foo>z', + 'Input is not considered html' + ); + + mw.messages.set( 'plain-replace', 'Foo $1' ); + + assert.equal( + formatParse( 'plain-replace', '<bar bar="bar">></bar>' ), + 'Foo <bar bar="bar">&gt;</bar>', + 'Replacement is not considered html' + ); + + mw.messages.set( 'object-replace', 'Foo $1' ); + + assert.equal( + formatParse( 'object-replace', $( '<div class="bar">></div>' ) ), + 'Foo <div class="bar">></div>', + 'jQuery objects are preserved as raw html' + ); + + assert.equal( + formatParse( 'object-replace', $( '<div class="bar">></div>' ).get( 0 ) ), + 'Foo <div class="bar">></div>', + 'HTMLElement objects are preserved as raw html' + ); + + assert.equal( + formatParse( 'object-replace', $( '<div class="bar">></div>' ).toArray() ), + 'Foo <div class="bar">></div>', + 'HTMLElement[] arrays are preserved as raw html' + ); + + assert.equal( + formatParse( 'external-link-replace', 'http://example.org/?x=y&z' ), + 'Foo <a href="http://example.org/?x=y&z">bar</a>', + 'Href is not double-escaped in wikilink function' + ); + } ); + + QUnit.test( 'Plural', 6, function ( assert ) { + assert.equal( formatParse( 'plural-msg', 0 ), 'Found 0 items', 'Plural test for english with zero as count' ); + assert.equal( formatParse( 'plural-msg', 1 ), 'Found 1 item', 'Singular test for english' ); + assert.equal( formatParse( 'plural-msg', 2 ), 'Found 2 items', 'Plural test for english' ); + assert.equal( formatParse( 'plural-msg-explicit-forms-nested', 6 ), 'Found 6 results', 'Plural message with explicit plural forms' ); + assert.equal( formatParse( 'plural-msg-explicit-forms-nested', 0 ), 'Found no results in ' + mw.config.get( 'wgSiteName' ), 'Plural message with explicit plural forms, with nested {{SITENAME}}' ); + assert.equal( formatParse( 'plural-msg-explicit-forms-nested', 1 ), 'Found 1 result', 'Plural message with explicit plural forms with placeholder nested' ); + } ); + + QUnit.test( 'Gender', 15, function ( assert ) { + var originalGender = mw.user.options.get( 'gender' ); + + // TODO: These tests should be for mw.msg once mw.msg integrated with mw.jqueryMsg + // TODO: English may not be the best language for these tests. Use a language like Arabic or Russian + mw.user.options.set( 'gender', 'male' ); + assert.equal( + formatParse( 'gender-msg', 'Bob', 'male' ), + 'Bob: blue', + 'Masculine from string "male"' + ); + assert.equal( + formatParse( 'gender-msg', 'Bob', mw.user ), + 'Bob: blue', + 'Masculine from mw.user object' + ); + assert.equal( + formatParse( 'gender-msg-currentuser' ), + 'blue', + 'Masculine for current user' + ); + + mw.user.options.set( 'gender', 'female' ); + assert.equal( + formatParse( 'gender-msg', 'Alice', 'female' ), + 'Alice: pink', + 'Feminine from string "female"' ); + assert.equal( + formatParse( 'gender-msg', 'Alice', mw.user ), + 'Alice: pink', + 'Feminine from mw.user object' + ); + assert.equal( + formatParse( 'gender-msg-currentuser' ), + 'pink', + 'Feminine for current user' + ); + + mw.user.options.set( 'gender', 'unknown' ); + assert.equal( + formatParse( 'gender-msg', 'Foo', mw.user ), + 'Foo: green', + 'Neutral from mw.user object' ); + assert.equal( + formatParse( 'gender-msg', 'User' ), + 'User: green', + 'Neutral when no parameter given' ); + assert.equal( + formatParse( 'gender-msg', 'User', 'unknown' ), + 'User: green', + 'Neutral from string "unknown"' + ); + assert.equal( + formatParse( 'gender-msg-currentuser' ), + 'green', + 'Neutral for current user' + ); + + mw.messages.set( 'gender-msg-one-form', '{{GENDER:$1|User}}: $2 {{PLURAL:$2|edit|edits}}' ); + + assert.equal( + formatParse( 'gender-msg-one-form', 'male', 10 ), + 'User: 10 edits', + 'Gender neutral and plural form' + ); + assert.equal( + formatParse( 'gender-msg-one-form', 'female', 1 ), + 'User: 1 edit', + 'Gender neutral and singular form' + ); + + mw.messages.set( 'gender-msg-lowercase', '{{gender:$1|he|she}} is awesome' ); + assert.equal( + formatParse( 'gender-msg-lowercase', 'male' ), + 'he is awesome', + 'Gender masculine' + ); + assert.equal( + formatParse( 'gender-msg-lowercase', 'female' ), + 'she is awesome', + 'Gender feminine' + ); + + mw.messages.set( 'gender-msg-wrong', '{{gender}} test' ); + assert.equal( + formatParse( 'gender-msg-wrong', 'female' ), + ' test', + 'Invalid syntax should result in {{gender}} simply being stripped away' + ); + + mw.user.options.set( 'gender', originalGender ); + } ); + + QUnit.test( 'Grammar', 2, function ( assert ) { + assert.equal( formatParse( 'grammar-msg' ), 'Przeszukaj ' + mw.config.get( 'wgSiteName' ), 'Grammar Test with sitename' ); + + mw.messages.set( 'grammar-msg-wrong-syntax', 'Przeszukaj {{GRAMMAR:grammar_case_xyz}}' ); + assert.equal( formatParse( 'grammar-msg-wrong-syntax' ), 'Przeszukaj ', 'Grammar Test with wrong grammar template syntax' ); + } ); + + QUnit.test( 'Match PHP parser', mw.libs.phpParserData.tests.length, function ( assert ) { + mw.messages.set( mw.libs.phpParserData.messages ); + var tasks = $.map( mw.libs.phpParserData.tests, function ( test ) { + return function ( next ) { + getMwLanguage( test.lang ) + .done( function ( langClass ) { + mw.config.set( 'wgUserLanguage', test.lang ); + var parser = new mw.jqueryMsg.parser( { language: langClass } ); + assert.equal( + parser.parse( test.key, test.args ).html(), + test.result, + test.name + ); + } ) + .fail( function () { + assert.ok( false, 'Language "' + test.lang + '" failed to load.' ); + } ) + .always( next ); + }; + } ); + + QUnit.stop(); + process( tasks, QUnit.start ); + } ); + + QUnit.test( 'Links', 6, function ( assert ) { + var expectedDisambiguationsText, + expectedMultipleBars, + expectedSpecialCharacters; + + // The below three are all identical to or based on real messages. For disambiguations-text, + // the bold was removed because it is not yet implemented. + + assert.htmlEqual( + formatParse( 'jquerymsg-test-statistics-users' ), + expectedListUsers, + 'Piped wikilink' + ); + + expectedDisambiguationsText = 'The following pages contain at least one link to a disambiguation page.\nThey may have to link to a more appropriate page instead.\nA page is treated as a disambiguation page if it uses a template that is linked from ' + + '<a title="MediaWiki:Disambiguationspage" href="/wiki/MediaWiki:Disambiguationspage">MediaWiki:Disambiguationspage</a>.'; + + mw.messages.set( 'disambiguations-text', 'The following pages contain at least one link to a disambiguation page.\nThey may have to link to a more appropriate page instead.\nA page is treated as a disambiguation page if it uses a template that is linked from [[MediaWiki:Disambiguationspage]].' ); + assert.htmlEqual( + formatParse( 'disambiguations-text' ), + expectedDisambiguationsText, + 'Wikilink without pipe' + ); + + assert.htmlEqual( + formatParse( 'jquerymsg-test-version-entrypoints-index-php' ), + expectedEntrypoints, + 'External link' + ); + + // Pipe trick is not supported currently, but should not parse as text either. + mw.messages.set( 'pipe-trick', '[[Tampa, Florida|]]' ); + this.suppressWarnings(); + assert.equal( + formatParse( 'pipe-trick' ), + '[[Tampa, Florida|]]', + 'Pipe trick should not be parsed.' + ); + this.restoreWarnings(); + + expectedMultipleBars = '<a title="Main Page" href="/wiki/Main_Page">Main|Page</a>'; + mw.messages.set( 'multiple-bars', '[[Main Page|Main|Page]]' ); + assert.htmlEqual( + formatParse( 'multiple-bars' ), + expectedMultipleBars, + 'Bar in anchor' + ); + + expectedSpecialCharacters = '<a title=""Who" wants to be a millionaire & live on 'Exotic Island'?" href="/wiki/%22Who%22_wants_to_be_a_millionaire_%26_live_on_%27Exotic_Island%27%3F">"Who" wants to be a millionaire & live on 'Exotic Island'?</a>'; + + mw.messages.set( 'special-characters', '[[' + specialCharactersPageName + ']]' ); + assert.htmlEqual( + formatParse( 'special-characters' ), + expectedSpecialCharacters, + 'Special characters' + ); + } ); + +// Tests that {{-transformation vs. general parsing are done as requested + QUnit.test( 'Curly brace transformation', 16, function ( assert ) { + var oldUserLang = mw.config.get( 'wgUserLanguage' ); + + assertBothModes( assert, ['gender-msg', 'Bob', 'male'], 'Bob: blue', 'gender is resolved' ); + + assertBothModes( assert, ['plural-msg', 5], 'Found 5 items', 'plural is resolved' ); + + assertBothModes( assert, ['grammar-msg'], 'Przeszukaj ' + mw.config.get( 'wgSiteName' ), 'grammar is resolved' ); + + mw.config.set( 'wgUserLanguage', 'en' ); + assertBothModes( assert, ['formatnum-msg', '987654321.654321'], '987,654,321.654', 'formatnum is resolved' ); + + // Test non-{{ wikitext, where behavior differs + + // Wikilink + assert.equal( + formatText( 'jquerymsg-test-statistics-users' ), + mw.messages.get( 'jquerymsg-test-statistics-users' ), + 'Internal link message unchanged when format is \'text\'' + ); + assert.htmlEqual( + formatParse( 'jquerymsg-test-statistics-users' ), + expectedListUsers, + 'Internal link message parsed when format is \'parse\'' + ); + + // External link + assert.equal( + formatText( 'jquerymsg-test-version-entrypoints-index-php' ), + mw.messages.get( 'jquerymsg-test-version-entrypoints-index-php' ), + 'External link message unchanged when format is \'text\'' + ); + assert.htmlEqual( + formatParse( 'jquerymsg-test-version-entrypoints-index-php' ), + expectedEntrypoints, + 'External link message processed when format is \'parse\'' + ); + + // External link with parameter + assert.equal( + formatText( 'external-link-replace', 'http://example.com' ), + 'Foo [http://example.com bar]', + 'External link message only substitutes parameter when format is \'text\'' + ); + assert.htmlEqual( + formatParse( 'external-link-replace', 'http://example.com' ), + 'Foo <a href="http://example.com">bar</a>', + 'External link message processed when format is \'parse\'' + ); + assert.htmlEqual( + formatParse( 'external-link-replace', $( '<i>' ) ), + 'Foo <i>bar</i>', + 'External link message processed as jQuery object when format is \'parse\'' + ); + assert.htmlEqual( + formatParse( 'external-link-replace', function () {} ), + 'Foo <a href="#">bar</a>', + 'External link message processed as function when format is \'parse\'' + ); + + mw.config.set( 'wgUserLanguage', oldUserLang ); + } ); + + QUnit.test( 'Int', 4, function ( assert ) { + var newarticletextSource = 'You have followed a link to a page that does not exist yet. To create the page, start typing in the box below (see the [[{{Int:Foobar}}|foobar]] for more info). If you are here by mistake, click your browser\'s back button.', + expectedNewarticletext, + helpPageTitle = 'Help:Foobar'; + + mw.messages.set( 'foobar', helpPageTitle ); + + expectedNewarticletext = 'You have followed a link to a page that does not exist yet. To create the page, start typing in the box below (see the ' + + '<a title="Help:Foobar" href="/wiki/Help:Foobar">foobar</a> for more info). If you are here by mistake, click your browser\'s back button.'; + + mw.messages.set( 'newarticletext', newarticletextSource ); + + assert.htmlEqual( + formatParse( 'newarticletext' ), + expectedNewarticletext, + 'Link with nested message' + ); + + assert.equal( + formatParse( 'see-portal-url' ), + 'Project:Community portal is an important community page.', + 'Nested message' + ); + + mw.messages.set( 'newarticletext-lowercase', + newarticletextSource.replace( 'Int:Helppage', 'int:helppage' ) ); + + assert.htmlEqual( + formatParse( 'newarticletext-lowercase' ), + expectedNewarticletext, + 'Link with nested message, lowercase include' + ); + + mw.messages.set( 'uses-missing-int', '{{int:doesnt-exist}}' ); + + assert.equal( + formatParse( 'uses-missing-int' ), + '[doesnt-exist]', + 'int: where nested message does not exist' + ); + } ); + + // Tests that getMessageFunction is used for non-plain messages with curly braces or + // square brackets, but not otherwise. + QUnit.test( 'mw.Message.prototype.parser monkey-patch', 22, function ( assert ) { + var oldGMF, outerCalled, innerCalled; + + mw.messages.set( { + 'curly-brace': '{{int:message}}', + 'single-square-bracket': '[https://www.mediawiki.org/ MediaWiki]', + 'double-square-bracket': '[[Some page]]', + 'regular': 'Other message' + } ); + + oldGMF = mw.jqueryMsg.getMessageFunction; + + mw.jqueryMsg.getMessageFunction = function () { + outerCalled = true; + return function () { + innerCalled = true; + }; + }; + + function verifyGetMessageFunction( key, format, shouldCall ) { + var message; + outerCalled = false; + innerCalled = false; + message = mw.message( key ); + message[format](); + assert.strictEqual( outerCalled, shouldCall, 'Outer function called for ' + key ); + assert.strictEqual( innerCalled, shouldCall, 'Inner function called for ' + key ); + } + + verifyGetMessageFunction( 'curly-brace', 'parse', true ); + verifyGetMessageFunction( 'curly-brace', 'plain', false ); + + verifyGetMessageFunction( 'single-square-bracket', 'parse', true ); + verifyGetMessageFunction( 'single-square-bracket', 'plain', false ); + + verifyGetMessageFunction( 'double-square-bracket', 'parse', true ); + verifyGetMessageFunction( 'double-square-bracket', 'plain', false ); + + verifyGetMessageFunction( 'regular', 'parse', false ); + verifyGetMessageFunction( 'regular', 'plain', false ); + + verifyGetMessageFunction( 'jquerymsg-test-pagetriage-del-talk-page-notify-summary', 'plain', false ); + verifyGetMessageFunction( 'jquerymsg-test-categorytree-collapse-bullet', 'plain', false ); + verifyGetMessageFunction( 'jquerymsg-test-wikieditor-toolbar-help-content-signature-result', 'plain', false ); + + mw.jqueryMsg.getMessageFunction = oldGMF; + } ); + +formatnumTests = [ + { + lang: 'en', + number: 987654321.654321, + result: '987,654,321.654', + description: 'formatnum test for English, decimal seperator' + }, + { + lang: 'ar', + number: 987654321.654321, + result: '٩٨٧٬٦٥٤٬٣٢١٫٦٥٤', + description: 'formatnum test for Arabic, with decimal seperator' + }, + { + lang: 'ar', + number: '٩٨٧٦٥٤٣٢١٫٦٥٤٣٢١', + result: 987654321, + integer: true, + description: 'formatnum test for Arabic, with decimal seperator, reverse' + }, + { + lang: 'ar', + number: -12.89, + result: '-١٢٫٨٩', + description: 'formatnum test for Arabic, negative number' + }, + { + lang: 'ar', + number: '-١٢٫٨٩', + result: -12, + integer: true, + description: 'formatnum test for Arabic, negative number, reverse' + }, + { + lang: 'nl', + number: 987654321.654321, + result: '987.654.321,654', + description: 'formatnum test for Nederlands, decimal seperator' + }, + { + lang: 'nl', + number: -12.89, + result: '-12,89', + description: 'formatnum test for Nederlands, negative number' + }, + { + lang: 'nl', + number: '.89', + result: '0,89', + description: 'formatnum test for Nederlands' + }, + { + lang: 'nl', + number: 'invalidnumber', + result: 'invalidnumber', + description: 'formatnum test for Nederlands, invalid number' + }, + { + lang: 'ml', + number: '1000000000', + result: '1,00,00,00,000', + description: 'formatnum test for Malayalam' + }, + { + lang: 'ml', + number: '-1000000000', + result: '-1,00,00,00,000', + description: 'formatnum test for Malayalam, negative number' + }, + /* + * This will fail because of wrong pattern for ml in MW(different from CLDR) + { + lang: 'ml', + number: '1000000000.000', + result: '1,00,00,00,000.000', + description: 'formatnum test for Malayalam with decimal place' + }, + */ + { + lang: 'hi', + number: '123456789.123456789', + result: '१२,३४,५६,७८९', + description: 'formatnum test for Hindi' + }, + { + lang: 'hi', + number: '१२,३४,५६,७८९', + result: '१२,३४,५६,७८९', + description: 'formatnum test for Hindi, Devanagari digits passed' + }, + { + lang: 'hi', + number: '१२३४५६,७८९', + result: '123456', + integer: true, + description: 'formatnum test for Hindi, Devanagari digits passed to get integer value' + } +]; + +QUnit.test( 'formatnum', formatnumTests.length, function ( assert ) { + mw.messages.set( 'formatnum-msg', '{{formatnum:$1}}' ); + mw.messages.set( 'formatnum-msg-int', '{{formatnum:$1|R}}' ); + var queue = $.map( formatnumTests, function ( test ) { + return function ( next ) { + getMwLanguage( test.lang ) + .done( function ( langClass ) { + mw.config.set( 'wgUserLanguage', test.lang ); + var parser = new mw.jqueryMsg.parser( { language: langClass } ); + assert.equal( + parser.parse( test.integer ? 'formatnum-msg-int' : 'formatnum-msg', + [ test.number ] ).html(), + test.result, + test.description + ); + } ) + .fail( function () { + assert.ok( false, 'Language "' + test.lang + '" failed to load' ); + } ) + .always( next ); + }; + } ); + QUnit.stop(); + process( queue, QUnit.start ); +} ); + +// HTML in wikitext +QUnit.test( 'HTML', 26, function ( assert ) { + mw.messages.set( 'jquerymsg-italics-msg', '<i>Very</i> important' ); + + assertBothModes( assert, ['jquerymsg-italics-msg'], mw.messages.get( 'jquerymsg-italics-msg' ), 'Simple italics unchanged' ); + + mw.messages.set( 'jquerymsg-bold-msg', '<b>Strong</b> speaker' ); + assertBothModes( assert, ['jquerymsg-bold-msg'], mw.messages.get( 'jquerymsg-bold-msg' ), 'Simple bold unchanged' ); + + mw.messages.set( 'jquerymsg-bold-italics-msg', 'It is <b><i>key</i></b>' ); + assertBothModes( assert, ['jquerymsg-bold-italics-msg'], mw.messages.get( 'jquerymsg-bold-italics-msg' ), 'Bold and italics nesting order preserved' ); + + mw.messages.set( 'jquerymsg-italics-bold-msg', 'It is <i><b>vital</b></i>' ); + assertBothModes( assert, ['jquerymsg-italics-bold-msg'], mw.messages.get( 'jquerymsg-italics-bold-msg' ), 'Italics and bold nesting order preserved' ); + + mw.messages.set( 'jquerymsg-italics-with-link', 'An <i>italicized [[link|wiki-link]]</i>' ); + + assert.htmlEqual( + formatParse( 'jquerymsg-italics-with-link' ), + 'An <i>italicized <a title="link" href="' + mw.html.escape( mw.util.getUrl( 'link' ) ) + '">wiki-link</i>', + 'Italics with link inside in parse mode' + ); + + assert.equal( + formatText( 'jquerymsg-italics-with-link' ), + mw.messages.get( 'jquerymsg-italics-with-link' ), + 'Italics with link unchanged in text mode' + ); + + mw.messages.set( 'jquerymsg-italics-id-class', '<i id="foo" class="bar">Foo</i>' ); + assert.htmlEqual( + formatParse( 'jquerymsg-italics-id-class' ), + mw.messages.get( 'jquerymsg-italics-id-class' ), + 'ID and class are allowed' + ); + + mw.messages.set( 'jquerymsg-italics-onclick', '<i onclick="alert(\'foo\')">Foo</i>' ); + assert.htmlEqual( + formatParse( 'jquerymsg-italics-onclick' ), + '<i onclick="alert(\'foo\')">Foo</i>', + 'element with onclick is escaped because it is not allowed' + ); + + mw.messages.set( 'jquerymsg-script-msg', '<script >alert( "Who put this tag here?" );</script>' ); + assert.htmlEqual( + formatParse( 'jquerymsg-script-msg' ), + '<script >alert( "Who put this tag here?" );</script>', + 'Tag outside whitelist escaped in parse mode' + ); + + assert.equal( + formatText( 'jquerymsg-script-msg' ), + mw.messages.get( 'jquerymsg-script-msg' ), + 'Tag outside whitelist unchanged in text mode' + ); + + mw.messages.set( 'jquerymsg-script-link-msg', '<script>[[Foo|bar]]</script>' ); + assert.htmlEqual( + formatParse( 'jquerymsg-script-link-msg' ), + '<script><a title="Foo" href="' + mw.html.escape( mw.util.getUrl( 'Foo' ) ) + '">bar</a></script>', + 'Script tag text is escaped because that element is not allowed, but link inside is still HTML' + ); + + mw.messages.set( 'jquerymsg-mismatched-html', '<i class="important">test</b>' ); + assert.htmlEqual( + formatParse( 'jquerymsg-mismatched-html' ), + '<i class="important">test</b>', + 'Mismatched HTML start and end tag treated as text' + ); + + // TODO (mattflaschen, 2013-03-18): It's not a security issue, but there's no real + // reason the htmlEmitter span needs to be here. It's an artifact of how emitting works. + mw.messages.set( 'jquerymsg-script-and-external-link', '<script>alert( "jquerymsg-script-and-external-link test" );</script> [http://example.com <i>Foo</i> bar]' ); + assert.htmlEqual( + formatParse( 'jquerymsg-script-and-external-link' ), + '<script>alert( "jquerymsg-script-and-external-link test" );</script> <a href="http://example.com"><span class="mediaWiki_htmlEmitter"><i>Foo</i> bar</span></a>', + 'HTML tags in external links not interfering with escaping of other tags' + ); + + mw.messages.set( 'jquerymsg-link-script', '[http://example.com <script>alert( "jquerymsg-link-script test" );</script>]' ); + assert.htmlEqual( + formatParse( 'jquerymsg-link-script' ), + '<a href="http://example.com"><span class="mediaWiki_htmlEmitter"><script>alert( "jquerymsg-link-script test" );</script></span></a>', + 'Non-whitelisted HTML tag in external link anchor treated as text' + ); + + // Intentionally not using htmlEqual for the quote tests + mw.messages.set( 'jquerymsg-double-quotes-preserved', '<i id="double">Double</i>' ); + assert.equal( + formatParse( 'jquerymsg-double-quotes-preserved' ), + mw.messages.get( 'jquerymsg-double-quotes-preserved' ), + 'Attributes with double quotes are preserved as such' + ); + + mw.messages.set( 'jquerymsg-single-quotes-normalized-to-double', '<i id=\'single\'>Single</i>' ); + assert.equal( + formatParse( 'jquerymsg-single-quotes-normalized-to-double' ), + '<i id="single">Single</i>', + 'Attributes with single quotes are normalized to double' + ); + + mw.messages.set( 'jquerymsg-escaped-double-quotes-attribute', '<i style="font-family:"Arial"">Styled</i>' ); + assert.htmlEqual( + formatParse( 'jquerymsg-escaped-double-quotes-attribute' ), + mw.messages.get( 'jquerymsg-escaped-double-quotes-attribute' ), + 'Escaped attributes are parsed correctly' + ); + + mw.messages.set( 'jquerymsg-escaped-single-quotes-attribute', '<i style=\'font-family:'Arial'\'>Styled</i>' ); + assert.htmlEqual( + formatParse( 'jquerymsg-escaped-single-quotes-attribute' ), + mw.messages.get( 'jquerymsg-escaped-single-quotes-attribute' ), + 'Escaped attributes are parsed correctly' + ); + + mw.messages.set( 'jquerymsg-wikitext-contents-parsed', '<i>[http://example.com Example]</i>' ); + assert.htmlEqual( + formatParse( 'jquerymsg-wikitext-contents-parsed' ), + '<i><a href="http://example.com">Example</a></i>', + 'Contents of valid tag are treated as wikitext, so external link is parsed' + ); + + mw.messages.set( 'jquerymsg-wikitext-contents-script', '<i><script>Script inside</script></i>' ); + assert.htmlEqual( + formatParse( 'jquerymsg-wikitext-contents-script' ), + '<i><span class="mediaWiki_htmlEmitter"><script>Script inside</script></span></i>', + 'Contents of valid tag are treated as wikitext, so invalid HTML element is treated as text' + ); + + mw.messages.set( 'jquerymsg-unclosed-tag', 'Foo<tag>bar' ); + assert.htmlEqual( + formatParse( 'jquerymsg-unclosed-tag' ), + 'Foo<tag>bar', + 'Nonsupported unclosed tags are escaped' + ); + + mw.messages.set( 'jquerymsg-self-closing-tag', 'Foo<tag/>bar' ); + assert.htmlEqual( + formatParse( 'jquerymsg-self-closing-tag' ), + 'Foo<tag/>bar', + 'Self-closing tags don\'t cause a parse error' + ); +} ); + + QUnit.test( 'Behavior in case of invalid wikitext', 3, function ( assert ) { + mw.messages.set( 'invalid-wikitext', '<b>{{FAIL}}</b>' ); + + this.suppressWarnings(); + var logSpy = this.sandbox.spy( mw.log, 'warn' ); + + assert.equal( + formatParse( 'invalid-wikitext' ), + '<b>{{FAIL}}</b>', + 'Invalid wikitext: \'parse\' format' + ); + + assert.equal( + formatText( 'invalid-wikitext' ), + '<b>{{FAIL}}</b>', + 'Invalid wikitext: \'text\' format' + ); + + assert.equal( logSpy.callCount, 2, 'mw.log.warn calls' ); + } ); + +}( mediaWiki, jQuery ) ); diff --git a/tests/qunit/suites/resources/mediawiki/mediawiki.jscompat.test.js b/tests/qunit/suites/resources/mediawiki/mediawiki.jscompat.test.js new file mode 100644 index 00000000..3328ce3f --- /dev/null +++ b/tests/qunit/suites/resources/mediawiki/mediawiki.jscompat.test.js @@ -0,0 +1,70 @@ +/** + * Some misc JavaScript compatibility tests, + * just to make sure the environments we run in are consistent. + */ +( function ( $ ) { + QUnit.module( 'mediawiki.jscompat', QUnit.newMwEnvironment() ); + + QUnit.test( 'Variable with Unicode letter in name', 3, function ( assert ) { + var orig, ŝablono; + + orig = 'some token'; + ŝablono = orig; + + assert.deepEqual( ŝablono, orig, 'ŝablono' ); + assert.deepEqual( \u015dablono, orig, '\\u015dablono' ); + assert.deepEqual( \u015Dablono, orig, '\\u015Dablono' ); + } ); + + /* + // Not that we need this. ;) + // This fails on IE 6-8 + // Works on IE 9, Firefox 6, Chrome 14 + QUnit.test( 'Keyword workaround: "if" as variable name using Unicode escapes', function ( assert ) { + var orig = "another token"; + \u0069\u0066 = orig; + assert.deepEqual( \u0069\u0066, orig, '\\u0069\\u0066' ); + }); + */ + + /* + // Not that we need this. ;) + // This fails on IE 6-9 + // Works on Firefox 6, Chrome 14 + QUnit.test( 'Keyword workaround: "if" as member variable name using Unicode escapes', function ( assert ) { + var orig = "another token"; + var foo = {}; + foo.\u0069\u0066 = orig; + assert.deepEqual( foo.\u0069\u0066, orig, 'foo.\\u0069\\u0066' ); + }); + */ + + QUnit.test( 'Stripping of single initial newline from textarea\'s literal contents (bug 12130)', function ( assert ) { + var maxn, n, + expected, $textarea; + + maxn = 4; + QUnit.expect( maxn * 2 ); + + function repeat( str, n ) { + var out; + if ( n <= 0 ) { + return ''; + } else { + out = []; + out.length = n + 1; + return out.join( str ); + } + } + + for ( n = 0; n < maxn; n++ ) { + expected = repeat( '\n', n ) + 'some text'; + + $textarea = $( '<textarea>\n' + expected + '</textarea>' ); + assert.equal( $textarea.val(), expected, 'Expecting ' + n + ' newlines (HTML contained ' + (n + 1) + ')' ); + + $textarea = $( '<textarea>' ).val( expected ); + assert.equal( $textarea.val(), expected, 'Expecting ' + n + ' newlines (from DOM set with ' + n + ')' ); + } + } ); +}( jQuery ) ); diff --git a/tests/qunit/suites/resources/mediawiki/mediawiki.language.test.js b/tests/qunit/suites/resources/mediawiki/mediawiki.language.test.js new file mode 100644 index 00000000..16f90df8 --- /dev/null +++ b/tests/qunit/suites/resources/mediawiki/mediawiki.language.test.js @@ -0,0 +1,475 @@ +( function ( mw, $ ) { + 'use strict'; + + QUnit.module( 'mediawiki.language', QUnit.newMwEnvironment( { + setup: function () { + this.liveLangData = mw.language.data.values; + mw.language.data.values = $.extend( true, {}, this.liveLangData ); + }, + teardown: function () { + mw.language.data.values = this.liveLangData; + } + } ) ); + + QUnit.test( 'mw.language getData and setData', 2, function ( assert ) { + mw.language.setData( 'en', 'testkey', 'testvalue' ); + assert.equal( mw.language.getData( 'en', 'testkey' ), 'testvalue', 'Getter setter test for mw.language' ); + assert.equal( mw.language.getData( 'en', 'invalidkey' ), undefined, 'Getter setter test for mw.language with invalid key' ); + } ); + + QUnit.test( 'mw.language.commafy test', 9, function ( assert ) { + // Number grouping patterns are as per http://cldr.unicode.org/translation/number-patterns + assert.equal( mw.language.commafy( 1234.567, '###0.#####' ), '1234.567', 'Pattern with no digit grouping separator defined' ); + assert.equal( mw.language.commafy( 123456789.567, '###0.#####' ), '123456789.567', 'Pattern with no digit grouping seperator defined, bigger decimal part' ); + assert.equal( mw.language.commafy( 0.567, '###0.#####' ), '0.567', 'Decimal part 0' ); + assert.equal( mw.language.commafy( '.567', '###0.#####' ), '0.567', 'Decimal part missing. replace with zero' ); + assert.equal( mw.language.commafy( 1234, '##,#0.#####' ), '12,34', 'Pattern with no fractional part' ); + assert.equal( mw.language.commafy( -1234.567, '###0.#####' ), '-1234.567', 'Negative number' ); + assert.equal( mw.language.commafy( -1234.567, '#,###.00' ), '-1,234.56', 'Fractional part bigger than pattern.' ); + assert.equal( mw.language.commafy( 123456789.567, '###,##0.00' ), '123,456,789.56', 'Decimal part as group of 3' ); + assert.equal( mw.language.commafy( 123456789.567, '###,###,#0.00' ), '1,234,567,89.56', 'Decimal part as group of 3 and last one 2' ); + } ); + + function grammarTest( langCode, test ) { + // The test works only if the content language is opt.language + // because it requires [lang].js to be loaded. + QUnit.test( 'Grammar test for lang=' + langCode, function ( assert ) { + QUnit.expect( test.length ); + + for ( var i = 0; i < test.length; i++ ) { + assert.equal( + mw.language.convertGrammar( test[i].word, test[i].grammarForm ), + test[i].expected, + test[i].description + ); + } + } ); + } + + // These tests run only for the current UI language. + var grammarTests = { + bs: [ + { + word: 'word', + grammarForm: 'instrumental', + expected: 's word', + description: 'Grammar test for instrumental case' + }, + { + word: 'word', + grammarForm: 'lokativ', + expected: 'o word', + description: 'Grammar test for lokativ case' + } + ], + + he: [ + { + word: 'ויקיפדיה', + grammarForm: 'prefixed', + expected: 'וויקיפדיה', + description: 'Duplicate the "Waw" if prefixed' + }, + { + word: 'וולפגנג', + grammarForm: 'prefixed', + expected: 'וולפגנג', + description: 'Duplicate the "Waw" if prefixed, but not if it is already duplicated.' + }, + { + word: 'הקובץ', + grammarForm: 'prefixed', + expected: 'קובץ', + description: 'Remove the "He" if prefixed' + }, + { + word: 'Wikipedia', + grammarForm: 'תחילית', + expected: '־Wikipedia', + description: 'GAdd a hyphen (maqaf) before non-Hebrew letters' + }, + { + word: '1995', + grammarForm: 'תחילית', + expected: '־1995', + description: 'Add a hyphen (maqaf) before numbers' + } + ], + + hsb: [ + { + word: 'word', + grammarForm: 'instrumental', + expected: 'z word', + description: 'Grammar test for instrumental case' + }, + { + word: 'word', + grammarForm: 'lokatiw', + expected: 'wo word', + description: 'Grammar test for lokatiw case' + } + ], + + dsb: [ + { + word: 'word', + grammarForm: 'instrumental', + expected: 'z word', + description: 'Grammar test for instrumental case' + }, + { + word: 'word', + grammarForm: 'lokatiw', + expected: 'wo word', + description: 'Grammar test for lokatiw case' + } + ], + + hy: [ + { + word: 'Մաունա', + grammarForm: 'genitive', + expected: 'Մաունայի', + description: 'Grammar test for genitive case' + }, + { + word: 'հետո', + grammarForm: 'genitive', + expected: 'հետոյի', + description: 'Grammar test for genitive case' + }, + { + word: 'գիրք', + grammarForm: 'genitive', + expected: 'գրքի', + description: 'Grammar test for genitive case' + }, + { + word: 'ժամանակի', + grammarForm: 'genitive', + expected: 'ժամանակիի', + description: 'Grammar test for genitive case' + } + ], + + fi: [ + { + word: 'talo', + grammarForm: 'genitive', + expected: 'talon', + description: 'Grammar test for genitive case' + }, + { + word: 'linux', + grammarForm: 'genitive', + expected: 'linuxin', + description: 'Grammar test for genitive case' + }, + { + word: 'talo', + grammarForm: 'elative', + expected: 'talosta', + description: 'Grammar test for elative case' + }, + { + word: 'pastöroitu', + grammarForm: 'partitive', + expected: 'pastöroitua', + description: 'Grammar test for partitive case' + }, + { + word: 'talo', + grammarForm: 'partitive', + expected: 'taloa', + description: 'Grammar test for partitive case' + }, + { + word: 'talo', + grammarForm: 'illative', + expected: 'taloon', + description: 'Grammar test for illative case' + }, + { + word: 'linux', + grammarForm: 'inessive', + expected: 'linuxissa', + description: 'Grammar test for inessive case' + } + ], + + ru: [ + { + word: 'тесть', + grammarForm: 'genitive', + expected: 'тестя', + description: 'Grammar test for genitive case, тесть -> тестя' + }, + { + word: 'привилегия', + grammarForm: 'genitive', + expected: 'привилегии', + description: 'Grammar test for genitive case, привилегия -> привилегии' + }, + { + word: 'установка', + grammarForm: 'genitive', + expected: 'установки', + description: 'Grammar test for genitive case, установка -> установки' + }, + { + word: 'похоти', + grammarForm: 'genitive', + expected: 'похотей', + description: 'Grammar test for genitive case, похоти -> похотей' + }, + { + word: 'доводы', + grammarForm: 'genitive', + expected: 'доводов', + description: 'Grammar test for genitive case, доводы -> доводов' + }, + { + word: 'песчаник', + grammarForm: 'genitive', + expected: 'песчаника', + description: 'Grammar test for genitive case, песчаник -> песчаника' + }, + { + word: 'данные', + grammarForm: 'genitive', + expected: 'данных', + description: 'Grammar test for genitive case, данные -> данных' + }, + { + word: 'тесть', + grammarForm: 'prepositional', + expected: 'тесте', + description: 'Grammar test for prepositional case, тесть -> тесте' + }, + { + word: 'привилегия', + grammarForm: 'prepositional', + expected: 'привилегии', + description: 'Grammar test for prepositional case, привилегия -> привилегии' + }, + { + word: 'установка', + grammarForm: 'prepositional', + expected: 'установке', + description: 'Grammar test for prepositional case, установка -> установке' + }, + { + word: 'похоти', + grammarForm: 'prepositional', + expected: 'похотях', + description: 'Grammar test for prepositional case, похоти -> похотях' + }, + { + word: 'доводы', + grammarForm: 'prepositional', + expected: 'доводах', + description: 'Grammar test for prepositional case, доводы -> доводах' + }, + { + word: 'Викисклад', + grammarForm: 'prepositional', + expected: 'Викискладе', + description: 'Grammar test for prepositional case, Викисклад -> Викискладе' + }, + { + word: 'Викисклад', + grammarForm: 'genitive', + expected: 'Викисклада', + description: 'Grammar test for genitive case, Викисклад -> Викисклада' + }, + { + word: 'песчаник', + grammarForm: 'prepositional', + expected: 'песчанике', + description: 'Grammar test for prepositional case, песчаник -> песчанике' + }, + { + word: 'данные', + grammarForm: 'prepositional', + expected: 'данных', + description: 'Grammar test for prepositional case, данные -> данных' + } + ], + + hu: [ + { + word: 'Wikipédiá', + grammarForm: 'rol', + expected: 'Wikipédiáról', + description: 'Grammar test for rol case' + }, + { + word: 'Wikipédiá', + grammarForm: 'ba', + expected: 'Wikipédiába', + description: 'Grammar test for ba case' + }, + { + word: 'Wikipédiá', + grammarForm: 'k', + expected: 'Wikipédiák', + description: 'Grammar test for k case' + } + ], + + ga: [ + { + word: 'an Domhnach', + grammarForm: 'ainmlae', + expected: 'Dé Domhnaigh', + description: 'Grammar test for ainmlae case' + }, + { + word: 'an Luan', + grammarForm: 'ainmlae', + expected: 'Dé Luain', + description: 'Grammar test for ainmlae case' + }, + { + word: 'an Satharn', + grammarForm: 'ainmlae', + expected: 'Dé Sathairn', + description: 'Grammar test for ainmlae case' + } + ], + + uk: [ + { + word: 'тесть', + grammarForm: 'genitive', + expected: 'тестя', + description: 'Grammar test for genitive case' + }, + { + word: 'Вікіпедія', + grammarForm: 'genitive', + expected: 'Вікіпедії', + description: 'Grammar test for genitive case' + }, + { + word: 'установка', + grammarForm: 'genitive', + expected: 'установки', + description: 'Grammar test for genitive case' + }, + { + word: 'похоти', + grammarForm: 'genitive', + expected: 'похотей', + description: 'Grammar test for genitive case' + }, + { + word: 'доводы', + grammarForm: 'genitive', + expected: 'доводов', + description: 'Grammar test for genitive case' + }, + { + word: 'песчаник', + grammarForm: 'genitive', + expected: 'песчаника', + description: 'Grammar test for genitive case' + }, + { + word: 'Вікіпедія', + grammarForm: 'accusative', + expected: 'Вікіпедію', + description: 'Grammar test for accusative case' + } + ], + + sl: [ + { + word: 'word', + grammarForm: 'orodnik', + expected: 'z word', + description: 'Grammar test for orodnik case' + }, + { + word: 'word', + grammarForm: 'mestnik', + expected: 'o word', + description: 'Grammar test for mestnik case' + } + ], + + os: [ + { + word: 'бæстæ', + grammarForm: 'genitive', + expected: 'бæсты', + description: 'Grammar test for genitive case' + }, + { + word: 'бæстæ', + grammarForm: 'allative', + expected: 'бæстæм', + description: 'Grammar test for allative case' + }, + { + word: 'Тигр', + grammarForm: 'dative', + expected: 'Тигрæн', + description: 'Grammar test for dative case' + }, + { + word: 'цъити', + grammarForm: 'dative', + expected: 'цъитийæн', + description: 'Grammar test for dative case' + }, + { + word: 'лæппу', + grammarForm: 'genitive', + expected: 'лæппуйы', + description: 'Grammar test for genitive case' + }, + { + word: '2011', + grammarForm: 'equative', + expected: '2011-ау', + description: 'Grammar test for equative case' + } + ], + + la: [ + { + word: 'Translatio', + grammarForm: 'genitive', + expected: 'Translationis', + description: 'Grammar test for genitive case' + }, + { + word: 'Translatio', + grammarForm: 'accusative', + expected: 'Translationem', + description: 'Grammar test for accusative case' + }, + { + word: 'Translatio', + grammarForm: 'ablative', + expected: 'Translatione', + description: 'Grammar test for ablative case' + } + ] + }; + + $.each( grammarTests, function ( langCode, test ) { + if ( langCode === mw.config.get( 'wgUserLanguage' ) ) { + grammarTest( langCode, test ); + } + } ); + + QUnit.test( 'List to text test', 4, function ( assert ) { + assert.equal( mw.language.listToText( [] ), '', 'Blank list' ); + assert.equal( mw.language.listToText( ['a'] ), 'a', 'Single item' ); + assert.equal( mw.language.listToText( ['a', 'b'] ), 'a and b', 'Two items' ); + assert.equal( mw.language.listToText( ['a', 'b', 'c'] ), 'a, b and c', 'More than two items' ); + } ); +}( mediaWiki, jQuery ) ); diff --git a/tests/qunit/suites/resources/mediawiki/mediawiki.test.js b/tests/qunit/suites/resources/mediawiki/mediawiki.test.js new file mode 100644 index 00000000..7e0ee917 --- /dev/null +++ b/tests/qunit/suites/resources/mediawiki/mediawiki.test.js @@ -0,0 +1,985 @@ +/*jshint -W024 */ +( function ( mw, $ ) { + var specialCharactersPageName; + + // Since QUnitTestResources.php loads both mediawiki and mediawiki.jqueryMsg as + // dependencies, this only tests the monkey-patched behavior with the two of them combined. + + // See mediawiki.jqueryMsg.test.js for unit tests for jqueryMsg-specific functionality. + + QUnit.module( 'mediawiki', QUnit.newMwEnvironment( { + setup: function () { + specialCharactersPageName = '"Who" wants to be a millionaire & live on \'Exotic Island\'?'; + }, + config: { + wgArticlePath: '/wiki/$1', + + // For formatnum tests + wgUserLanguage: 'en' + }, + // Messages used in multiple tests + messages: { + 'other-message': 'Other Message', + 'mediawiki-test-pagetriage-del-talk-page-notify-summary': 'Notifying author of deletion nomination for [[$1]]', + 'gender-plural-msg': '{{GENDER:$1|he|she|they}} {{PLURAL:$2|is|are}} awesome', + 'grammar-msg': 'Przeszukaj {{GRAMMAR:grammar_case_foo|{{SITENAME}}}}', + 'formatnum-msg': '{{formatnum:$1}}', + 'int-msg': 'Some {{int:other-message}}', + 'mediawiki-test-version-entrypoints-index-php': '[https://www.mediawiki.org/wiki/Manual:index.php index.php]', + 'external-link-replace': 'Foo [$1 bar]' + } + } ) ); + + mw.loader.addSource( + 'testloader', + QUnit.fixurl( mw.config.get( 'wgScriptPath' ) + '/tests/qunit/data/load.mock.php' ) + ); + + QUnit.test( 'Initial check', 8, function ( assert ) { + assert.ok( window.jQuery, 'jQuery defined' ); + assert.ok( window.$, '$ defined' ); + assert.strictEqual( window.$, window.jQuery, '$ alias to jQuery' ); + + this.suppressWarnings(); + assert.ok( window.$j, '$j defined' ); + assert.strictEqual( window.$j, window.jQuery, '$j alias to jQuery' ); + this.restoreWarnings(); + + // window.mw and window.mediaWiki are not deprecated, but for some reason + // PhantomJS is triggerring the accessors on all mw.* properties in this test, + // and with that lots of unrelated deprecation notices. + this.suppressWarnings(); + assert.ok( window.mediaWiki, 'mediaWiki defined' ); + assert.ok( window.mw, 'mw defined' ); + assert.strictEqual( window.mw, window.mediaWiki, 'mw alias to mediaWiki' ); + this.restoreWarnings(); + } ); + + QUnit.test( 'mw.Map', 28, function ( assert ) { + var arry, conf, funky, globalConf, nummy, someValues; + + conf = new mw.Map(); + // Dummy variables + funky = function () {}; + arry = []; + nummy = 7; + + // Single get and set + + assert.strictEqual( conf.set( 'foo', 'Bar' ), true, 'Map.set returns boolean true if a value was set for a valid key string' ); + assert.equal( conf.get( 'foo' ), 'Bar', 'Map.get returns a single value value correctly' ); + + assert.strictEqual( conf.get( 'example' ), null, 'Map.get returns null if selection was a string and the key was not found' ); + assert.strictEqual( conf.get( 'example', arry ), arry, 'Map.get returns fallback by reference if the key was not found' ); + assert.strictEqual( conf.get( 'example', undefined ), undefined, 'Map.get supports `undefined` as fallback instead of `null`' ); + + assert.strictEqual( conf.get( 'constructor' ), null, 'Map.get does not look at Object.prototype of internal storage (constructor)' ); + assert.strictEqual( conf.get( 'hasOwnProperty' ), null, 'Map.get does not look at Object.prototype of internal storage (hasOwnProperty)' ); + + conf.set( 'hasOwnProperty', function () { return true; } ); + assert.strictEqual( conf.get( 'example', 'missing' ), 'missing', 'Map.get uses neutral hasOwnProperty method (positive)' ); + + conf.set( 'example', 'Foo' ); + conf.set( 'hasOwnProperty', function () { return false; } ); + assert.strictEqual( conf.get( 'example' ), 'Foo', 'Map.get uses neutral hasOwnProperty method (negative)' ); + + assert.strictEqual( conf.set( 'constructor', 42 ), true, 'Map.set for key "constructor"' ); + assert.strictEqual( conf.get( 'constructor' ), 42, 'Map.get for key "constructor"' ); + + assert.strictEqual( conf.set( 'ImUndefined', undefined ), true, 'Map.set allows setting value to `undefined`' ); + assert.equal( conf.get( 'ImUndefined', 'fallback' ), undefined, 'Map.get supports retreiving value of `undefined`' ); + + assert.strictEqual( conf.set( funky, 'Funky' ), false, 'Map.set returns boolean false if key was invalid (Function)' ); + assert.strictEqual( conf.set( arry, 'Arry' ), false, 'Map.set returns boolean false if key was invalid (Array)' ); + assert.strictEqual( conf.set( nummy, 'Nummy' ), false, 'Map.set returns boolean false if key was invalid (Number)' ); + + assert.strictEqual( conf.get( funky ), null, 'Map.get ruturns null if selection was invalid (Function)' ); + assert.strictEqual( conf.get( nummy ), null, 'Map.get ruturns null if selection was invalid (Number)' ); + + conf.set( String( nummy ), 'I used to be a number' ); + + assert.strictEqual( conf.exists( 'doesNotExist' ), false, 'Map.exists where property does not exist' ); + assert.strictEqual( conf.exists( 'ImUndefined' ), true, 'Map.exists where value is `undefined`' ); + assert.strictEqual( conf.exists( nummy ), false, 'Map.exists where key is invalid but looks like an existing key' ); + + // Multiple values at once + someValues = { + 'foo': 'bar', + 'lorem': 'ipsum', + 'MediaWiki': true + }; + assert.strictEqual( conf.set( someValues ), true, 'Map.set returns boolean true if multiple values were set by passing an object' ); + assert.deepEqual( conf.get( ['foo', 'lorem'] ), { + 'foo': 'bar', + 'lorem': 'ipsum' + }, 'Map.get returns multiple values correctly as an object' ); + + assert.deepEqual( conf, new mw.Map( conf.values ), 'new mw.Map maps over existing values-bearing object' ); + + assert.deepEqual( conf.get( ['foo', 'notExist'] ), { + 'foo': 'bar', + 'notExist': null + }, 'Map.get return includes keys that were not found as null values' ); + + // Interacting with globals and accessing the values object + assert.strictEqual( conf.get(), conf.values, 'Map.get returns the entire values object by reference (if called without arguments)' ); + + conf.set( 'globalMapChecker', 'Hi' ); + + assert.ok( 'globalMapChecker' in window === false, 'new mw.Map did not store its values in the global window object by default' ); + + globalConf = new mw.Map( true ); + globalConf.set( 'anotherGlobalMapChecker', 'Hello' ); + + assert.ok( 'anotherGlobalMapChecker' in window, 'new mw.Map( true ) did store its values in the global window object' ); + + // Whitelist this global variable for QUnit's 'noglobal' mode + if ( QUnit.config.noglobals ) { + QUnit.config.pollution.push( 'anotherGlobalMapChecker' ); + } + } ); + + QUnit.test( 'mw.config', 1, function ( assert ) { + assert.ok( mw.config instanceof mw.Map, 'mw.config instance of mw.Map' ); + } ); + + QUnit.test( 'mw.message & mw.messages', 100, function ( assert ) { + var goodbye, hello; + + // Convenience method for asserting the same result for multiple formats + function assertMultipleFormats( messageArguments, formats, expectedResult, assertMessage ) { + var len = formats.length, format, i; + for ( i = 0; i < len; i++ ) { + format = formats[i]; + assert.equal( mw.message.apply( null, messageArguments )[format](), expectedResult, assertMessage + ' when format is ' + format ); + } + } + + assert.ok( mw.messages, 'messages defined' ); + assert.ok( mw.messages instanceof mw.Map, 'mw.messages instance of mw.Map' ); + assert.ok( mw.messages.set( 'hello', 'Hello <b>awesome</b> world' ), 'mw.messages.set: Register' ); + + hello = mw.message( 'hello' ); + + // https://bugzilla.wikimedia.org/show_bug.cgi?id=44459 + assert.equal( hello.format, 'text', 'Message property "format" defaults to "text"' ); + + assert.strictEqual( hello.map, mw.messages, 'Message property "map" defaults to the global instance in mw.messages' ); + assert.equal( hello.key, 'hello', 'Message property "key" (currect key)' ); + assert.deepEqual( hello.parameters, [], 'Message property "parameters" defaults to an empty array' ); + + // Todo + assert.ok( hello.params, 'Message prototype "params"' ); + + hello.format = 'plain'; + assert.equal( hello.toString(), 'Hello <b>awesome</b> world', 'Message.toString returns the message as a string with the current "format"' ); + + assert.equal( hello.escaped(), 'Hello <b>awesome</b> world', 'Message.escaped returns the escaped message' ); + assert.equal( hello.format, 'escaped', 'Message.escaped correctly updated the "format" property' ); + + assert.ok( mw.messages.set( 'multiple-curly-brace', '"{{SITENAME}}" is the home of {{int:other-message}}' ), 'mw.messages.set: Register' ); + assertMultipleFormats( ['multiple-curly-brace'], ['text', 'parse'], '"' + mw.config.get( 'wgSiteName') + '" is the home of Other Message', 'Curly brace format works correctly' ); + assert.equal( mw.message( 'multiple-curly-brace' ).plain(), mw.messages.get( 'multiple-curly-brace' ), 'Plain format works correctly for curly brace message' ); + assert.equal( mw.message( 'multiple-curly-brace' ).escaped(), mw.html.escape( '"' + mw.config.get( 'wgSiteName') + '" is the home of Other Message' ), 'Escaped format works correctly for curly brace message' ); + + assert.ok( mw.messages.set( 'multiple-square-brackets-and-ampersand', 'Visit the [[Project:Community portal|community portal]] & [[Project:Help desk|help desk]]' ), 'mw.messages.set: Register' ); + assertMultipleFormats( ['multiple-square-brackets-and-ampersand'], ['plain', 'text'], mw.messages.get( 'multiple-square-brackets-and-ampersand' ), 'Square bracket message is not processed' ); + assert.equal( mw.message( 'multiple-square-brackets-and-ampersand' ).escaped(), 'Visit the [[Project:Community portal|community portal]] & [[Project:Help desk|help desk]]', 'Escaped format works correctly for square bracket message' ); + assert.htmlEqual( mw.message( 'multiple-square-brackets-and-ampersand' ).parse(), 'Visit the ' + + '<a title="Project:Community portal" href="/wiki/Project:Community_portal">community portal</a>' + + ' & <a title="Project:Help desk" href="/wiki/Project:Help_desk">help desk</a>', 'Internal links work with parse' ); + + assertMultipleFormats( ['mediawiki-test-version-entrypoints-index-php'], ['plain', 'text', 'escaped'], mw.messages.get( 'mediawiki-test-version-entrypoints-index-php' ), 'External link markup is unprocessed' ); + assert.htmlEqual( mw.message( 'mediawiki-test-version-entrypoints-index-php' ).parse(), '<a href="https://www.mediawiki.org/wiki/Manual:index.php">index.php</a>', 'External link works correctly in parse mode' ); + + assertMultipleFormats( ['external-link-replace', 'http://example.org/?x=y&z'], ['plain', 'text'], 'Foo [http://example.org/?x=y&z bar]', 'Parameters are substituted but external link is not processed' ); + assert.equal( mw.message( 'external-link-replace', 'http://example.org/?x=y&z' ).escaped(), 'Foo [http://example.org/?x=y&z bar]', 'In escaped mode, parameters are substituted and ampersand is escaped, but external link is not processed' ); + assert.htmlEqual( mw.message( 'external-link-replace', 'http://example.org/?x=y&z' ).parse(), 'Foo <a href="http://example.org/?x=y&z">bar</a>', 'External link with replacement works in parse mode without double-escaping' ); + + hello.parse(); + assert.equal( hello.format, 'parse', 'Message.parse correctly updated the "format" property' ); + + hello.plain(); + assert.equal( hello.format, 'plain', 'Message.plain correctly updated the "format" property' ); + + hello.text(); + assert.equal( hello.format, 'text', 'Message.text correctly updated the "format" property' ); + + assert.strictEqual( hello.exists(), true, 'Message.exists returns true for existing messages' ); + + goodbye = mw.message( 'goodbye' ); + assert.strictEqual( goodbye.exists(), false, 'Message.exists returns false for nonexistent messages' ); + + assertMultipleFormats( ['goodbye'], ['plain', 'text'], '<goodbye>', 'Message.toString returns <key> if key does not exist' ); + // bug 30684 + assertMultipleFormats( ['goodbye'], ['parse', 'escaped'], '<goodbye>', 'Message.toString returns properly escaped <key> if key does not exist' ); + + assert.ok( mw.messages.set( 'plural-test-msg', 'There {{PLURAL:$1|is|are}} $1 {{PLURAL:$1|result|results}}' ), 'mw.messages.set: Register' ); + assertMultipleFormats( ['plural-test-msg', 6], ['text', 'parse', 'escaped'], 'There are 6 results', 'plural get resolved' ); + assert.equal( mw.message( 'plural-test-msg', 6 ).plain(), 'There {{PLURAL:6|is|are}} 6 {{PLURAL:6|result|results}}', 'Parameter is substituted but plural is not resolved in plain' ); + + assert.ok( mw.messages.set( 'plural-test-msg-explicit', 'There {{plural:$1|is one car|are $1 cars|0=are no cars|12=are a dozen cars}}' ), 'mw.messages.set: Register message with explicit plural forms' ); + assertMultipleFormats( ['plural-test-msg-explicit', 12], ['text', 'parse', 'escaped'], 'There are a dozen cars', 'explicit plural get resolved' ); + + assert.ok( mw.messages.set( 'plural-test-msg-explicit-beginning', 'Basket has {{plural:$1|0=no eggs|12=a dozen eggs|6=half a dozen eggs|one egg|$1 eggs}}' ), 'mw.messages.set: Register message with explicit plural forms' ); + assertMultipleFormats( ['plural-test-msg-explicit-beginning', 1], ['text', 'parse', 'escaped'], 'Basket has one egg', 'explicit plural given at beginning get resolved for singular' ); + assertMultipleFormats( ['plural-test-msg-explicit-beginning', 4], ['text', 'parse', 'escaped'], 'Basket has 4 eggs', 'explicit plural given at beginning get resolved for plural' ); + assertMultipleFormats( ['plural-test-msg-explicit-beginning', 6], ['text', 'parse', 'escaped'], 'Basket has half a dozen eggs', 'explicit plural given at beginning get resolved for 6' ); + assertMultipleFormats( ['plural-test-msg-explicit-beginning', 0], ['text', 'parse', 'escaped'], 'Basket has no eggs', 'explicit plural given at beginning get resolved for 0' ); + + assertMultipleFormats( ['mediawiki-test-pagetriage-del-talk-page-notify-summary'], ['plain', 'text'], mw.messages.get( 'mediawiki-test-pagetriage-del-talk-page-notify-summary' ), 'Double square brackets with no parameters unchanged' ); + + assertMultipleFormats( ['mediawiki-test-pagetriage-del-talk-page-notify-summary', specialCharactersPageName], ['plain', 'text'], 'Notifying author of deletion nomination for [[' + specialCharactersPageName + ']]', 'Double square brackets with one parameter' ); + + assert.equal( mw.message( 'mediawiki-test-pagetriage-del-talk-page-notify-summary', specialCharactersPageName ).escaped(), 'Notifying author of deletion nomination for [[' + mw.html.escape( specialCharactersPageName ) + ']]', 'Double square brackets with one parameter, when escaped' ); + + assert.ok( mw.messages.set( 'mediawiki-test-categorytree-collapse-bullet', '[<b>−</b>]' ), 'mw.messages.set: Register' ); + assert.equal( mw.message( 'mediawiki-test-categorytree-collapse-bullet' ).plain(), mw.messages.get( 'mediawiki-test-categorytree-collapse-bullet' ), 'Single square brackets unchanged in plain mode' ); + + assert.ok( mw.messages.set( 'mediawiki-test-wikieditor-toolbar-help-content-signature-result', '<a href=\'#\' title=\'{{#special:mypage}}\'>Username</a> (<a href=\'#\' title=\'{{#special:mytalk}}\'>talk</a>)' ), 'mw.messages.set: Register' ); + assert.equal( mw.message( 'mediawiki-test-wikieditor-toolbar-help-content-signature-result' ).plain(), mw.messages.get( 'mediawiki-test-wikieditor-toolbar-help-content-signature-result' ), 'HTML message with curly braces is not changed in plain mode' ); + + assertMultipleFormats( ['gender-plural-msg', 'male', 1], ['text', 'parse', 'escaped'], 'he is awesome', 'Gender and plural are resolved' ); + assert.equal( mw.message( 'gender-plural-msg', 'male', 1 ).plain(), '{{GENDER:male|he|she|they}} {{PLURAL:1|is|are}} awesome', 'Parameters are substituted, but gender and plural are not resolved in plain mode' ); + + assert.equal( mw.message( 'grammar-msg' ).plain(), mw.messages.get( 'grammar-msg' ), 'Grammar is not resolved in plain mode' ); + assertMultipleFormats( ['grammar-msg'], ['text', 'parse'], 'Przeszukaj ' + mw.config.get( 'wgSiteName' ), 'Grammar is resolved' ); + assert.equal( mw.message( 'grammar-msg' ).escaped(), 'Przeszukaj ' + mw.html.escape( mw.config.get( 'wgSiteName' ) ), 'Grammar is resolved in escaped mode' ); + + assertMultipleFormats( ['formatnum-msg', '987654321.654321'], ['text', 'parse', 'escaped'], '987,654,321.654', 'formatnum is resolved' ); + assert.equal( mw.message( 'formatnum-msg' ).plain(), mw.messages.get( 'formatnum-msg' ), 'formatnum is not resolved in plain mode' ); + + assertMultipleFormats( ['int-msg'], ['text', 'parse', 'escaped'], 'Some Other Message', 'int is resolved' ); + assert.equal( mw.message( 'int-msg' ).plain(), mw.messages.get( 'int-msg' ), 'int is not resolved in plain mode' ); + + assert.ok( mw.messages.set( 'mediawiki-italics-msg', '<i>Very</i> important' ), 'mw.messages.set: Register' ); + assertMultipleFormats( ['mediawiki-italics-msg'], ['plain', 'text', 'parse'], mw.messages.get( 'mediawiki-italics-msg' ), 'Simple italics unchanged' ); + assert.htmlEqual( + mw.message( 'mediawiki-italics-msg' ).escaped(), + '<i>Very</i> important', + 'Italics are escaped in escaped mode' + ); + + assert.ok( mw.messages.set( 'mediawiki-italics-with-link', 'An <i>italicized [[link|wiki-link]]</i>' ), 'mw.messages.set: Register' ); + assertMultipleFormats( ['mediawiki-italics-with-link'], ['plain', 'text'], mw.messages.get( 'mediawiki-italics-with-link' ), 'Italics with link unchanged' ); + assert.htmlEqual( + mw.message( 'mediawiki-italics-with-link' ).escaped(), + 'An <i>italicized [[link|wiki-link]]</i>', + 'Italics and link unchanged except for escaping in escaped mode' + ); + assert.htmlEqual( + mw.message( 'mediawiki-italics-with-link' ).parse(), + 'An <i>italicized <a title="link" href="' + mw.util.getUrl( 'link' ) + '">wiki-link</i>', + 'Italics with link inside in parse mode' + ); + + assert.ok( mw.messages.set( 'mediawiki-script-msg', '<script >alert( "Who put this script here?" );</script>' ), 'mw.messages.set: Register' ); + assertMultipleFormats( ['mediawiki-script-msg'], ['plain', 'text'], mw.messages.get( 'mediawiki-script-msg' ), 'Script unchanged' ); + assert.htmlEqual( + mw.message( 'mediawiki-script-msg' ).escaped(), + '<script >alert( "Who put this script here?" );</script>', + 'Script escaped when using escaped format' + ); + assert.htmlEqual( + mw.message( 'mediawiki-script-msg' ).parse(), + '<script >alert( "Who put this script here?" );</script>', + 'Script escaped when using parse format' + ); + + } ); + + QUnit.test( 'mw.msg', 14, function ( assert ) { + assert.ok( mw.messages.set( 'hello', 'Hello <b>awesome</b> world' ), 'mw.messages.set: Register' ); + assert.equal( mw.msg( 'hello' ), 'Hello <b>awesome</b> world', 'Gets message with default options (existing message)' ); + assert.equal( mw.msg( 'goodbye' ), '<goodbye>', 'Gets message with default options (nonexistent message)' ); + + assert.ok( mw.messages.set( 'plural-item', 'Found $1 {{PLURAL:$1|item|items}}' ), 'mw.messages.set: Register' ); + assert.equal( mw.msg( 'plural-item', 5 ), 'Found 5 items', 'Apply plural for count 5' ); + assert.equal( mw.msg( 'plural-item', 0 ), 'Found 0 items', 'Apply plural for count 0' ); + assert.equal( mw.msg( 'plural-item', 1 ), 'Found 1 item', 'Apply plural for count 1' ); + + assert.equal( mw.msg( 'mediawiki-test-pagetriage-del-talk-page-notify-summary', specialCharactersPageName ), 'Notifying author of deletion nomination for [[' + specialCharactersPageName + ']]', 'Double square brackets in mw.msg one parameter' ); + + assert.equal( mw.msg( 'gender-plural-msg', 'male', 1 ), 'he is awesome', 'Gender test for male, plural count 1' ); + assert.equal( mw.msg( 'gender-plural-msg', 'female', '1' ), 'she is awesome', 'Gender test for female, plural count 1' ); + assert.equal( mw.msg( 'gender-plural-msg', 'unknown', 10 ), 'they are awesome', 'Gender test for neutral, plural count 10' ); + + assert.equal( mw.msg( 'grammar-msg' ), 'Przeszukaj ' + mw.config.get( 'wgSiteName' ), 'Grammar is resolved' ); + + assert.equal( mw.msg( 'formatnum-msg', '987654321.654321' ), '987,654,321.654', 'formatnum is resolved' ); + + assert.equal( mw.msg( 'int-msg' ), 'Some Other Message', 'int is resolved' ); + } ); + + /** + * The sync style load test (for @import). This is, in a way, also an open bug for + * ResourceLoader ("execute js after styles are loaded"), but browsers don't offer a + * way to get a callback from when a stylesheet is loaded (that is, including any + * @import rules inside). To work around this, we'll have a little time loop to check + * if the styles apply. + * Note: This test originally used new Image() and onerror to get a callback + * when the url is loaded, but that is fragile since it doesn't monitor the + * same request as the css @import, and Safari 4 has issues with + * onerror/onload not being fired at all in weird cases like this. + */ + function assertStyleAsync( assert, $element, prop, val, fn ) { + var styleTestStart, + el = $element.get( 0 ), + styleTestTimeout = ( QUnit.config.testTimeout || 5000 ) - 200; + + function isCssImportApplied() { + // Trigger reflow, repaint, redraw, whatever (cross-browser) + var x = $element.css( 'height' ); + x = el.innerHTML; + el.className = el.className; + x = document.documentElement.clientHeight; + + return $element.css( prop ) === val; + } + + function styleTestLoop() { + var styleTestSince = new Date().getTime() - styleTestStart; + // If it is passing or if we timed out, run the real test and stop the loop + if ( isCssImportApplied() || styleTestSince > styleTestTimeout ) { + assert.equal( $element.css( prop ), val, + 'style "' + prop + ': ' + val + '" from url is applied (after ' + styleTestSince + 'ms)' + ); + + if ( fn ) { + fn(); + } + + return; + } + // Otherwise, keep polling + setTimeout( styleTestLoop, 150 ); + } + + // Start the loop + styleTestStart = new Date().getTime(); + styleTestLoop(); + } + + function urlStyleTest( selector, prop, val ) { + return QUnit.fixurl( + mw.config.get( 'wgScriptPath' ) + + '/tests/qunit/data/styleTest.css.php?' + + $.param( { + selector: selector, + prop: prop, + val: val + } ) + ); + } + + QUnit.asyncTest( 'mw.loader', 2, function ( assert ) { + var isAwesomeDone; + + mw.loader.testCallback = function () { + QUnit.start(); + assert.strictEqual( isAwesomeDone, undefined, 'Implementing module is.awesome: isAwesomeDone should still be undefined' ); + isAwesomeDone = true; + }; + + mw.loader.implement( 'test.callback', [QUnit.fixurl( mw.config.get( 'wgScriptPath' ) + '/tests/qunit/data/callMwLoaderTestCallback.js' )], {}, {} ); + + mw.loader.using( 'test.callback', function () { + + // /sample/awesome.js declares the "mw.loader.testCallback" function + // which contains a call to start() and ok() + assert.strictEqual( isAwesomeDone, true, 'test.callback module should\'ve caused isAwesomeDone to be true' ); + delete mw.loader.testCallback; + + }, function () { + QUnit.start(); + assert.ok( false, 'Error callback fired while loader.using "test.callback" module' ); + } ); + } ); + + QUnit.asyncTest( 'mw.loader.using( .. ).promise', 2, function ( assert ) { + var isAwesomeDone; + + mw.loader.testCallback = function () { + QUnit.start(); + assert.strictEqual( isAwesomeDone, undefined, 'Implementing module is.awesome: isAwesomeDone should still be undefined' ); + isAwesomeDone = true; + }; + + mw.loader.implement( 'test.promise', [QUnit.fixurl( mw.config.get( 'wgScriptPath' ) + '/tests/qunit/data/callMwLoaderTestCallback.js' )], {}, {} ); + + mw.loader.using( 'test.promise' ) + .done( function () { + + // /sample/awesome.js declares the "mw.loader.testCallback" function + // which contains a call to start() and ok() + assert.strictEqual( isAwesomeDone, true, 'test.promise module should\'ve caused isAwesomeDone to be true' ); + delete mw.loader.testCallback; + + } ) + .fail( function () { + QUnit.start(); + assert.ok( false, 'Error callback fired while loader.using "test.promise" module' ); + } ); + } ); + + QUnit.asyncTest( 'mw.loader.implement( styles={ "css": [text, ..] } )', 2, function ( assert ) { + var $element = $( '<div class="mw-test-implement-a"></div>' ).appendTo( '#qunit-fixture' ); + + assert.notEqual( + $element.css( 'float' ), + 'right', + 'style is clear' + ); + + mw.loader.implement( + 'test.implement.a', + function () { + assert.equal( + $element.css( 'float' ), + 'right', + 'style is applied' + ); + QUnit.start(); + }, + { + 'all': '.mw-test-implement-a { float: right; }' + }, + {} + ); + + mw.loader.load( [ + 'test.implement.a' + ] ); + } ); + + QUnit.asyncTest( 'mw.loader.implement( styles={ "url": { <media>: [url, ..] } } )', 7, function ( assert ) { + var $element1 = $( '<div class="mw-test-implement-b1"></div>' ).appendTo( '#qunit-fixture' ), + $element2 = $( '<div class="mw-test-implement-b2"></div>' ).appendTo( '#qunit-fixture' ), + $element3 = $( '<div class="mw-test-implement-b3"></div>' ).appendTo( '#qunit-fixture' ); + + assert.notEqual( + $element1.css( 'text-align' ), + 'center', + 'style is clear' + ); + assert.notEqual( + $element2.css( 'float' ), + 'left', + 'style is clear' + ); + assert.notEqual( + $element3.css( 'text-align' ), + 'right', + 'style is clear' + ); + + mw.loader.implement( + 'test.implement.b', + function () { + // Note: QUnit.start() must only be called when the entire test is + // complete. So, make sure that we don't start until *both* + // assertStyleAsync calls have completed. + var pending = 2; + assertStyleAsync( assert, $element2, 'float', 'left', function () { + assert.notEqual( $element1.css( 'text-align' ), 'center', 'print style is not applied' ); + + pending--; + if ( pending === 0 ) { + QUnit.start(); + } + } ); + assertStyleAsync( assert, $element3, 'float', 'right', function () { + assert.notEqual( $element1.css( 'text-align' ), 'center', 'print style is not applied' ); + + pending--; + if ( pending === 0 ) { + QUnit.start(); + } + } ); + }, + { + 'url': { + 'print': [urlStyleTest( '.mw-test-implement-b1', 'text-align', 'center' )], + 'screen': [ + // bug 40834: Make sure it actually works with more than 1 stylesheet reference + urlStyleTest( '.mw-test-implement-b2', 'float', 'left' ), + urlStyleTest( '.mw-test-implement-b3', 'float', 'right' ) + ] + } + }, + {} + ); + + mw.loader.load( [ + 'test.implement.b' + ] ); + } ); + + // Backwards compatibility + QUnit.asyncTest( 'mw.loader.implement( styles={ <media>: text } ) (back-compat)', 2, function ( assert ) { + var $element = $( '<div class="mw-test-implement-c"></div>' ).appendTo( '#qunit-fixture' ); + + assert.notEqual( + $element.css( 'float' ), + 'right', + 'style is clear' + ); + + mw.loader.implement( + 'test.implement.c', + function () { + assert.equal( + $element.css( 'float' ), + 'right', + 'style is applied' + ); + QUnit.start(); + }, + { + 'all': '.mw-test-implement-c { float: right; }' + }, + {} + ); + + mw.loader.load( [ + 'test.implement.c' + ] ); + } ); + + // Backwards compatibility + QUnit.asyncTest( 'mw.loader.implement( styles={ <media>: [url, ..] } ) (back-compat)', 4, function ( assert ) { + var $element = $( '<div class="mw-test-implement-d"></div>' ).appendTo( '#qunit-fixture' ), + $element2 = $( '<div class="mw-test-implement-d2"></div>' ).appendTo( '#qunit-fixture' ); + + assert.notEqual( + $element.css( 'float' ), + 'right', + 'style is clear' + ); + assert.notEqual( + $element2.css( 'text-align' ), + 'center', + 'style is clear' + ); + + mw.loader.implement( + 'test.implement.d', + function () { + assertStyleAsync( assert, $element, 'float', 'right', function () { + + assert.notEqual( $element2.css( 'text-align' ), 'center', 'print style is not applied (bug 40500)' ); + + QUnit.start(); + } ); + }, + { + 'all': [urlStyleTest( '.mw-test-implement-d', 'float', 'right' )], + 'print': [urlStyleTest( '.mw-test-implement-d2', 'text-align', 'center' )] + }, + {} + ); + + mw.loader.load( [ + 'test.implement.d' + ] ); + } ); + + // @import (bug 31676) + QUnit.asyncTest( 'mw.loader.implement( styles has @import)', 5, function ( assert ) { + var isJsExecuted, $element; + + mw.loader.implement( + 'test.implement.import', + function () { + assert.strictEqual( isJsExecuted, undefined, 'javascript not executed multiple times' ); + isJsExecuted = true; + + assert.equal( mw.loader.getState( 'test.implement.import' ), 'ready', 'module state is "ready" while implement() is executing javascript' ); + + $element = $( '<div class="mw-test-implement-import">Foo bar</div>' ).appendTo( '#qunit-fixture' ); + + assert.equal( mw.msg( 'test-foobar' ), 'Hello Foobar, $1!', 'Messages are loaded before javascript execution' ); + + assertStyleAsync( assert, $element, 'float', 'right', function () { + assert.equal( $element.css( 'text-align' ), 'center', + 'CSS styles after the @import rule are working' + ); + + QUnit.start(); + } ); + }, + { + 'css': [ + '@import url(\'' + + urlStyleTest( '.mw-test-implement-import', 'float', 'right' ) + + '\');\n' + + '.mw-test-implement-import { text-align: center; }' + ] + }, + { + 'test-foobar': 'Hello Foobar, $1!' + } + ); + + mw.loader.load( 'test.implement' ); + + } ); + + QUnit.asyncTest( 'mw.loader.implement( only messages )', 2, function ( assert ) { + assert.assertFalse( mw.messages.exists( 'bug_29107' ), 'Verify that the test message doesn\'t exist yet' ); + + mw.loader.implement( 'test.implement.msgs', [], {}, { 'bug_29107': 'loaded' } ); + mw.loader.using( 'test.implement.msgs', function () { + QUnit.start(); + assert.ok( mw.messages.exists( 'bug_29107' ), 'Bug 29107: messages-only module should implement ok' ); + }, function () { + QUnit.start(); + assert.ok( false, 'Error callback fired while implementing "test.implement.msgs" module' ); + } ); + } ); + + QUnit.test( 'mw.loader erroneous indirect dependency', 3, function ( assert ) { + mw.loader.register( [ + ['test.module1', '0'], + ['test.module2', '0', ['test.module1']], + ['test.module3', '0', ['test.module2']] + ] ); + mw.loader.implement( 'test.module1', function () { + throw new Error( 'expected' ); + }, {}, {} ); + assert.strictEqual( mw.loader.getState( 'test.module1' ), 'error', 'Expected "error" state for test.module1' ); + assert.strictEqual( mw.loader.getState( 'test.module2' ), 'error', 'Expected "error" state for test.module2' ); + assert.strictEqual( mw.loader.getState( 'test.module3' ), 'error', 'Expected "error" state for test.module3' ); + } ); + + QUnit.test( 'mw.loader out-of-order implementation', 9, function ( assert ) { + mw.loader.register( [ + ['test.module4', '0'], + ['test.module5', '0', ['test.module4']], + ['test.module6', '0', ['test.module5']] + ] ); + mw.loader.implement( 'test.module4', function () { + }, {}, {} ); + assert.strictEqual( mw.loader.getState( 'test.module4' ), 'ready', 'Expected "ready" state for test.module4' ); + assert.strictEqual( mw.loader.getState( 'test.module5' ), 'registered', 'Expected "registered" state for test.module5' ); + assert.strictEqual( mw.loader.getState( 'test.module6' ), 'registered', 'Expected "registered" state for test.module6' ); + mw.loader.implement( 'test.module6', function () { + }, {}, {} ); + assert.strictEqual( mw.loader.getState( 'test.module4' ), 'ready', 'Expected "ready" state for test.module4' ); + assert.strictEqual( mw.loader.getState( 'test.module5' ), 'registered', 'Expected "registered" state for test.module5' ); + assert.strictEqual( mw.loader.getState( 'test.module6' ), 'loaded', 'Expected "loaded" state for test.module6' ); + mw.loader.implement( 'test.module5', function () { + }, {}, {} ); + assert.strictEqual( mw.loader.getState( 'test.module4' ), 'ready', 'Expected "ready" state for test.module4' ); + assert.strictEqual( mw.loader.getState( 'test.module5' ), 'ready', 'Expected "ready" state for test.module5' ); + assert.strictEqual( mw.loader.getState( 'test.module6' ), 'ready', 'Expected "ready" state for test.module6' ); + } ); + + QUnit.test( 'mw.loader missing dependency', 13, function ( assert ) { + mw.loader.register( [ + ['test.module7', '0'], + ['test.module8', '0', ['test.module7']], + ['test.module9', '0', ['test.module8']] + ] ); + mw.loader.implement( 'test.module8', function () { + }, {}, {} ); + assert.strictEqual( mw.loader.getState( 'test.module7' ), 'registered', 'Expected "registered" state for test.module7' ); + assert.strictEqual( mw.loader.getState( 'test.module8' ), 'loaded', 'Expected "loaded" state for test.module8' ); + assert.strictEqual( mw.loader.getState( 'test.module9' ), 'registered', 'Expected "registered" state for test.module9' ); + mw.loader.state( 'test.module7', 'missing' ); + assert.strictEqual( mw.loader.getState( 'test.module7' ), 'missing', 'Expected "missing" state for test.module7' ); + assert.strictEqual( mw.loader.getState( 'test.module8' ), 'error', 'Expected "error" state for test.module8' ); + assert.strictEqual( mw.loader.getState( 'test.module9' ), 'error', 'Expected "error" state for test.module9' ); + mw.loader.implement( 'test.module9', function () { + }, {}, {} ); + assert.strictEqual( mw.loader.getState( 'test.module7' ), 'missing', 'Expected "missing" state for test.module7' ); + assert.strictEqual( mw.loader.getState( 'test.module8' ), 'error', 'Expected "error" state for test.module8' ); + assert.strictEqual( mw.loader.getState( 'test.module9' ), 'error', 'Expected "error" state for test.module9' ); + mw.loader.using( + ['test.module7'], + function () { + assert.ok( false, 'Success fired despite missing dependency' ); + assert.ok( true, 'QUnit expected() count dummy' ); + }, + function ( e, dependencies ) { + assert.strictEqual( $.isArray( dependencies ), true, 'Expected array of dependencies' ); + assert.deepEqual( dependencies, ['test.module7'], 'Error callback called with module test.module7' ); + } + ); + mw.loader.using( + ['test.module9'], + function () { + assert.ok( false, 'Success fired despite missing dependency' ); + assert.ok( true, 'QUnit expected() count dummy' ); + }, + function ( e, dependencies ) { + assert.strictEqual( $.isArray( dependencies ), true, 'Expected array of dependencies' ); + dependencies.sort(); + assert.deepEqual( + dependencies, + ['test.module7', 'test.module8', 'test.module9'], + 'Error callback called with all three modules as dependencies' + ); + } + ); + } ); + + QUnit.asyncTest( 'mw.loader dependency handling', 5, function ( assert ) { + mw.loader.register( [ + // [module, version, dependencies, group, source] + ['testMissing', '1', [], null, 'testloader'], + ['testUsesMissing', '1', ['testMissing'], null, 'testloader'], + ['testUsesNestedMissing', '1', ['testUsesMissing'], null, 'testloader'] + ] ); + + function verifyModuleStates() { + assert.equal( mw.loader.getState( 'testMissing' ), 'missing', 'Module not known to server must have state "missing"' ); + assert.equal( mw.loader.getState( 'testUsesMissing' ), 'error', 'Module with missing dependency must have state "error"' ); + assert.equal( mw.loader.getState( 'testUsesNestedMissing' ), 'error', 'Module with indirect missing dependency must have state "error"' ); + } + + mw.loader.using( ['testUsesNestedMissing'], + function () { + assert.ok( false, 'Error handler should be invoked.' ); + assert.ok( true ); // Dummy to reach QUnit expect() + + verifyModuleStates(); + + QUnit.start(); + }, + function ( e, badmodules ) { + assert.ok( true, 'Error handler should be invoked.' ); + // As soon as server spits out state('testMissing', 'missing'); + // it will bubble up and trigger the error callback. + // Therefor the badmodules array is not testUsesMissing or testUsesNestedMissing. + assert.deepEqual( badmodules, ['testMissing'], 'Bad modules as expected.' ); + + verifyModuleStates(); + + QUnit.start(); + } + ); + } ); + + QUnit.asyncTest( 'mw.loader skin-function handling', 5, function ( assert ) { + mw.loader.register( [ + // [module, version, dependencies, group, source, skip] + ['testSkipped', '1', [], null, 'testloader', 'return true;'], + ['testNotSkipped', '1', [], null, 'testloader', 'return false;'], + ['testUsesSkippable', '1', ['testSkipped', 'testNotSkipped'], null, 'testloader'] + ] ); + + function verifyModuleStates() { + assert.equal( mw.loader.getState( 'testSkipped' ), 'ready', 'Module is ready when skipped' ); + assert.equal( mw.loader.getState( 'testNotSkipped' ), 'ready', 'Module is ready when not skipped but loaded' ); + assert.equal( mw.loader.getState( 'testUsesSkippable' ), 'ready', 'Module is ready when skippable dependencies are ready' ); + } + + mw.loader.using( ['testUsesSkippable'], + function () { + assert.ok( true, 'Success handler should be invoked.' ); + assert.ok( true ); // Dummy to match error handler and reach QUnit expect() + + verifyModuleStates(); + + QUnit.start(); + }, + function ( e, badmodules ) { + assert.ok( false, 'Error handler should not be invoked.' ); + assert.deepEqual( badmodules, [], 'Bad modules as expected.' ); + + verifyModuleStates(); + + QUnit.start(); + } + ); + } ); + + QUnit.asyncTest( 'mw.loader( "//protocol-relative" ) (bug 30825)', 2, function ( assert ) { + // This bug was actually already fixed in 1.18 and later when discovered in 1.17. + // Test is for regressions! + + // Forge an URL to the test callback script + var target = QUnit.fixurl( + mw.config.get( 'wgServer' ) + mw.config.get( 'wgScriptPath' ) + '/tests/qunit/data/qunitOkCall.js' + ); + + // Confirm that mw.loader.load() works with protocol-relative URLs + target = target.replace( /https?:/, '' ); + + assert.equal( target.slice( 0, 2 ), '//', + 'URL must be relative to test relative URLs!' + ); + + // Async! + // The target calls QUnit.start + mw.loader.load( target ); + } ); + + QUnit.test( 'mw.html', 13, function ( assert ) { + assert.throws( function () { + mw.html.escape(); + }, TypeError, 'html.escape throws a TypeError if argument given is not a string' ); + + assert.equal( mw.html.escape( '<mw awesome="awesome" value=\'test\' />' ), + '<mw awesome="awesome" value='test' />', 'escape() escapes special characters to html entities' ); + + assert.equal( mw.html.element(), + '<undefined/>', 'element() always returns a valid html string (even without arguments)' ); + + assert.equal( mw.html.element( 'div' ), '<div/>', 'element() Plain DIV (simple)' ); + + assert.equal( mw.html.element( 'div', {}, '' ), '<div></div>', 'element() Basic DIV (simple)' ); + + assert.equal( + mw.html.element( + 'div', { + id: 'foobar' + } + ), + '<div id="foobar"/>', + 'html.element DIV (attribs)' ); + + assert.equal( mw.html.element( 'p', null, 12 ), '<p>12</p>', 'Numbers are valid content and should be casted to a string' ); + + assert.equal( mw.html.element( 'p', { title: 12 }, '' ), '<p title="12"></p>', 'Numbers are valid attribute values' ); + + // Example from https://www.mediawiki.org/wiki/ResourceLoader/Default_modules#mediaWiki.html + assert.equal( + mw.html.element( + 'div', + {}, + new mw.html.Raw( + mw.html.element( 'img', { src: '<' } ) + ) + ), + '<div><img src="<"/></div>', + 'Raw inclusion of another element' + ); + + assert.equal( + mw.html.element( + 'option', { + selected: true + }, 'Foo' + ), + '<option selected="selected">Foo</option>', + 'Attributes may have boolean values. True copies the attribute name to the value.' + ); + + assert.equal( + mw.html.element( + 'option', { + value: 'foo', + selected: false + }, 'Foo' + ), + '<option value="foo">Foo</option>', + 'Attributes may have boolean values. False keeps the attribute from output.' + ); + + assert.equal( mw.html.element( 'div', + null, 'a' ), + '<div>a</div>', + 'html.element DIV (content)' ); + + assert.equal( mw.html.element( 'a', + { href: 'http://mediawiki.org/w/index.php?title=RL&action=history' }, 'a' ), + '<a href="http://mediawiki.org/w/index.php?title=RL&action=history">a</a>', + 'html.element DIV (attribs + content)' ); + + } ); + + QUnit.test( 'mw.hook', 13, function ( assert ) { + var hook, add, fire, chars, callback; + + mw.hook( 'test.hook.unfired' ).add( function () { + assert.ok( false, 'Unfired hook' ); + } ); + + mw.hook( 'test.hook.basic' ).add( function () { + assert.ok( true, 'Basic callback' ); + } ); + mw.hook( 'test.hook.basic' ).fire(); + + mw.hook( 'hasOwnProperty' ).add( function () { + assert.ok( true, 'hook with name of predefined method' ); + } ); + mw.hook( 'hasOwnProperty' ).fire(); + + mw.hook( 'test.hook.data' ).add( function ( data1, data2 ) { + assert.equal( data1, 'example', 'Fire with data (string param)' ); + assert.deepEqual( data2, ['two'], 'Fire with data (array param)' ); + } ); + mw.hook( 'test.hook.data' ).fire( 'example', ['two'] ); + + hook = mw.hook( 'test.hook.chainable' ); + assert.strictEqual( hook.add(), hook, 'hook.add is chainable' ); + assert.strictEqual( hook.remove(), hook, 'hook.remove is chainable' ); + assert.strictEqual( hook.fire(), hook, 'hook.fire is chainable' ); + + hook = mw.hook( 'test.hook.detach' ); + add = hook.add; + fire = hook.fire; + add( function ( x, y ) { + assert.deepEqual( [x, y], ['x', 'y'], 'Detached (contextless) with data' ); + } ); + fire( 'x', 'y' ); + + mw.hook( 'test.hook.fireBefore' ).fire().add( function () { + assert.ok( true, 'Invoke handler right away if it was fired before' ); + } ); + + mw.hook( 'test.hook.fireTwiceBefore' ).fire().fire().add( function () { + assert.ok( true, 'Invoke handler right away if it was fired before (only last one)' ); + } ); + + chars = []; + + mw.hook( 'test.hook.many' ) + .add( function ( chr ) { + chars.push( chr ); + } ) + .fire( 'x' ).fire( 'y' ).fire( 'z' ) + .add( function ( chr ) { + assert.equal( chr, 'z', 'Adding callback later invokes right away with last data' ); + } ); + + assert.deepEqual( chars, ['x', 'y', 'z'], 'Multiple callbacks with multiple fires' ); + + chars = []; + callback = function ( chr ) { + chars.push( chr ); + }; + + mw.hook( 'test.hook.variadic' ) + .add( + callback, + callback, + function ( chr ) { + chars.push( chr ); + }, + callback + ) + .fire( 'x' ) + .remove( + function () { + 'not-added'; + }, + callback + ) + .fire( 'y' ) + .remove( callback ) + .fire( 'z' ); + + assert.deepEqual( + chars, + ['x', 'x', 'x', 'x', 'y', 'z'], + '"add" and "remove" support variadic arguments. ' + + '"add" does not filter unique. ' + + '"remove" removes all equal by reference. ' + + '"remove" is silent if the function is not found' + ); + } ); + +}( mediaWiki, jQuery ) ); diff --git a/tests/qunit/suites/resources/mediawiki/mediawiki.toc.test.js b/tests/qunit/suites/resources/mediawiki/mediawiki.toc.test.js new file mode 100644 index 00000000..e43516b0 --- /dev/null +++ b/tests/qunit/suites/resources/mediawiki/mediawiki.toc.test.js @@ -0,0 +1,40 @@ +( function ( mw, $ ) { + QUnit.module( 'mediawiki.toc', QUnit.newMwEnvironment( { + setup: function () { + // Prevent live cookies like mw_hidetoc=1 from interferring with the test + this.stub( $, 'cookie' ).returns( null ); + } + } ) ); + + QUnit.asyncTest( 'toggleToc', 4, function ( assert ) { + var tocHtml, $toggleLink, $tocList; + + assert.strictEqual( $( '#toc' ).length, 0, 'There is no table of contents on the page at the beginning' ); + + tocHtml = '<div id="toc" class="toc">' + + '<div id="toctitle">' + + '<h2>Contents</h2>' + + '</div>' + + '<ul><li></li></ul>' + + '</div>'; + $( tocHtml ).appendTo( '#qunit-fixture' ); + mw.hook( 'wikipage.content' ).fire( $( '#qunit-fixture' ) ); + + $tocList = $( '#toc ul:first' ); + $toggleLink = $( '#togglelink' ); + + assert.strictEqual( $toggleLink.length, 1, 'Toggle link is added to the table of contents' ); + + assert.strictEqual( $tocList.is( ':hidden' ), false, 'The table of contents is now visible' ); + + $toggleLink.click(); + $tocList.promise().done( function () { + assert.strictEqual( $tocList.is( ':hidden' ), true, 'The table of contents is now hidden' ); + + $toggleLink.click(); + $tocList.promise().done( function () { + QUnit.start(); + } ); + } ); + } ); +}( mediaWiki, jQuery ) ); diff --git a/tests/qunit/suites/resources/mediawiki/mediawiki.user.test.js b/tests/qunit/suites/resources/mediawiki/mediawiki.user.test.js new file mode 100644 index 00000000..91321a2f --- /dev/null +++ b/tests/qunit/suites/resources/mediawiki/mediawiki.user.test.js @@ -0,0 +1,54 @@ +( function ( mw ) { + QUnit.module( 'mediawiki.user', QUnit.newMwEnvironment( { + setup: function () { + this.server = this.sandbox.useFakeServer(); + } + } ) ); + + QUnit.test( 'options', 1, function ( assert ) { + assert.ok( mw.user.options instanceof mw.Map, 'options instance of mw.Map' ); + } ); + + QUnit.test( 'user status', 7, function ( assert ) { + + // Forge an anonymous user + mw.config.set( 'wgUserName', null ); + delete mw.config.values.wgUserId; + + assert.strictEqual( mw.user.getName(), null, 'user.getName() returns null when anonymous' ); + assert.assertTrue( mw.user.isAnon(), 'user.isAnon() returns true when anonymous' ); + assert.strictEqual( mw.user.getId(), 0, 'user.getId() returns 0 when anonymous' ); + + // Not part of startUp module + mw.config.set( 'wgUserName', 'John' ); + mw.config.set( 'wgUserId', 123 ); + + assert.equal( mw.user.getName(), 'John', 'user.getName() returns username when logged-in' ); + assert.assertFalse( mw.user.isAnon(), 'user.isAnon() returns false when logged-in' ); + assert.strictEqual( mw.user.getId(), 123, 'user.getId() returns correct ID when logged-in' ); + + assert.equal( mw.user.id(), 'John', 'user.id Returns username when logged-in' ); + } ); + + QUnit.test( 'getUserInfos', 3, function ( assert ) { + mw.user.getGroups( function ( groups ) { + assert.deepEqual( groups, [ '*', 'user' ], 'Result' ); + } ); + + mw.user.getRights( function ( rights ) { + assert.deepEqual( rights, [ 'read', 'edit', 'createtalk' ], 'Result (callback)' ); + } ); + + mw.user.getRights().done( function ( rights ) { + assert.deepEqual( rights, [ 'read', 'edit', 'createtalk' ], 'Result (promise)' ); + } ); + + this.server.respondWith( /meta=userinfo/, function ( request ) { + request.respond( 200, { 'Content-Type': 'application/json' }, + '{ "query": { "userinfo": { "groups": [ "*", "user" ], "rights": [ "read", "edit", "createtalk" ] } } }' + ); + } ); + + this.server.respond(); + } ); +}( mediaWiki ) ); diff --git a/tests/qunit/suites/resources/mediawiki/mediawiki.util.test.js b/tests/qunit/suites/resources/mediawiki/mediawiki.util.test.js new file mode 100644 index 00000000..4401eadb --- /dev/null +++ b/tests/qunit/suites/resources/mediawiki/mediawiki.util.test.js @@ -0,0 +1,343 @@ +( function ( mw, $ ) { + QUnit.module( 'mediawiki.util', QUnit.newMwEnvironment( { + setup: function () { + $.fn.updateTooltipAccessKeys.setTestMode( true ); + }, + teardown: function () { + $.fn.updateTooltipAccessKeys.setTestMode( false ); + }, + messages: { + // Used by accessKeyLabel in test for addPortletLink + 'brackets': '[$1]', + 'word-separator': ' ' + } + } ) ); + + QUnit.test( 'rawurlencode', 1, function ( assert ) { + assert.equal( mw.util.rawurlencode( 'Test:A & B/Here' ), 'Test%3AA%20%26%20B%2FHere' ); + } ); + + QUnit.test( 'wikiUrlencode', 10, function ( assert ) { + assert.equal( mw.util.wikiUrlencode( 'Test:A & B/Here' ), 'Test:A_%26_B/Here' ); + // See also wfUrlencodeTest.php#provideURLS + $.each( { + '+': '%2B', + '&': '%26', + '=': '%3D', + ':': ':', + ';@$-_.!*': ';@$-_.!*', + '/': '/', + '[]': '%5B%5D', + '<>': '%3C%3E', + '\'': '%27' + }, function ( input, output ) { + assert.equal( mw.util.wikiUrlencode( input ), output ); + } ); + } ); + + QUnit.test( 'getUrl', 4, function ( assert ) { + // Not part of startUp module + mw.config.set( 'wgArticlePath', '/wiki/$1' ); + mw.config.set( 'wgPageName', 'Foobar' ); + + var href = mw.util.getUrl( 'Sandbox' ); + assert.equal( href, '/wiki/Sandbox', 'Simple title; Get link for "Sandbox"' ); + + href = mw.util.getUrl( 'Foo:Sandbox ? 5+5=10 ! (test)/subpage' ); + assert.equal( href, '/wiki/Foo:Sandbox_%3F_5%2B5%3D10_!_(test)/subpage', + 'Advanced title; Get link for "Foo:Sandbox ? 5+5=10 ! (test)/subpage"' ); + + href = mw.util.getUrl(); + assert.equal( href, '/wiki/Foobar', 'Default title; Get link for current page ("Foobar")' ); + + href = mw.util.getUrl( 'Sandbox', { action: 'edit' } ); + assert.equal( href, '/wiki/Sandbox?action=edit', + 'Simple title with query string; Get link for "Sandbox" with action=edit' ); + } ); + + QUnit.test( 'wikiScript', 4, function ( assert ) { + mw.config.set( { + 'wgScript': '/w/i.php', // customized wgScript for bug 39103 + 'wgLoadScript': '/w/l.php', // customized wgLoadScript for bug 39103 + 'wgScriptPath': '/w', + 'wgScriptExtension': '.php' + } ); + + assert.equal( mw.util.wikiScript(), mw.config.get( 'wgScript' ), + 'wikiScript() returns wgScript' + ); + assert.equal( mw.util.wikiScript( 'index' ), mw.config.get( 'wgScript' ), + 'wikiScript( index ) returns wgScript' + ); + assert.equal( mw.util.wikiScript( 'load' ), mw.config.get( 'wgLoadScript' ), + 'wikiScript( load ) returns wgLoadScript' + ); + assert.equal( mw.util.wikiScript( 'api' ), '/w/api.php', 'API path' ); + } ); + + QUnit.test( 'addCSS', 3, function ( assert ) { + var $el, style; + $el = $( '<div>' ).attr( 'id', 'mw-addcsstest' ).appendTo( '#qunit-fixture' ); + + style = mw.util.addCSS( '#mw-addcsstest { visibility: hidden; }' ); + assert.equal( typeof style, 'object', 'addCSS returned an object' ); + assert.strictEqual( style.disabled, false, 'property "disabled" is available and set to false' ); + + assert.equal( $el.css( 'visibility' ), 'hidden', 'Added style properties are in effect' ); + + // Clean up + $( style.ownerNode ).remove(); + } ); + + QUnit.test( 'getParamValue', 5, function ( assert ) { + var url; + + url = 'http://example.org/?foo=wrong&foo=right#&foo=bad'; + assert.equal( mw.util.getParamValue( 'foo', url ), 'right', 'Use latest one, ignore hash' ); + assert.strictEqual( mw.util.getParamValue( 'bar', url ), null, 'Return null when not found' ); + + url = 'http://example.org/#&foo=bad'; + assert.strictEqual( mw.util.getParamValue( 'foo', url ), null, 'Ignore hash if param is not in querystring but in hash (bug 27427)' ); + + url = 'example.org?' + $.param( { 'TEST': 'a b+c' } ); + assert.strictEqual( mw.util.getParamValue( 'TEST', url ), 'a b+c', 'Bug 30441: getParamValue must understand "+" encoding of space' ); + + url = 'example.org?' + $.param( { 'TEST': 'a b+c d' } ); // check for sloppy code from r95332 :) + assert.strictEqual( mw.util.getParamValue( 'TEST', url ), 'a b+c d', 'Bug 30441: getParamValue must understand "+" encoding of space (multiple spaces)' ); + } ); + + QUnit.test( 'tooltipAccessKey', 4, function ( assert ) { + this.suppressWarnings(); + + assert.equal( typeof mw.util.tooltipAccessKeyPrefix, 'string', 'tooltipAccessKeyPrefix must be a string' ); + assert.equal( $.type( mw.util.tooltipAccessKeyRegexp ), 'regexp', 'tooltipAccessKeyRegexp is a regexp' ); + assert.ok( mw.util.updateTooltipAccessKeys, 'updateTooltipAccessKeys is non-empty' ); + + 'Example [a]'.replace( mw.util.tooltipAccessKeyRegexp, function ( sub, m1, m2, m3, m4, m5, m6 ) { + assert.equal( m6, 'a', 'tooltipAccessKeyRegexp finds the accesskey hint' ); + } ); + + this.restoreWarnings(); + } ); + + QUnit.test( '$content', 2, function ( assert ) { + assert.ok( mw.util.$content instanceof jQuery, 'mw.util.$content instance of jQuery' ); + assert.strictEqual( mw.util.$content.length, 1, 'mw.util.$content must have length of 1' ); + } ); + + /** + * Portlet names are prefixed with 'p-test' to avoid conflict with core + * when running the test suite under a wiki page. + * Previously, test elements where invisible to the selector since only + * one element can have a given id. + */ + QUnit.test( 'addPortletLink', 13, function ( assert ) { + var pTestTb, pCustom, vectorTabs, tbRL, cuQuux, $cuQuux, tbMW, $tbMW, tbRLDM, caFoo, + addedAfter, tbRLDMnonexistentid, tbRLDMemptyjquery; + + pTestTb = '\ + <div class="portlet" id="p-test-tb">\ + <h3>Toolbox</h3>\ + <ul class="body"></ul>\ + </div>'; + pCustom = '\ + <div class="portlet" id="p-test-custom">\ + <h3>Views</h3>\ + <ul class="body">\ + <li id="c-foo"><a href="#">Foo</a></li>\ + <li id="c-barmenu">\ + <ul>\ + <li id="c-bar-baz"><a href="#">Baz</a></a>\ + </ul>\ + </li>\ + </ul>\ + </div>'; + vectorTabs = '\ + <div id="p-test-views" class="vectorTabs">\ + <h3>Views</h3>\ + <ul></ul>\ + </div>'; + + $( '#qunit-fixture' ).append( pTestTb, pCustom, vectorTabs ); + + tbRL = mw.util.addPortletLink( 'p-test-tb', '//mediawiki.org/wiki/ResourceLoader', + 'ResourceLoader', 't-rl', 'More info about ResourceLoader on MediaWiki.org ', 'l' + ); + + assert.ok( $.isDomElement( tbRL ), 'addPortletLink returns a valid DOM Element according to $.isDomElement' ); + + tbMW = mw.util.addPortletLink( 'p-test-tb', '//mediawiki.org/', + 'MediaWiki.org', 't-mworg', 'Go to MediaWiki.org', 'm', tbRL ); + $tbMW = $( tbMW ); + + assert.propEqual( + $tbMW.getAttrs(), + { + id: 't-mworg' + }, + 'Validate attributes of created element' + ); + + assert.propEqual( + $tbMW.find( 'a' ).getAttrs(), + { + href: '//mediawiki.org/', + title: 'Go to MediaWiki.org [test-m]', + accesskey: 'm' + }, + 'Validate attributes of anchor tag in created element' + ); + + assert.equal( $tbMW.closest( '.portlet' ).attr( 'id' ), 'p-test-tb', 'Link was inserted within correct portlet' ); + assert.strictEqual( $tbMW.next()[0], tbRL, 'Link is in the correct position (by passing nextnode)' ); + + cuQuux = mw.util.addPortletLink( 'p-test-custom', '#', 'Quux', null, 'Example [shift-x]', 'q' ); + $cuQuux = $( cuQuux ); + + assert.equal( $cuQuux.find( 'a' ).attr( 'title' ), 'Example [test-q]', 'Existing accesskey is stripped and updated' ); + + assert.equal( + $( '#p-test-custom #c-barmenu ul li' ).length, + 1, + 'addPortletLink did not add the item to all <ul> elements in the portlet (bug 35082)' + ); + + tbRLDM = mw.util.addPortletLink( 'p-test-tb', '//mediawiki.org/wiki/RL/DM', + 'Default modules', 't-rldm', 'List of all default modules ', 'd', '#t-rl' ); + + assert.equal( $( tbRLDM ).next().attr( 'id' ), 't-rl', 'Link is in the correct position (by passing CSS selector)' ); + + caFoo = mw.util.addPortletLink( 'p-test-views', '#', 'Foo' ); + + assert.strictEqual( $tbMW.find( 'span' ).length, 0, 'No <span> element should be added for porlets without vectorTabs class.' ); + assert.strictEqual( $( caFoo ).find( 'span' ).length, 1, 'A <span> element should be added for porlets with vectorTabs class.' ); + + addedAfter = mw.util.addPortletLink( 'p-test-tb', '#', 'After foo', 'post-foo', 'After foo', null, $( tbRL ) ); + assert.strictEqual( $( addedAfter ).next()[0], tbRL, 'Link is in the correct position (by passing a jQuery object as nextnode)' ); + + // test case - nonexistent id as next node + tbRLDMnonexistentid = mw.util.addPortletLink( 'p-test-tb', '//mediawiki.org/wiki/RL/DM', + 'Default modules', 't-rldm-nonexistent', 'List of all default modules ', 'd', '#t-rl-nonexistent' ); + + assert.equal( tbRLDMnonexistentid, $( '#p-test-tb li:last' )[0], 'Nonexistent id as nextnode adds the portlet at end' ); + + // test case - empty jquery object as next node + tbRLDMemptyjquery = mw.util.addPortletLink( 'p-test-tb', '//mediawiki.org/wiki/RL/DM', + 'Default modules', 't-rldm-empty-jquery', 'List of all default modules ', 'd', $( '#t-rl-nonexistent' ) ); + + assert.equal( tbRLDMemptyjquery, $( '#p-test-tb li:last' )[0], 'Empty jquery as nextnode adds the portlet at end' ); + } ); + + QUnit.test( 'jsMessage', 1, function ( assert ) { + this.suppressWarnings(); + var a = mw.util.jsMessage( 'MediaWiki is <b>Awesome</b>.' ); + this.restoreWarnings(); + assert.ok( a, 'Basic checking of return value' ); + } ); + + QUnit.test( 'validateEmail', 6, function ( assert ) { + assert.strictEqual( mw.util.validateEmail( '' ), null, 'Should return null for empty string ' ); + assert.strictEqual( mw.util.validateEmail( 'user@localhost' ), true, 'Return true for a valid e-mail address' ); + + // testEmailWithCommasAreInvalids + assert.strictEqual( mw.util.validateEmail( 'user,foo@example.org' ), false, 'Emails with commas are invalid' ); + assert.strictEqual( mw.util.validateEmail( 'userfoo@ex,ample.org' ), false, 'Emails with commas are invalid' ); + + // testEmailWithHyphens + assert.strictEqual( mw.util.validateEmail( 'user-foo@example.org' ), true, 'Emails may contain a hyphen' ); + assert.strictEqual( mw.util.validateEmail( 'userfoo@ex-ample.org' ), true, 'Emails may contain a hyphen' ); + } ); + + QUnit.test( 'isIPv6Address', 40, function ( assert ) { + // Shortcuts + function assertFalseIPv6( addy, summary ) { + return assert.strictEqual( mw.util.isIPv6Address( addy ), false, summary ); + } + + function assertTrueIPv6( addy, summary ) { + return assert.strictEqual( mw.util.isIPv6Address( addy ), true, summary ); + } + + // Based on IPTest.php > testisIPv6 + assertFalseIPv6( ':fc:100::', 'IPv6 starting with lone ":"' ); + assertFalseIPv6( 'fc:100:::', 'IPv6 ending with a ":::"' ); + assertFalseIPv6( 'fc:300', 'IPv6 with only 2 words' ); + assertFalseIPv6( 'fc:100:300', 'IPv6 with only 3 words' ); + + $.each( + ['fc:100::', + 'fc:100:a::', + 'fc:100:a:d::', + 'fc:100:a:d:1::', + 'fc:100:a:d:1:e::', + 'fc:100:a:d:1:e:ac::'], function ( i, addy ) { + assertTrueIPv6( addy, addy + ' is a valid IP' ); + } ); + + assertFalseIPv6( 'fc:100:a:d:1:e:ac:0::', 'IPv6 with 8 words ending with "::"' ); + assertFalseIPv6( 'fc:100:a:d:1:e:ac:0:1::', 'IPv6 with 9 words ending with "::"' ); + + assertFalseIPv6( ':::' ); + assertFalseIPv6( '::0:', 'IPv6 ending in a lone ":"' ); + + assertTrueIPv6( '::', 'IPv6 zero address' ); + $.each( + ['::0', + '::fc', + '::fc:100', + '::fc:100:a', + '::fc:100:a:d', + '::fc:100:a:d:1', + '::fc:100:a:d:1:e', + '::fc:100:a:d:1:e:ac', + + 'fc:100:a:d:1:e:ac:0'], function ( i, addy ) { + assertTrueIPv6( addy, addy + ' is a valid IP' ); + } ); + + assertFalseIPv6( '::fc:100:a:d:1:e:ac:0', 'IPv6 with "::" and 8 words' ); + assertFalseIPv6( '::fc:100:a:d:1:e:ac:0:1', 'IPv6 with 9 words' ); + + assertFalseIPv6( ':fc::100', 'IPv6 starting with lone ":"' ); + assertFalseIPv6( 'fc::100:', 'IPv6 ending with lone ":"' ); + assertFalseIPv6( 'fc:::100', 'IPv6 with ":::" in the middle' ); + + assertTrueIPv6( 'fc::100', 'IPv6 with "::" and 2 words' ); + assertTrueIPv6( 'fc::100:a', 'IPv6 with "::" and 3 words' ); + assertTrueIPv6( 'fc::100:a:d', 'IPv6 with "::" and 4 words' ); + assertTrueIPv6( 'fc::100:a:d:1', 'IPv6 with "::" and 5 words' ); + assertTrueIPv6( 'fc::100:a:d:1:e', 'IPv6 with "::" and 6 words' ); + assertTrueIPv6( 'fc::100:a:d:1:e:ac', 'IPv6 with "::" and 7 words' ); + assertTrueIPv6( '2001::df', 'IPv6 with "::" and 2 words' ); + assertTrueIPv6( '2001:5c0:1400:a::df', 'IPv6 with "::" and 5 words' ); + assertTrueIPv6( '2001:5c0:1400:a::df:2', 'IPv6 with "::" and 6 words' ); + + assertFalseIPv6( 'fc::100:a:d:1:e:ac:0', 'IPv6 with "::" and 8 words' ); + assertFalseIPv6( 'fc::100:a:d:1:e:ac:0:1', 'IPv6 with 9 words' ); + } ); + + QUnit.test( 'isIPv4Address', 11, function ( assert ) { + // Shortcuts + function assertFalseIPv4( addy, summary ) { + assert.strictEqual( mw.util.isIPv4Address( addy ), false, summary ); + } + + function assertTrueIPv4( addy, summary ) { + assert.strictEqual( mw.util.isIPv4Address( addy ), true, summary ); + } + + // Based on IPTest.php > testisIPv4 + assertFalseIPv4( false, 'Boolean false is not an IP' ); + assertFalseIPv4( true, 'Boolean true is not an IP' ); + assertFalseIPv4( '', 'Empty string is not an IP' ); + assertFalseIPv4( 'abc', '"abc" is not an IP' ); + assertFalseIPv4( ':', 'Colon is not an IP' ); + assertFalseIPv4( '124.24.52', 'IPv4 not enough quads' ); + assertFalseIPv4( '24.324.52.13', 'IPv4 out of range' ); + assertFalseIPv4( '.24.52.13', 'IPv4 starts with period' ); + + assertTrueIPv4( '124.24.52.13', '124.24.52.134 is a valid IP' ); + assertTrueIPv4( '1.24.52.13', '1.24.52.13 is a valid IP' ); + assertFalseIPv4( '74.24.52.13/20', 'IPv4 ranges are not recogzized as valid IPs' ); + } ); +}( mediaWiki, jQuery ) ); diff --git a/tests/qunit/suites/resources/startup.test.js b/tests/qunit/suites/resources/startup.test.js new file mode 100644 index 00000000..ed03418a --- /dev/null +++ b/tests/qunit/suites/resources/startup.test.js @@ -0,0 +1,143 @@ +/*global isCompatible: true */ +( function ( $ ) { + var testcases = { + gradeA: [ + // Chrome + 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_7; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.205 Safari/534.16', + // Firefox 4+ + 'Mozilla/5.0 (Windows NT 6.1.1; rv:5.0) Gecko/20100101 Firefox/5.0', + 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:9.0) Gecko/20100101 Firefox/9.0', + 'Mozilla/5.0 (Macintosh; I; Intel Mac OS X 11_7_9; de-LI; rv:1.9b4) Gecko/2012010317 Firefox/10.0a4', + 'Mozilla/5.0 (Windows NT 6.1; rv:12.0) Gecko/20120403211507 Firefox/12.0', + 'Mozilla/5.0 (Windows NT 6.2; Win64; x64; rv:16.0.1) Gecko/20121011 Firefox/16.0.1', + // Kindle Fire + 'Mozilla/5.0 (Linux; U; Android 2.3.4; en-us; Kindle Fire Build/GINGERBREAD) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Safari/533.1', + // Safari 5.0+ + 'Mozilla/5.0 (Macintosh; I; Intel Mac OS X 10_6_7; ru-ru) AppleWebKit/534.31+ (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1', + // Opera 12+ (Presto-based) + 'Opera/9.80 (Windows NT 6.1; U; es-ES) Presto/2.9.181 Version/12.00', + 'Opera/9.80 (Windows NT 5.1) Presto/2.12.388 Version/12.17', + // Opera 15+ (Chromium-based) + 'Mozilla/5.0 (Windows NT 6.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36 OPR/15.0.1147.153', + 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.57 Safari/537.36 OPR/16.0.1196.62', + 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36 OPR/23.0.1522.75', + // Internet Explorer 8+ + 'Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; Media Center PC 4.0; SLCC1; .NET CLR 3.0.04320)', + 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 7.1; Trident/5.0)', + 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)', + // IE Mobile + 'Mozilla/5.0 (compatible; MSIE 9.0; Windows Phone OS 7.5; Trident/5.0; IEMobile/9.0; NOKIA; Lumia 800)', + // BlackBerry 6+ + 'Mozilla/5.0 (BlackBerry; U; BlackBerry 9300; en) AppleWebKit/534.8+ (KHTML, like Gecko) Version/6.0.0.570 Mobile Safari/534.8+', + 'Mozilla/5.0 (BlackBerry; U; BlackBerry 9900; en) AppleWebKit/534.11+ (KHTML, like Gecko) Version/7.1.0.346 Mobile Safari/534.11+', + 'Mozilla/5.0 (BB10; Touch) AppleWebKit/537.3+ (KHTML, like Gecko) Version/10.0.9.386 Mobile Safari/537.3+', + // Open WebOS 1.4+ (HP Veer 4G) + 'Mozilla/5.0 (webOS/2.1.2; U; en-US) AppleWebKit/532.2 (KHTML, like Gecko) Version/1.0 Safari/532.2 P160UNA/1.0', + // Firefox Mobile + 'Mozilla/5.0 (Mobile; rv:14.0) Gecko/14.0 Firefox/14.0', + // iOS + 'Mozilla/5.0 (ipod: U;CPU iPhone OS 2_2 like Mac OS X: es_es) AppleWebKit/525.18.1 (KHTML, like Gecko) Version/3.0 Mobile/3B48b Safari/419.3', + 'Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420.1 (KHTML, like Gecko) Version/3.0 Mobile/3B48b Safari/419.3', + // Android + 'Mozilla/5.0 (Linux; U; Android 2.1; en-us; Nexus One Build/ERD62) AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17' + ], + gradeC: [ + // Internet Explorer < 8 + 'Mozilla/2.0 (compatible; MSIE 3.03; Windows 3.1)', + 'Mozilla/4.0 (compatible; MSIE 4.01; Windows 95)', + 'Mozilla/4.0 (compatible; MSIE 5.0; Windows 98;)', + 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)', + 'Mozilla/5.0 (compatible; MSIE 6.0; Windows NT 5.1)', + 'Mozilla/5.0 (compatible; MSIE 7.0; Windows NT 6.0; en-US)', + // Firefox < 3 + 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.2) Gecko/20060308 Firefox/1.5.0.2', + 'Mozilla/5.0 (X11; U; Linux i686; nl; rv:1.8.1.1) Gecko/20070311 Firefox/2.0.0.1', + // Opera < 12 + 'Mozilla/5.0 (Windows NT 5.0; U) Opera 7.54 [en]', + 'Opera/7.54 (Windows NT 5.0; U) [en]', + 'Mozilla/5.0 (Windows NT 5.1; U; en) Opera 8.0', + 'Opera/8.0 (X11; Linux i686; U; cs)', + 'Opera/9.00 (X11; Linux i686; U; de)', + 'Opera/9.62 (X11; Linux i686; U; en) Presto/2.1.1', + 'Opera/9.80 (Windows NT 6.1; U; en) Presto/2.2.15 Version/10.00', + 'Opera/9.80 (Windows NT 6.1; U; ru) Presto/2.8.131 Version/11.10', + 'Opera/9.80 (Windows NT 6.1; WOW64; U; pt) Presto/2.10.229 Version/11.62', + // BlackBerry < 6 + 'BlackBerry9300/5.0.0.716 Profile/MIDP-2.1 Configuration/CLDC-1.1 VendorID/133', + 'BlackBerry7250/4.0.0 Profile/MIDP-2.0 Configuration/CLDC-1.1', + // Open WebOS < 1.5 (Palm Pre, Palm Pixi) + 'Mozilla/5.0 (webOS/1.0; U; en-US) AppleWebKit/525.27.1 (KHTML, like Gecko) Version/1.0 Safari/525.27.1 Pre/1.0', + 'Mozilla/5.0 (webOS/1.4.0; U; en-US) AppleWebKit/532.2 (KHTML, like Gecko) Version/1.0 Safari/532.2 Pixi/1.1 ', + // SymbianOS + 'NokiaN95_8GB-3;Mozilla/5.0 SymbianOS/9.2;U;Series60/3.1 NokiaN95_8GB-3/11.2.011 Profile/MIDP-2.0 Configuration/CLDC-1.1 AppleWebKit/413 (KHTML, like Gecko)', + 'Nokia7610/2.0 (5.0509.0) SymbianOS/7.0s Series60/2.1 Profile/MIDP-2.0 Configuration/CLDC-1.0 ', + 'Mozilla/5.0 (SymbianOS/9.1; U; [en]; SymbianOS/91 Series60/3.0) AppleWebKit/413 (KHTML, like Gecko) Safari/413', + 'Mozilla/5.0 (SymbianOS/9.3; Series60/3.2 NokiaE52-2/091.003; Profile/MIDP-2.1 Configuration/CLDC-1.1 ) AppleWebKit/533.4 (KHTML, like Gecko) NokiaBrowser/7.3.1.34 Mobile Safari/533.4', + // NetFront + 'Mozilla/4.0 (compatible; Linux 2.6.10) NetFront/3.3 Kindle/1.0 (screen 600x800)', + 'Mozilla/4.0 (compatible; Linux 2.6.22) NetFront/3.4 Kindle/2.0 (screen 824x1200; rotate)', + 'Mozilla/4.08 (Windows; Mobile Content Viewer/1.0) NetFront/3.2', + // Opera Mini + 'Opera/9.80 (J2ME/MIDP; Opera Mini/3.1.10423/22.387; U; en) Presto/2.5.25 Version/10.54', + 'Opera/9.50 (J2ME/MIDP; Opera Mini/4.0.10031/298; U; en)', + 'Opera/9.80 (J2ME/MIDP; Opera Mini/6.24093/26.1305; U; en) Presto/2.8.119 Version/10.54', + 'Opera/9.80 (Android; Opera Mini/7.29530/27.1407; U; en) Presto/2.8.119 Version/11.10', + // Ovi Browser + 'Mozilla/5.0 (Series40; NokiaX3-02/05.60; Profile/MIDP-2.1 Configuration/CLDC-1.1) Gecko/20100401 S40OviBrowser/3.2.0.0.6', + 'Mozilla/5.0 (Series40; Nokia305/05.92; Profile/MIDP-2.1 Configuration/CLDC-1.1) Gecko/20100401 S40OviBrowser/3.7.0.0.11', + // Google Glass + 'Mozilla/5.0 (Linux; U; Android 4.0.4; en-us; Glass 1 Build/IMM76L; XE11) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30' + ], + // No explicit support for or against these browsers, they're given a shot at Grade A. + gradeX: [ + // Firefox 3.6 + 'Mozilla/5.0 (Windows; U; Windows NT 6.1; ru; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3', + // Gecko + 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.0.7) Gecko/20060928 (Debian|Debian-1.8.0.7-1) Epiphany/2.14', + 'Mozilla/5.0 (X11; U; Linux i686 (x86_64); en-US; rv:1.8.1.6) Gecko/20070817 IceWeasel/2.0.0.6-g2', + // KHTML + 'Mozilla/5.0 (compatible; Konqueror/4.3; Linux) KHTML/4.3.5 (like Gecko)', + // Text browsers + 'Links (2.1pre33; Darwin 8.11.0 Power Macintosh; x)', + 'Links (6.9; Unix 6.9-astral sparc; 80x25)', + 'Lynx/2.8.6rel.4 libwww-FM/2.14 SSL-MM/1.4.1 OpenSSL/0.9.8g', + 'w3m/0.5.1', + // Bots + 'Googlebot/2.1 (+http://www.google.com/bot.html)', + 'Mozilla/5.0 (compatible; googlebot/2.1; +http://www.google.com/bot.html)', + 'Mozilla/5.0 (compatible; YandexBot/3.0)', + // Scripts + 'curl/7.21.4 (universal-apple-darwin11.0) libcurl/7.21.4 OpenSSL/0.9.8r zlib/1.2.5', + 'Wget/1.9', + 'Wget/1.10.1 (Red Hat modified)', + // Unknown + 'I\'m an unknown browser', + // Empty + '' + ] + }; + + QUnit.module( 'startup', QUnit.newMwEnvironment() ); + + QUnit.test( 'isCompatible( Grade A )', testcases.gradeA.length, function ( assert ) { + $.each( testcases.gradeA, function ( i, ua ) { + assert.strictEqual( isCompatible( ua ), true, ua ); + } + ); + } ); + + QUnit.test( 'isCompatible( Grade C )', testcases.gradeC.length, function ( assert ) { + $.each( testcases.gradeC, function ( i, ua ) { + assert.strictEqual( isCompatible( ua ), false, ua ); + } + ); + } ); + + QUnit.test( 'isCompatible( Grade X )', testcases.gradeX.length, function ( assert ) { + $.each( testcases.gradeX, function ( i, ua ) { + assert.strictEqual( isCompatible( ua ), true, ua ); + } + ); + } ); + +}( jQuery ) ); |