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