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