MediaWiki  1.29.1
SpecialJavaScriptTest.php
Go to the documentation of this file.
1 <?php
28 
29  public function __construct() {
30  parent::__construct( 'JavaScriptTest' );
31  }
32 
33  public function execute( $par ) {
34  $out = $this->getOutput();
35 
36  $this->setHeaders();
37  $out->disallowUserJs();
38 
39  // This special page is disabled by default ($wgEnableJavaScriptTest), and contains
40  // no sensitive data. In order to allow TestSwarm to embed it into a test client window,
41  // we need to allow iframing of this page.
42  $out->allowClickjacking();
43 
44  // Sub resource: Internal JavaScript export bundle for QUnit
45  if ( $par === 'qunit/export' ) {
46  $this->exportQUnit();
47  return;
48  }
49 
50  // Regular view: QUnit test runner
51  // (Support "/qunit" and "/qunit/plain" for backwards compatibility)
52  if ( $par === null || $par === '' || $par === 'qunit' || $par === 'qunit/plain' ) {
53  $this->plainQUnit();
54  return;
55  }
56 
57  // Unknown action
58  $out->setStatusCode( 404 );
59  $out->setPageTitle( $this->msg( 'javascripttest' ) );
60  $out->addHTML(
61  '<div class="error">'
62  . $this->msg( 'javascripttest-pagetext-unknownaction' )
63  ->plaintextParams( $par )->parseAsBlock()
64  . '</div>'
65  );
66  }
67 
73  private function getSummaryHtml() {
74  $summary = $this->msg( 'javascripttest-qunit-intro' )
75  ->params( 'https://www.mediawiki.org/wiki/Manual:JavaScript_unit_testing' )
76  ->parseAsBlock();
77  return "<div id=\"mw-javascripttest-summary\">$summary</div>";
78  }
79 
90  private function exportQUnit() {
91  $out = $this->getOutput();
92  $out->disable();
93 
94  $rl = $out->getResourceLoader();
95 
96  $query = [
97  'lang' => $this->getLanguage()->getCode(),
98  'skin' => $this->getSkin()->getSkinName(),
99  'debug' => ResourceLoader::inDebugMode() ? 'true' : 'false',
100  'target' => 'test',
101  ];
102  $embedContext = new ResourceLoaderContext( $rl, new FauxRequest( $query ) );
103  $query['only'] = 'scripts';
104  $startupContext = new ResourceLoaderContext( $rl, new FauxRequest( $query ) );
105 
106  $query['raw'] = true;
107 
108  $modules = $rl->getTestModuleNames( 'qunit' );
109 
110  // Disable autostart because we load modules asynchronously. By default, QUnit would start
111  // at domready when there are no tests loaded and also fire 'QUnit.done' which then instructs
112  // Karma to end the run before the tests even started.
113  $qunitConfig = 'QUnit.config.autostart = false;'
114  . 'if (window.__karma__) {'
115  // karma-qunit's use of autostart=false and QUnit.start conflicts with ours.
116  // Hack around this by replacing 'karma.loaded' with a no-op and call it ourselves later.
117  // See <https://github.com/karma-runner/karma-qunit/issues/27>.
118  . 'window.__karma__.loaded = function () {};'
119  . '}';
120 
121  // The below is essentially a pure-javascript version of OutputPage::headElement().
122  $startup = $rl->makeModuleResponse( $startupContext, [
123  'startup' => $rl->getModule( 'startup' ),
124  ] );
125  // Embed page-specific mw.config variables.
126  // The current Special page shouldn't be relevant to tests, but various modules (which
127  // are loaded before the test suites), reference mw.config while initialising.
128  $code = ResourceLoader::makeConfigSetScript( $out->getJSVars() );
129  // Embed private modules as they're not allowed to be loaded dynamically
130  $code .= $rl->makeModuleResponse( $embedContext, [
131  'user.options' => $rl->getModule( 'user.options' ),
132  'user.tokens' => $rl->getModule( 'user.tokens' ),
133  ] );
134  // Catch exceptions (such as "dependency missing" or "unknown module") so that we
135  // always start QUnit. Re-throw so that they are caught and reported as global exceptions
136  // by QUnit and Karma.
137  $code .= '(function () {'
138  . 'var start = window.__karma__ ? window.__karma__.start : QUnit.start;'
139  . 'try {'
140  . 'mw.loader.using( ' . Xml::encodeJsVar( $modules ) . ' )'
141  . '.always( start )'
142  . '.fail( function ( e ) { throw e; } );'
143  . '} catch ( e ) { start(); throw e; }'
144  . '}());';
145 
146  header( 'Content-Type: text/javascript; charset=utf-8' );
147  header( 'Cache-Control: private, no-cache, must-revalidate' );
148  header( 'Pragma: no-cache' );
149  echo $qunitConfig;
150  echo $startup;
151  // The following has to be deferred via RLQ because the startup module is asynchronous.
152  echo ResourceLoader::makeLoaderConditionalScript( $code );
153  }
154 
155  private function plainQUnit() {
156  $out = $this->getOutput();
157  $out->disable();
158 
159  $styles = $out->makeResourceLoaderLink( 'jquery.qunit',
161  );
162 
163  // Use 'raw' because QUnit loads before ResourceLoader initialises (omit mw.loader.state call)
164  // Use 'test' to ensure OutputPage doesn't use the "async" attribute because QUnit must
165  // load before qunit/export.
166  $scripts = $out->makeResourceLoaderLink( 'jquery.qunit',
168  [ 'raw' => true, 'sync' => true ]
169  );
170 
171  $head = implode( "\n", [ $styles, $scripts ] );
172  $summary = $this->getSummaryHtml();
173  $html = <<<HTML
174 <!DOCTYPE html>
175 <title>QUnit</title>
176 $head
177 $summary
178 <div id="qunit"></div>
179 HTML;
180 
181  $url = $this->getPageTitle( 'qunit/export' )->getFullURL( [
182  'debug' => ResourceLoader::inDebugMode() ? 'true' : 'false',
183  ] );
184  $html .= "\n" . Html::linkedScript( $url );
185 
186  header( 'Content-Type: text/html; charset=utf-8' );
187  echo $html;
188  }
189 
195  public function getSubpagesForPrefixSearch() {
196  return self::$frameworks;
197  }
198 
199  protected function getGroupName() {
200  return 'other';
201  }
202 }
SpecialPage\getPageTitle
getPageTitle( $subpage=false)
Get a self-referential title object.
Definition: SpecialPage.php:628
ResourceLoaderContext
Object passed around to modules which contains information about the state of a specific loader reque...
Definition: ResourceLoaderContext.php:32
FauxRequest
WebRequest clone which takes values from a provided array.
Definition: FauxRequest.php:33
SpecialJavaScriptTest\execute
execute( $par)
Default execute method Checks user permissions.
Definition: SpecialJavaScriptTest.php:33
SpecialJavaScriptTest\getSummaryHtml
getSummaryHtml()
Get summary text wrapped in a container.
Definition: SpecialJavaScriptTest.php:73
SpecialJavaScriptTest\getSubpagesForPrefixSearch
getSubpagesForPrefixSearch()
Return an array of subpages that this special page will accept.
Definition: SpecialJavaScriptTest.php:195
SpecialPage\getOutput
getOutput()
Get the OutputPage being used for this instance.
Definition: SpecialPage.php:675
SpecialJavaScriptTest\getGroupName
getGroupName()
Under which header this special page is listed in Special:SpecialPages See messages 'specialpages-gro...
Definition: SpecialJavaScriptTest.php:199
SpecialPage\getSkin
getSkin()
Shortcut to get the skin being used for this instance.
Definition: SpecialPage.php:695
SpecialPage\getLanguage
getLanguage()
Shortcut to get user's language.
Definition: SpecialPage.php:705
Xml\encodeJsVar
static encodeJsVar( $value, $pretty=false)
Encode a variable of arbitrary type to JavaScript.
Definition: Xml.php:627
php
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
$query
null for the wiki Added should default to null in handler for backwards compatibility add a value to it if you want to add a cookie that have to vary cache options can modify $query
Definition: hooks.txt:1572
$html
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses & $html
Definition: hooks.txt:1956
SpecialJavaScriptTest\__construct
__construct()
Definition: SpecialJavaScriptTest.php:29
SpecialJavaScriptTest\plainQUnit
plainQUnit()
Definition: SpecialJavaScriptTest.php:155
Html\linkedScript
static linkedScript( $url)
Output a "<script>" tag linking to the given URL, e.g., "<script src=foo.js></script>".
Definition: Html.php:600
$modules
$modules
Definition: HTMLFormElement.php:12
ResourceLoaderModule\TYPE_SCRIPTS
const TYPE_SCRIPTS
Definition: ResourceLoaderModule.php:36
div
div
Definition: parserTests.txt:6533
SpecialPage\setHeaders
setHeaders()
Sets headers - this should be called from the execute() method of all derived classes!
Definition: SpecialPage.php:484
SpecialPage\msg
msg()
Wrapper around wfMessage that sets the current context.
Definition: SpecialPage.php:746
SpecialPage
Parent class for all special pages.
Definition: SpecialPage.php:36
title
title
Definition: parserTests.txt:211
SpecialJavaScriptTest
Definition: SpecialJavaScriptTest.php:27
SpecialJavaScriptTest\exportQUnit
exportQUnit()
Generate self-sufficient JavaScript payload to run the tests elsewhere.
Definition: SpecialJavaScriptTest.php:90
$code
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable & $code
Definition: hooks.txt:783
ResourceLoaderModule\TYPE_STYLES
const TYPE_STYLES
Definition: ResourceLoaderModule.php:37
$out
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output $out
Definition: hooks.txt:783