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.
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 ResourceLoader::makeConfigSetScript( [
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 private modules as they're not allowed to be loaded dynamically
141 . $rl->makeModuleResponse( $embedContext, [
142 'user.options' => $rl->getModule( 'user.options' ),
143 ] )
144 // Load all the test modules
145 . Html::encodeJsCall( 'mw.loader.load', [ $modules ] )
146 );
147 $encModules = Html::encodeJsVar( $modules );
148 $code .= ResourceLoader::makeInlineCodeWithModule( 'mediawiki.base', <<<JAVASCRIPT
149 // Wait for each module individually, so that partial failures wont break the page
150 // completely by rejecting the promise before all/ any modules are loaded.
151 var promises = $encModules.map( function( module ) {
152 return mw.loader.using( module ).promise();
153 } );
154 Promise.allSettled( promises ).then( QUnit.start );
155JAVASCRIPT
156 );
157
158 header( 'Content-Type: text/javascript; charset=utf-8' );
159 header( 'Cache-Control: private, no-cache, must-revalidate' );
160 echo $code;
161 }
162
163 private function renderPage() {
164 $req = $this->getContext()->getRequest();
165 $component = $req->getRawVal( 'component' );
166 // If set, validate
167 $this->getModulesForComponentOrThrow( $component );
168
169 $basePath = $this->getConfig()->get( MainConfigNames::ResourceBasePath );
170 $headHtml = implode( "\n", [
171 Html::linkedStyle( "$basePath/resources/lib/qunitjs/qunit.css" ),
172 Html::linkedStyle( "$basePath/resources/src/qunitjs/qunit-local.css" ),
173 ] );
174
175 $scriptUrl = $this->getPageTitle( 'qunit/export' )->getFullURL( [
176 'debug' => $req->getRawVal( 'debug' ) ?? '0',
177 'component' => $component,
178 ] );
179 $script = implode( "\n", [
180 Html::linkedScript( "$basePath/resources/lib/qunitjs/qunit.js" ),
181 Html::inlineScript( 'QUnit.config.autostart = false;' ),
182 Html::linkedScript( $scriptUrl ),
183 ] );
184
185 header( 'Content-Type: text/html; charset=utf-8' );
186 echo <<<HTML
187<!DOCTYPE html>
188<title>QUnit</title>
189$headHtml
190<div id="qunit"></div>
191<div id="qunit-fixture"></div>
192$script
193HTML;
194 }
195
197 protected function getGroupName() {
198 return 'other';
199 }
200}
201
203class_alias( SpecialJavaScriptTest::class, 'SpecialJavaScriptTest' );
wfHttpError( $code, $label, $desc)
Provide a simple HTTP error.
if(!defined('MW_SETUP_CALLBACK'))
Definition WebStart.php:68
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:43
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:32
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...