SpecialJavaScriptTest.php 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. <?php
  2. /**
  3. * Implements Special:JavaScriptTest
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License along
  16. * with this program; if not, write to the Free Software Foundation, Inc.,
  17. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. * http://www.gnu.org/copyleft/gpl.html
  19. *
  20. * @file
  21. * @ingroup SpecialPage
  22. */
  23. /**
  24. * @ingroup SpecialPage
  25. */
  26. class SpecialJavaScriptTest extends SpecialPage {
  27. public function __construct() {
  28. parent::__construct( 'JavaScriptTest' );
  29. }
  30. public function execute( $par ) {
  31. $out = $this->getOutput();
  32. $this->setHeaders();
  33. $out->disallowUserJs();
  34. // This special page is disabled by default ($wgEnableJavaScriptTest), and contains
  35. // no sensitive data. In order to allow TestSwarm to embed it into a test client window,
  36. // we need to allow iframing of this page.
  37. $out->allowClickjacking();
  38. // Sub resource: Internal JavaScript export bundle for QUnit
  39. if ( $par === 'qunit/export' ) {
  40. $this->exportQUnit();
  41. return;
  42. }
  43. // Regular view: QUnit test runner
  44. // (Support "/qunit" and "/qunit/plain" for backwards compatibility)
  45. if ( $par === null || $par === '' || $par === 'qunit' || $par === 'qunit/plain' ) {
  46. $this->plainQUnit();
  47. return;
  48. }
  49. // Unknown action
  50. $out->setStatusCode( 404 );
  51. $out->setPageTitle( $this->msg( 'javascripttest' ) );
  52. $out->addHTML(
  53. '<div class="error">'
  54. . $this->msg( 'javascripttest-pagetext-unknownaction' )
  55. ->plaintextParams( $par )->parseAsBlock()
  56. . '</div>'
  57. );
  58. }
  59. /**
  60. * Get summary text wrapped in a container
  61. *
  62. * @return string HTML
  63. */
  64. private function getSummaryHtml() {
  65. $summary = $this->msg( 'javascripttest-qunit-intro' )
  66. ->params( 'https://www.mediawiki.org/wiki/Manual:JavaScript_unit_testing' )
  67. ->parseAsBlock();
  68. return "<div id=\"mw-javascripttest-summary\">$summary</div>";
  69. }
  70. /**
  71. * Generate self-sufficient JavaScript payload to run the tests elsewhere.
  72. *
  73. * Includes startup module to request modules from ResourceLoader.
  74. *
  75. * Note: This modifies the registry to replace 'jquery.qunit' with an
  76. * empty module to allow external environment to preload QUnit with any
  77. * neccecary framework adapters (e.g. Karma). Loading it again would
  78. * re-define QUnit and dereference event handlers from Karma.
  79. */
  80. private function exportQUnit() {
  81. $out = $this->getOutput();
  82. $out->disable();
  83. $rl = $out->getResourceLoader();
  84. $query = [
  85. 'lang' => $this->getLanguage()->getCode(),
  86. 'skin' => $this->getSkin()->getSkinName(),
  87. 'debug' => ResourceLoader::inDebugMode() ? 'true' : 'false',
  88. 'target' => 'test',
  89. ];
  90. $embedContext = new ResourceLoaderContext( $rl, new FauxRequest( $query ) );
  91. $query['only'] = 'scripts';
  92. $startupContext = new ResourceLoaderContext( $rl, new FauxRequest( $query ) );
  93. $modules = $rl->getTestSuiteModuleNames();
  94. // Disable autostart because we load modules asynchronously. By default, QUnit would start
  95. // at domready when there are no tests loaded and also fire 'QUnit.done' which then instructs
  96. // Karma to exit the browser process before the tests even finished loading.
  97. $qunitConfig = 'QUnit.config.autostart = false;'
  98. . 'if (window.__karma__) {'
  99. // karma-qunit's use of autostart=false and QUnit.start conflicts with ours.
  100. // Hack around this by replacing 'karma.loaded' with a no-op and perform its duty of calling
  101. // `__karma__.start()` ourselves. See <https://github.com/karma-runner/karma-qunit/issues/27>.
  102. . 'window.__karma__.loaded = function () {};'
  103. . '}';
  104. // The below is essentially a pure-javascript version of OutputPage::headElement().
  105. $code = $rl->makeModuleResponse( $startupContext, [
  106. 'startup' => $rl->getModule( 'startup' ),
  107. ] );
  108. $code .= <<<JAVASCRIPT
  109. // Disable module storage.
  110. // The unit test for mw.loader.store will enable it
  111. // explicitly with a mock timer.
  112. mw.loader.store.enabled = false;
  113. JAVASCRIPT;
  114. // The following has to be deferred via RLQ because the startup module is asynchronous.
  115. $code .= ResourceLoader::makeLoaderConditionalScript(
  116. // Embed page-specific mw.config variables.
  117. // The current Special page shouldn't be relevant to tests, but various modules (which
  118. // are loaded before the test suites), reference mw.config while initialising.
  119. ResourceLoader::makeConfigSetScript( $out->getJSVars() )
  120. // Embed private modules as they're not allowed to be loaded dynamically
  121. . $rl->makeModuleResponse( $embedContext, [
  122. 'user.options' => $rl->getModule( 'user.options' ),
  123. 'user.tokens' => $rl->getModule( 'user.tokens' ),
  124. ] )
  125. // Load all the test suites
  126. . Xml::encodeJsCall( 'mw.loader.load', [ $modules ] )
  127. );
  128. $encModules = Xml::encodeJsVar( $modules );
  129. $code .= ResourceLoader::makeInlineCodeWithModule( 'mediawiki.base', <<<JAVASCRIPT
  130. var start = window.__karma__ ? window.__karma__.start : QUnit.start;
  131. mw.loader.using( $encModules ).always( start );
  132. mw.trackSubscribe( 'resourceloader.exception', function ( topic, err ) {
  133. // Things like "dependency missing" or "unknown module".
  134. // Re-throw so that they are reported as global exceptions by QUnit and Karma.
  135. setTimeout( function () {
  136. throw err;
  137. } );
  138. } );
  139. JAVASCRIPT
  140. );
  141. header( 'Content-Type: text/javascript; charset=utf-8' );
  142. header( 'Cache-Control: private, no-cache, must-revalidate' );
  143. header( 'Pragma: no-cache' );
  144. echo $qunitConfig;
  145. echo $code;
  146. }
  147. private function plainQUnit() {
  148. $out = $this->getOutput();
  149. $out->disable();
  150. $styles = $out->makeResourceLoaderLink( 'jquery.qunit',
  151. ResourceLoaderModule::TYPE_STYLES
  152. );
  153. // Use 'raw' because QUnit loads before ResourceLoader initialises (omit mw.loader.state call)
  154. // Use 'sync' to ensure OutputPage doesn't use the "async" attribute because QUnit must
  155. // load before qunit/export.
  156. $scripts = $out->makeResourceLoaderLink( 'jquery.qunit',
  157. ResourceLoaderModule::TYPE_SCRIPTS,
  158. [ 'raw' => '1', 'sync' => '1' ]
  159. );
  160. $head = implode( "\n", [ $styles, $scripts ] );
  161. $summary = $this->getSummaryHtml();
  162. $html = <<<HTML
  163. <!DOCTYPE html>
  164. <title>QUnit</title>
  165. $head
  166. $summary
  167. <div id="qunit"></div>
  168. HTML;
  169. $url = $this->getPageTitle( 'qunit/export' )->getFullURL( [
  170. 'debug' => ResourceLoader::inDebugMode() ? 'true' : 'false',
  171. ] );
  172. $html .= "\n" . Html::linkedScript( $url );
  173. header( 'Content-Type: text/html; charset=utf-8' );
  174. echo $html;
  175. }
  176. protected function getGroupName() {
  177. return 'other';
  178. }
  179. }