MediaWiki master
SpecialJavaScriptTest.php
Go to the documentation of this file.
1<?php
7namespace MediaWiki\Specials;
8
18
24
25 public function __construct() {
26 parent::__construct( 'JavaScriptTest' );
27 }
28
30 public function execute( $par ) {
31 $this->getOutput()->disable();
32
33 if ( $par === 'qunit/export' ) {
34 // Send the JavaScript payload.
35 $this->exportJS();
36 } elseif ( $par === null || $par === '' || $par === 'qunit' || $par === 'qunit/plain' ) {
37 // Render the page
38 // (Support "/qunit" and "/qunit/plain" for backwards-compatibility)
39 $this->renderPage();
40 } else {
41 wfHttpError( 404, 'Unknown action', "Unknown action \"$par\"." );
42 }
43 }
44
45 private function getComponents(): array {
46 $components = [];
47
48 $rl = $this->getOutput()->getResourceLoader();
49 foreach ( $rl->getTestSuiteModuleNames() as $module ) {
50 if ( str_starts_with( $module, 'test.' ) ) {
51 $components[] = substr( $module, 5 );
52 }
53 }
54
55 return $components;
56 }
57
61 private function getModulesForComponentOrThrow( ?string $component ): array {
62 if ( $component !== null ) {
63 if ( !in_array( $component, $this->getComponents() ) ) {
64 throw new HttpError(
65 404,
66 "No test module found for the '$component' component.\n"
67 . "Make sure the extension is enabled via wfLoadExtension(),\n"
68 . "and register a test module via the QUnitTestModule attribute in extension.json.",
69 'Unknown component',
70 );
71 }
72 return [ 'test.' . $component ];
73 } else {
74 $rl = $this->getOutput()->getResourceLoader();
75 return $rl->getTestSuiteModuleNames();
76 }
77 }
78
84 private function exportJS() {
85 $out = $this->getOutput();
86 $req = $this->getContext()->getRequest();
87 $rl = $out->getResourceLoader();
88
89 // Allow framing (disabling wgBreakFrames). Otherwise, mediawiki.page.ready
90 // will close this tab when running from CLI using karma-qunit.
91 $out->getMetadata()->setPreventClickjacking( false );
92
93 $query = [
94 'lang' => 'qqx',
95 'skin' => 'fallback',
96 'debug' => $req->getRawVal( 'debug' ),
97 'target' => 'test',
98 ];
99 $embedContext = new RL\Context( $rl, new FauxRequest( $query ) );
100 $query['only'] = 'scripts';
101 $startupContext = new RL\Context( $rl, new FauxRequest( $query ) );
102
103 $component = $req->getRawVal( 'component' );
104 $modules = $this->getModulesForComponentOrThrow( $component );
105
106 // Disable module storage.
107 // The unit test for mw.loader.store will enable it (with a mock timers).
108 $config = new MultiConfig( [
109 new HashConfig( [ MainConfigNames::ResourceLoaderStorageEnabled => false ] ),
110 $rl->getConfig(),
111 ] );
112
113 // The below is essentially a pure-javascript version of OutputPage::headElement().
114 $startupModule = $rl->getModule( 'startup' );
115 $startupModule->setConfig( $config );
116 $code = $rl->makeModuleResponse( $startupContext, [ 'startup' => $startupModule ] );
117 // The following has to be deferred via RLQ because the startup module is asynchronous.
118 $code .= ResourceLoader::makeLoaderConditionalScript(
119 // Embed page-specific mw.config variables (substitute for OutputPage::getJSVars)
120 //
121 // For compatibility with older tests, these will come from the user
122 // action "viewing Special:JavaScripTest".
123 //
124 // This is deprecated since MediaWiki 1.25 and slowly being phased out in favour of:
125 // 1. tests explicitly mocking the configuration they depend on.
126 // 2. tests explicitly skipping or not loading code that is only meant
127 // for real page views (e.g. not loading as dependency, or using a QUnit
128 // conditional).
129 //
130 // See https://phabricator.wikimedia.org/T89434.
131 // Keep a select few that are commonly referenced.
132 'mw.config.set(' . $embedContext->encodeJson( [
133 // used by mediawiki.util
134 'wgPageName' => 'Special:Badtitle/JavaScriptTest',
135 // used as input for mw.Title
136 'wgRelevantPageName' => 'Special:Badtitle/JavaScriptTest',
137 // used by testrunner.js for QUnit toolbar
138 'wgTestModuleComponents' => $this->getComponents(),
139 ] ) . ');'
140 // Embed site-wide mw.config variables (override ResourceLoader::getSiteConfigSettings)
141 //
142 // To ensure stable testing irrespective of the developer's LocalSettings.php file,
143 // inspired by T277470.
144 . 'mw.config.set(' . $embedContext->encodeJson( [
145 // used by mediawiki.Title
146 'wgCaseSensitiveNamespaces' => [],
147 ] ) . ');'
148 // Embed private modules as they're not allowed to be loaded dynamically
149 . $rl->makeModuleResponse( $embedContext, [
150 'user.options' => $rl->getModule( 'user.options' ),
151 ] )
152 // Load all the test modules
153 . Html::encodeJsCall( 'mw.loader.load', [ $modules ] )
154 );
155 $encModules = Html::encodeJsVar( $modules );
156 $code .= ResourceLoader::makeInlineCodeWithModule( 'mediawiki.base', <<<JAVASCRIPT
157 // Wait for each module individually, so that partial failures wont break the page
158 // completely by rejecting the promise before all/ any modules are loaded.
159 var promises = $encModules.map( function( module ) {
160 return mw.loader.using( module ).promise();
161 } );
162 Promise.allSettled( promises ).then( QUnit.start );
163JAVASCRIPT
164 );
165
166 header( 'Content-Type: text/javascript; charset=utf-8' );
167 header( 'Cache-Control: private, no-cache, must-revalidate' );
168 echo $code;
169 }
170
171 private function renderPage() {
172 $req = $this->getContext()->getRequest();
173 $component = $req->getRawVal( 'component' );
174 // If set, validate
175 $this->getModulesForComponentOrThrow( $component );
176
177 $basePath = $this->getConfig()->get( MainConfigNames::ResourceBasePath );
178 $headHtml = implode( "\n", [
179 Html::linkedStyle( "$basePath/resources/lib/qunitjs/qunit.css" ),
180 Html::linkedStyle( "$basePath/resources/src/qunitjs/qunit-local.css" ),
181 ] );
182
183 $scriptUrl = $this->getPageTitle( 'qunit/export' )->getFullURL( [
184 'debug' => $req->getRawVal( 'debug' ) ?? '0',
185 'component' => $component,
186 ] );
187 $script = implode( "\n", [
188 Html::linkedScript( "$basePath/resources/lib/qunitjs/qunit.js" ),
189 Html::inlineScript( 'QUnit.config.autostart = false;' ),
190 Html::linkedScript( $scriptUrl ),
191 ] );
192
193 header( 'Content-Type: text/html; charset=utf-8' );
194 echo <<<HTML
195<!DOCTYPE html>
196<title>QUnit</title>
197$headHtml
198<div id="qunit"></div>
199<div id="qunit-fixture"></div>
200$script
201HTML;
202 }
203
205 protected function getGroupName() {
206 return 'other';
207 }
208}
209
210// @codeCoverageIgnoreStart
212class_alias( SpecialJavaScriptTest::class, 'SpecialJavaScriptTest' );
213// @codeCoverageIgnoreEnd
wfHttpError( $code, $label, $desc)
Provide a simple HTTP error.
if(!defined('MW_SETUP_CALLBACK'))
Definition WebStart.php:71
A Config instance which stores all settings as a member variable.
Provides a fallback sequence for Config objects.
Show an error that looks like an HTTP server error.
Definition HttpError.php:23
This class is a collection of static functions that serve two purposes:
Definition Html.php:44
A class containing constants representing the names of configuration variables.
WebRequest clone which takes values from a provided array.
Context object that contains information about the state of a specific ResourceLoader web request.
Definition Context.php:35
ResourceLoader is a loading system for JavaScript and CSS resources.
Parent class for all special pages.
getOutput()
Get the OutputPage being used for this instance.
execute( $par)
Default execute method Checks user permissions.This must be overridden by subclasses; it will be made...
getGroupName()
Under which header this special page is listed in Special:SpecialPages See messages 'specialpages-gro...