MediaWiki  master
SpecialJavaScriptTest.php
Go to the documentation of this file.
1 <?php
27 
32 
33  public function __construct() {
34  parent::__construct( 'JavaScriptTest' );
35  }
36 
37  public function execute( $par ) {
38  $this->getOutput()->disable();
39 
40  if ( $par === 'qunit/export' ) {
41  // Send the JavaScript payload.
42  $this->exportJS();
43  } elseif ( $par === null || $par === '' || $par === 'qunit' || $par === 'qunit/plain' ) {
44  // Render the page
45  // (Support "/qunit" and "/qunit/plain" for backwards-compatibility)
46  $this->renderPage();
47  } else {
48  wfHttpError( 404, 'Unknown action', "Unknown action \"$par\"." );
49  }
50  }
51 
57  private function exportJS() {
58  $out = $this->getOutput();
59  $rl = $out->getResourceLoader();
60 
61  // Allow framing (disabling wgBreakFrames). Otherwise, mediawiki.page.ready
62  // will close this tab when running from CLI using karma-qunit.
63  $out->setPreventClickjacking( false );
64 
65  $query = [
66  'lang' => 'qqx',
67  'skin' => 'fallback',
68  'debug' => (string)ResourceLoader::inDebugMode(),
69  'target' => 'test',
70  ];
71  $embedContext = new RL\Context( $rl, new FauxRequest( $query ) );
72  $query['only'] = 'scripts';
73  $startupContext = new RL\Context( $rl, new FauxRequest( $query ) );
74 
75  $modules = $rl->getTestSuiteModuleNames();
76  $component = $this->getContext()->getRequest()->getVal( 'component' );
77  if ( $component ) {
78  $module = 'test.' . $component;
79  if ( !in_array( 'test.' . $component, $modules ) ) {
81  404,
82  'Unknown test module',
83  "'$module' is not a defined test module. "
84  . 'Register one via the QUnitTestModules attribute in extension.json.'
85  );
86  return;
87  }
88  $modules = [ 'test.' . $component ];
89  }
90 
91  // Disable module storage.
92  // The unit test for mw.loader.store will enable it (with a mock timers).
93  $config = new MultiConfig( [
94  new HashConfig( [ MainConfigNames::ResourceLoaderStorageEnabled => false ] ),
95  $rl->getConfig(),
96  ] );
97 
98  // Disable autostart because we load modules asynchronously. By default, QUnit would start
99  // at domready when there are no tests loaded and also fire 'QUnit.done' which then instructs
100  // Karma to exit the browser process before the tests even finished loading.
101  $qunitConfig = 'QUnit.config.autostart = false;'
102  . 'if (window.__karma__) {'
103  // karma-qunit's use of autostart=false and QUnit.start conflicts with ours.
104  // Hack around this by replacing 'karma.loaded' with a no-op and perform its duty of calling
105  // `__karma__.start()` ourselves. See <https://github.com/karma-runner/karma-qunit/issues/27>.
106  . 'window.__karma__.loaded = function () {};'
107  . '}';
108 
109  // The below is essentially a pure-javascript version of OutputPage::headElement().
110  $startupModule = $rl->getModule( 'startup' );
111  $startupModule->setConfig( $config );
112  $code = $rl->makeModuleResponse( $startupContext, [ 'startup' => $startupModule ] );
113  // The following has to be deferred via RLQ because the startup module is asynchronous.
114  $code .= ResourceLoader::makeLoaderConditionalScript(
115  // Embed page-specific mw.config variables.
116  //
117  // For compatibility with older tests, these will come from the user
118  // action "viewing Special:JavaScripTest".
119  //
120  // This is deprecated since MediaWiki 1.25 and slowly being phased out in favour of:
121  // 1. tests explicitly mocking the configuration they depend on.
122  // 2. tests explicitly skipping or not loading code that is only meant
123  // for real page views (e.g. not loading as dependency, or using a QUnit
124  // conditional).
125  //
126  // See https://phabricator.wikimedia.org/T89434.
127  // Keep a select few that are commonly referenced.
128  ResourceLoader::makeConfigSetScript( [
129  // used by mediawiki.util
130  'wgPageName' => 'Special:Badtitle/JavaScriptTest',
131  // used as input for mw.Title
132  'wgRelevantPageName' => 'Special:Badtitle/JavaScriptTest',
133  ] )
134  // Embed private modules as they're not allowed to be loaded dynamically
135  . $rl->makeModuleResponse( $embedContext, [
136  'user.options' => $rl->getModule( 'user.options' ),
137  ] )
138  // Load all the test suites
139  . Xml::encodeJsCall( 'mw.loader.load', [ $modules ] )
140  );
141  $encModules = Xml::encodeJsVar( $modules );
142  $code .= ResourceLoader::makeInlineCodeWithModule( 'mediawiki.base', <<<JAVASCRIPT
143  var start = window.__karma__ ? window.__karma__.start : QUnit.start;
144  mw.loader.using( $encModules ).always( start );
145  mw.trackSubscribe( 'resourceloader.exception', function ( topic, err ) {
146  // Things like "dependency missing" or "unknown module".
147  // Re-throw so that they are reported as global exceptions by QUnit and Karma.
148  setTimeout( function () {
149  throw err;
150  } );
151  } );
152 JAVASCRIPT
153  );
154 
155  header( 'Content-Type: text/javascript; charset=utf-8' );
156  header( 'Cache-Control: private, no-cache, must-revalidate' );
157  header( 'Pragma: no-cache' );
158  echo $qunitConfig;
159  echo $code;
160  }
161 
162  private function renderPage() {
163  $basePath = $this->getConfig()->get( MainConfigNames::ResourceBasePath );
164  $headHtml = implode( "\n", [
165  Html::linkedScript( "$basePath/resources/lib/qunitjs/qunit.js" ),
166  Html::linkedStyle( "$basePath/resources/lib/qunitjs/qunit.css" ),
167  Html::linkedStyle( "$basePath/resources/src/qunitjs/qunit-local.css" ),
168  ] );
169 
170  $introHtml = $this->msg( 'javascripttest-qunit-intro' )
171  ->params( 'https://www.mediawiki.org/wiki/Manual:JavaScript_unit_testing' )
172  ->parseAsBlock();
173 
174  $scriptUrl = $this->getPageTitle( 'qunit/export' )->getFullURL( [
175  'debug' => (string)ResourceLoader::inDebugMode(),
176  ] );
177  $script = Html::linkedScript( $scriptUrl );
178 
179  header( 'Content-Type: text/html; charset=utf-8' );
180  echo <<<HTML
181 <!DOCTYPE html>
182 <title>QUnit</title>
183 $headHtml
184 $introHtml
185 <div id="qunit"></div>
186 $script
187 HTML;
188  }
189 
190  protected function getGroupName() {
191  return 'other';
192  }
193 }
wfHttpError( $code, $label, $desc)
Provide a simple HTTP error.
$modules
WebRequest clone which takes values from a provided array.
Definition: FauxRequest.php:37
A Config instance which stores all settings as a member variable.
Definition: HashConfig.php:30
static linkedScript( $url, $nonce=null)
Output a "<script>" tag linking to the given URL, e.g., "<script src=foo.js></script>".
Definition: Html.php:617
static linkedStyle( $url, $media='all')
Output a "<link rel=stylesheet>" linking to the given URL for the given media type (if any).
Definition: Html.php:669
A class containing constants representing the names of configuration variables.
Context object that contains information about the state of a specific ResourceLoader web request.
Definition: Context.php:46
ResourceLoader is a loading system for JavaScript and CSS resources.
Provides a fallback sequence for Config objects.
Definition: MultiConfig.php:28
execute( $par)
Default execute method Checks user permissions.
getGroupName()
Under which header this special page is listed in Special:SpecialPages See messages 'specialpages-gro...
exportJS()
Send the standalone JavaScript payload.
Parent class for all special pages.
Definition: SpecialPage.php:44
getOutput()
Get the OutputPage being used for this instance.
getContext()
Gets the context this SpecialPage is executed in.
msg( $key,... $params)
Wrapper around wfMessage that sets the current context.
getConfig()
Shortcut to get main config object.
getPageTitle( $subpage=false)
Get a self-referential title object.
static encodeJsVar( $value, $pretty=false)
Encode a variable of arbitrary type to JavaScript.
Definition: Xml.php:678
static encodeJsCall( $name, $args, $pretty=false)
Create a call to a JavaScript function.
Definition: Xml.php:696