Merge "Remove .mw-help-field-hint and -data CSS classes from mw.legacy/shared"
[lhc/web/wiklou.git] / tests / parser / ParserTestRunner.php
1 <?php
2 /**
3 * Generic backend for the MediaWiki parser test suite, used by both the
4 * standalone parserTests.php and the PHPUnit "parsertests" suite.
5 *
6 * Copyright © 2004, 2010 Brion Vibber <brion@pobox.com>
7 * https://www.mediawiki.org/
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
23 *
24 * @todo Make this more independent of the configuration (and if possible the database)
25 * @file
26 * @ingroup Testing
27 */
28 use MediaWiki\MediaWikiServices;
29
30 /**
31 * @ingroup Testing
32 */
33 class ParserTestRunner {
34 /**
35 * @var bool $useTemporaryTables Use temporary tables for the temporary database
36 */
37 private $useTemporaryTables = true;
38
39 /**
40 * @var array $setupDone The status of each setup function
41 */
42 private $setupDone = [
43 'staticSetup' => false,
44 'perTestSetup' => false,
45 'setupDatabase' => false,
46 'setDatabase' => false,
47 'setupUploads' => false,
48 ];
49
50 /**
51 * Our connection to the database
52 * @var DatabaseBase
53 */
54 private $db;
55
56 /**
57 * Database clone helper
58 * @var CloneDatabase
59 */
60 private $dbClone;
61
62 /**
63 * @var DjVuSupport
64 */
65 private $djVuSupport;
66
67 /**
68 * @var TidySupport
69 */
70 private $tidySupport;
71
72 /**
73 * @var TidyDriverBase
74 */
75 private $tidyDriver = null;
76
77 /**
78 * @var TestRecorder
79 */
80 private $recorder;
81
82 /**
83 * The upload directory, or null to not set up an upload directory
84 *
85 * @var string|null
86 */
87 private $uploadDir = null;
88
89 /**
90 * The name of the file backend to use, or null to use MockFileBackend.
91 * @var string|null
92 */
93 private $fileBackendName;
94
95 /**
96 * A complete regex for filtering tests.
97 * @var string
98 */
99 private $regex;
100
101 /**
102 * A list of normalization functions to apply to the expected and actual
103 * output.
104 * @var array
105 */
106 private $normalizationFunctions = [];
107
108 /**
109 * @param TestRecorder $recorder
110 * @param array $options
111 */
112 public function __construct( TestRecorder $recorder, $options = [] ) {
113 $this->recorder = $recorder;
114
115 if ( isset( $options['norm'] ) ) {
116 foreach ( $options['norm'] as $func ) {
117 if ( in_array( $func, [ 'removeTbody', 'trimWhitespace' ] ) ) {
118 $this->normalizationFunctions[] = $func;
119 } else {
120 $this->recorder->warning(
121 "Warning: unknown normalization option \"$func\"\n" );
122 }
123 }
124 }
125
126 if ( isset( $options['regex'] ) && $options['regex'] !== false ) {
127 $this->regex = $options['regex'];
128 } else {
129 # Matches anything
130 $this->regex = '//';
131 }
132
133 $this->keepUploads = !empty( $options['keep-uploads'] );
134
135 $this->fileBackendName = isset( $options['file-backend'] ) ?
136 $options['file-backend'] : false;
137
138 $this->runDisabled = !empty( $options['run-disabled'] );
139 $this->runParsoid = !empty( $options['run-parsoid'] );
140
141 $this->djVuSupport = new DjVuSupport();
142 $this->tidySupport = new TidySupport( !empty( $options['use-tidy-config'] ) );
143 if ( !$this->tidySupport->isEnabled() ) {
144 $this->recorder->warning(
145 "Warning: tidy is not installed, skipping some tests\n" );
146 }
147
148 if ( isset( $options['upload-dir'] ) ) {
149 $this->uploadDir = $options['upload-dir'];
150 }
151 }
152
153 public function getRecorder() {
154 return $this->recorder;
155 }
156
157 /**
158 * Do any setup which can be done once for all tests, independent of test
159 * options, except for database setup.
160 *
161 * Public setup functions in this class return a ScopedCallback object. When
162 * this object is destroyed by going out of scope, teardown of the
163 * corresponding test setup is performed.
164 *
165 * Teardown objects may be chained by passing a ScopedCallback from a
166 * previous setup stage as the $nextTeardown parameter. This enforces the
167 * convention that teardown actions are taken in reverse order to the
168 * corresponding setup actions. When $nextTeardown is specified, a
169 * ScopedCallback will be returned which first tears down the current
170 * setup stage, and then tears down the previous setup stage which was
171 * specified by $nextTeardown.
172 *
173 * @param ScopedCallback|null $nextTeardown
174 * @return ScopedCallback
175 */
176 public function staticSetup( $nextTeardown = null ) {
177 // A note on coding style:
178
179 // The general idea here is to keep setup code together with
180 // corresponding teardown code, in a fine-grained manner. We have two
181 // arrays: $setup and $teardown. The code snippets in the $setup array
182 // are executed at the end of the method, before it returns, and the
183 // code snippets in the $teardown array are executed in reverse order
184 // when the ScopedCallback object is consumed.
185
186 // Because it is a common operation to save, set and restore global
187 // variables, we have an additional convention: when the array key of
188 // $setup is a string, the string is taken to be the name of the global
189 // variable, and the element value is taken to be the desired new value.
190
191 // It's acceptable to just do the setup immediately, instead of adding
192 // a closure to $setup, except when the setup action depends on global
193 // variable initialisation being done first. In this case, you have to
194 // append a closure to $setup after the global variable is appended.
195
196 // When you add to setup functions in this class, please keep associated
197 // setup and teardown actions together in the source code, and please
198 // add comments explaining why the setup action is necessary.
199
200 $setup = [];
201 $teardown = [];
202
203 $teardown[] = $this->markSetupDone( 'staticSetup' );
204
205 // Some settings which influence HTML output
206 $setup['wgSitename'] = 'MediaWiki';
207 $setup['wgServer'] = 'http://example.org';
208 $setup['wgServerName'] = 'example.org';
209 $setup['wgScriptPath'] = '';
210 $setup['wgScript'] = '/index.php';
211 $setup['wgResourceBasePath'] = '';
212 $setup['wgStylePath'] = '/skins';
213 $setup['wgExtensionAssetsPath'] = '/extensions';
214 $setup['wgArticlePath'] = '/wiki/$1';
215 $setup['wgActionPaths'] = [];
216 $setup['wgVariantArticlePath'] = false;
217 $setup['wgUploadNavigationUrl'] = false;
218 $setup['wgCapitalLinks'] = true;
219 $setup['wgNoFollowLinks'] = true;
220 $setup['wgNoFollowDomainExceptions'] = [ 'no-nofollow.org' ];
221 $setup['wgExternalLinkTarget'] = false;
222 $setup['wgExperimentalHtmlIds'] = false;
223 $setup['wgLocaltimezone'] = 'UTC';
224 $setup['wgHtml5'] = true;
225 $setup['wgDisableLangConversion'] = false;
226 $setup['wgDisableTitleConversion'] = false;
227
228 // "extra language links"
229 // see https://gerrit.wikimedia.org/r/111390
230 $setup['wgExtraInterlanguageLinkPrefixes'] = [ 'mul' ];
231
232 // All FileRepo changes should be done here by injecting services,
233 // there should be no need to change global variables.
234 RepoGroup::setSingleton( $this->createRepoGroup() );
235 $teardown[] = function () {
236 RepoGroup::destroySingleton();
237 };
238
239 // Set up null lock managers
240 $setup['wgLockManagers'] = [ [
241 'name' => 'fsLockManager',
242 'class' => 'NullLockManager',
243 ], [
244 'name' => 'nullLockManager',
245 'class' => 'NullLockManager',
246 ] ];
247 $reset = function() {
248 LockManagerGroup::destroySingletons();
249 };
250 $setup[] = $reset;
251 $teardown[] = $reset;
252
253 // This allows article insertion into the prefixed DB
254 $setup['wgDefaultExternalStore'] = false;
255
256 // This might slightly reduce memory usage
257 $setup['wgAdaptiveMessageCache'] = true;
258
259 // This is essential and overrides disabling of database messages in TestSetup
260 $setup['wgUseDatabaseMessages'] = true;
261 $reset = function () {
262 MessageCache::destroyInstance();
263 };
264 $setup[] = $reset;
265 $teardown[] = $reset;
266
267 // It's not necessary to actually convert any files
268 $setup['wgSVGConverter'] = 'null';
269 $setup['wgSVGConverters'] = [ 'null' => 'echo "1">$output' ];
270
271 // Fake constant timestamp
272 Hooks::register( 'ParserGetVariableValueTs', 'ParserTestRunner::getFakeTimestamp' );
273 $teardown[] = function () {
274 Hooks::clear( 'ParserGetVariableValueTs' );
275 };
276
277 $this->appendNamespaceSetup( $setup, $teardown );
278
279 // Set up interwikis and append teardown function
280 $teardown[] = $this->setupInterwikis();
281
282 // This affects title normalization in links. It invalidates
283 // MediaWikiTitleCodec objects.
284 $setup['wgLocalInterwikis'] = [ 'local', 'mi' ];
285 $reset = function () {
286 $this->resetTitleServices();
287 };
288 $setup[] = $reset;
289 $teardown[] = $reset;
290
291 // Set up a mock MediaHandlerFactory
292 MediaWikiServices::getInstance()->disableService( 'MediaHandlerFactory' );
293 MediaWikiServices::getInstance()->redefineService(
294 'MediaHandlerFactory',
295 function() {
296 return new MockMediaHandlerFactory();
297 }
298 );
299 $teardown[] = function () {
300 MediaWikiServices::getInstance()->resetServiceForTesting( 'MediaHandlerFactory' );
301 };
302
303 // SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
304 // It seems to have been fixed since (r55079?), but regressed at some point before r85701.
305 // This works around it for now...
306 global $wgObjectCaches;
307 $setup['wgObjectCaches'] = [ CACHE_DB => $wgObjectCaches['hash'] ] + $wgObjectCaches;
308 if ( isset( ObjectCache::$instances[CACHE_DB] ) ) {
309 $savedCache = ObjectCache::$instances[CACHE_DB];
310 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
311 $teardown[] = function () use ( $savedCache ) {
312 ObjectCache::$instances[CACHE_DB] = $savedCache;
313 };
314 }
315
316 $teardown[] = $this->executeSetupSnippets( $setup );
317
318 // Schedule teardown snippets in reverse order
319 return $this->createTeardownObject( $teardown, $nextTeardown );
320 }
321
322 private function appendNamespaceSetup( &$setup, &$teardown ) {
323 // Add a namespace shadowing a interwiki link, to test
324 // proper precedence when resolving links. (bug 51680)
325 $setup['wgExtraNamespaces'] = [
326 100 => 'MemoryAlpha',
327 101 => 'MemoryAlpha_talk'
328 ];
329 // Changing wgExtraNamespaces invalidates caches in MWNamespace and
330 // any live Language object, both on setup and teardown
331 $reset = function () {
332 MWNamespace::getCanonicalNamespaces( true );
333 $GLOBALS['wgContLang']->resetNamespaces();
334 };
335 $setup[] = $reset;
336 $teardown[] = $reset;
337 }
338
339 /**
340 * Create a RepoGroup object appropriate for the current configuration
341 * @return RepoGroup
342 */
343 protected function createRepoGroup() {
344 if ( $this->uploadDir ) {
345 if ( $this->fileBackendName ) {
346 throw new MWException( 'You cannot specify both use-filebackend and upload-dir' );
347 }
348 $backend = new FSFileBackend( [
349 'name' => 'local-backend',
350 'wikiId' => wfWikiID(),
351 'basePath' => $this->uploadDir
352 ] );
353 } elseif ( $this->fileBackendName ) {
354 global $wgFileBackends;
355 $name = $this->fileBackendName;
356 $useConfig = false;
357 foreach ( $wgFileBackends as $conf ) {
358 if ( $conf['name'] === $name ) {
359 $useConfig = $conf;
360 }
361 }
362 if ( $useConfig === false ) {
363 throw new MWException( "Unable to find file backend \"$name\"" );
364 }
365 $useConfig['name'] = 'local-backend'; // swap name
366 unset( $useConfig['lockManager'] );
367 unset( $useConfig['fileJournal'] );
368 $class = $useConfig['class'];
369 $backend = new $class( $useConfig );
370 } else {
371 # Replace with a mock. We do not care about generating real
372 # files on the filesystem, just need to expose the file
373 # informations.
374 $backend = new MockFileBackend( [
375 'name' => 'local-backend',
376 'wikiId' => wfWikiID()
377 ] );
378 }
379
380 return new RepoGroup(
381 [
382 'class' => 'LocalRepo',
383 'name' => 'local',
384 'url' => 'http://example.com/images',
385 'hashLevels' => 2,
386 'transformVia404' => false,
387 'backend' => $backend
388 ],
389 []
390 );
391 }
392
393 /**
394 * Execute an array in which elements with integer keys are taken to be
395 * callable objects, and other elements are taken to be global variable
396 * set operations, with the key giving the variable name and the value
397 * giving the new global variable value. A closure is returned which, when
398 * executed, sets the global variables back to the values they had before
399 * this function was called.
400 *
401 * @see staticSetup
402 *
403 * @param array $setup
404 * @return closure
405 */
406 protected function executeSetupSnippets( $setup ) {
407 $saved = [];
408 foreach ( $setup as $name => $value ) {
409 if ( is_int( $name ) ) {
410 $value();
411 } else {
412 $saved[$name] = isset( $GLOBALS[$name] ) ? $GLOBALS[$name] : null;
413 $GLOBALS[$name] = $value;
414 }
415 }
416 return function () use ( $saved ) {
417 $this->executeSetupSnippets( $saved );
418 };
419 }
420
421 /**
422 * Take a setup array in the same format as the one given to
423 * executeSetupSnippets(), and return a ScopedCallback which, when consumed,
424 * executes the snippets in the setup array in reverse order. This is used
425 * to create "teardown objects" for the public API.
426 *
427 * @see staticSetup
428 *
429 * @param array $teardown The snippet array
430 * @param ScopedCallback|null A ScopedCallback to consume
431 * @return ScopedCallback
432 */
433 protected function createTeardownObject( $teardown, $nextTeardown ) {
434 return new ScopedCallback( function() use ( $teardown, $nextTeardown ) {
435 // Schedule teardown snippets in reverse order
436 $teardown = array_reverse( $teardown );
437
438 $this->executeSetupSnippets( $teardown );
439 if ( $nextTeardown ) {
440 ScopedCallback::consume( $nextTeardown );
441 }
442 } );
443 }
444
445 /**
446 * Set a setupDone flag to indicate that setup has been done, and return
447 * the teardown closure. If the flag was already set, throw an exception.
448 *
449 * @param string $funcName The setup function name
450 * @return closure
451 */
452 protected function markSetupDone( $funcName ) {
453 if ( $this->setupDone[$funcName] ) {
454 throw new MWException( "$funcName is already done" );
455 }
456 $this->setupDone[$funcName] = true;
457 return function () use ( $funcName ) {
458 wfDebug( "markSetupDone unmarked $funcName" );
459 $this->setupDone[$funcName] = false;
460 };
461 }
462
463 /**
464 * Ensure a given setup stage has been done, throw an exception if it has
465 * not.
466 */
467 protected function checkSetupDone( $funcName, $funcName2 = null ) {
468 if ( !$this->setupDone[$funcName]
469 && ( $funcName === null || !$this->setupDone[$funcName2] )
470 ) {
471 throw new MWException( "$funcName must be called before calling " .
472 wfGetCaller() );
473 }
474 }
475
476 /**
477 * Determine whether a particular setup function has been run
478 *
479 * @param string $funcName
480 * @return boolean
481 */
482 public function isSetupDone( $funcName ) {
483 return isset( $this->setupDone[$funcName] ) ? $this->setupDone[$funcName] : false;
484 }
485
486 /**
487 * Insert hardcoded interwiki in the lookup table.
488 *
489 * This function insert a set of well known interwikis that are used in
490 * the parser tests. They can be considered has fixtures are injected in
491 * the interwiki cache by using the 'InterwikiLoadPrefix' hook.
492 * Since we are not interested in looking up interwikis in the database,
493 * the hook completely replace the existing mechanism (hook returns false).
494 *
495 * @return closure for teardown
496 */
497 private function setupInterwikis() {
498 # Hack: insert a few Wikipedia in-project interwiki prefixes,
499 # for testing inter-language links
500 Hooks::register( 'InterwikiLoadPrefix', function ( $prefix, &$iwData ) {
501 static $testInterwikis = [
502 'local' => [
503 'iw_url' => 'http://doesnt.matter.org/$1',
504 'iw_api' => '',
505 'iw_wikiid' => '',
506 'iw_local' => 0 ],
507 'wikipedia' => [
508 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
509 'iw_api' => '',
510 'iw_wikiid' => '',
511 'iw_local' => 0 ],
512 'meatball' => [
513 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
514 'iw_api' => '',
515 'iw_wikiid' => '',
516 'iw_local' => 0 ],
517 'memoryalpha' => [
518 'iw_url' => 'http://www.memory-alpha.org/en/index.php/$1',
519 'iw_api' => '',
520 'iw_wikiid' => '',
521 'iw_local' => 0 ],
522 'zh' => [
523 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
524 'iw_api' => '',
525 'iw_wikiid' => '',
526 'iw_local' => 1 ],
527 'es' => [
528 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
529 'iw_api' => '',
530 'iw_wikiid' => '',
531 'iw_local' => 1 ],
532 'fr' => [
533 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
534 'iw_api' => '',
535 'iw_wikiid' => '',
536 'iw_local' => 1 ],
537 'ru' => [
538 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
539 'iw_api' => '',
540 'iw_wikiid' => '',
541 'iw_local' => 1 ],
542 'mi' => [
543 'iw_url' => 'http://mi.wikipedia.org/wiki/$1',
544 'iw_api' => '',
545 'iw_wikiid' => '',
546 'iw_local' => 1 ],
547 'mul' => [
548 'iw_url' => 'http://wikisource.org/wiki/$1',
549 'iw_api' => '',
550 'iw_wikiid' => '',
551 'iw_local' => 1 ],
552 ];
553 if ( array_key_exists( $prefix, $testInterwikis ) ) {
554 $iwData = $testInterwikis[$prefix];
555 }
556
557 // We only want to rely on the above fixtures
558 return false;
559 } );// hooks::register
560
561 return function () {
562 // Tear down
563 Hooks::clear( 'InterwikiLoadPrefix' );
564 };
565 }
566
567 /**
568 * Reset the Title-related services that need resetting
569 * for each test
570 */
571 private function resetTitleServices() {
572 $services = MediaWikiServices::getInstance();
573 $services->resetServiceForTesting( 'TitleFormatter' );
574 $services->resetServiceForTesting( 'TitleParser' );
575 $services->resetServiceForTesting( '_MediaWikiTitleCodec' );
576 $services->resetServiceForTesting( 'LinkRenderer' );
577 $services->resetServiceForTesting( 'LinkRendererFactory' );
578 }
579
580 /**
581 * Remove last character if it is a newline
582 * @group utility
583 * @param string $s
584 * @return string
585 */
586 public static function chomp( $s ) {
587 if ( substr( $s, -1 ) === "\n" ) {
588 return substr( $s, 0, -1 );
589 } else {
590 return $s;
591 }
592 }
593
594 /**
595 * Run a series of tests listed in the given text files.
596 * Each test consists of a brief description, wikitext input,
597 * and the expected HTML output.
598 *
599 * Prints status updates on stdout and counts up the total
600 * number and percentage of passed tests.
601 *
602 * Handles all setup and teardown.
603 *
604 * @param array $filenames Array of strings
605 * @return bool True if passed all tests, false if any tests failed.
606 */
607 public function runTestsFromFiles( $filenames ) {
608 $ok = false;
609
610 $teardownGuard = $this->staticSetup();
611 $teardownGuard = $this->setupDatabase( $teardownGuard );
612 $teardownGuard = $this->setupUploads( $teardownGuard );
613
614 $this->recorder->start();
615 try {
616 $ok = true;
617
618 foreach ( $filenames as $filename ) {
619 $testFileInfo = TestFileReader::read( $filename, [
620 'runDisabled' => $this->runDisabled,
621 'runParsoid' => $this->runParsoid,
622 'regex' => $this->regex ] );
623
624 // Don't start the suite if there are no enabled tests in the file
625 if ( !$testFileInfo['tests'] ) {
626 continue;
627 }
628
629 $this->recorder->startSuite( $filename );
630 $ok = $this->runTests( $testFileInfo ) && $ok;
631 $this->recorder->endSuite( $filename );
632 }
633
634 $this->recorder->report();
635 } catch ( DBError $e ) {
636 $this->recorder->warning( $e->getMessage() );
637 }
638 $this->recorder->end();
639
640 ScopedCallback::consume( $teardownGuard );
641
642 return $ok;
643 }
644
645 /**
646 * Determine whether the current parser has the hooks registered in it
647 * that are required by a file read by TestFileReader.
648 */
649 public function meetsRequirements( $requirements ) {
650 foreach ( $requirements as $requirement ) {
651 switch ( $requirement['type'] ) {
652 case 'hook':
653 $ok = $this->requireHook( $requirement['name'] );
654 break;
655 case 'functionHook':
656 $ok = $this->requireFunctionHook( $requirement['name'] );
657 break;
658 case 'transparentHook':
659 $ok = $this->requireTransparentHook( $requirement['name'] );
660 break;
661 }
662 if ( !$ok ) {
663 return false;
664 }
665 }
666 return true;
667 }
668
669 /**
670 * Run the tests from a single file. staticSetup() and setupDatabase()
671 * must have been called already.
672 *
673 * @param array $testFileInfo Parsed file info returned by TestFileReader
674 * @return bool True if passed all tests, false if any tests failed.
675 */
676 public function runTests( $testFileInfo ) {
677 $ok = true;
678
679 $this->checkSetupDone( 'staticSetup' );
680
681 // Don't add articles from the file if there are no enabled tests from the file
682 if ( !$testFileInfo['tests'] ) {
683 return true;
684 }
685
686 // If any requirements are not met, mark all tests from the file as skipped
687 if ( !$this->meetsRequirements( $testFileInfo['requirements'] ) ) {
688 foreach ( $testFileInfo['tests'] as $test ) {
689 $this->recorder->startTest( $test );
690 $this->recorder->skipped( $test, 'required extension not enabled' );
691 }
692 return true;
693 }
694
695 // Add articles
696 $this->addArticles( $testFileInfo['articles'] );
697
698 // Run tests
699 foreach ( $testFileInfo['tests'] as $test ) {
700 $this->recorder->startTest( $test );
701 $result =
702 $this->runTest( $test );
703 if ( $result !== false ) {
704 $ok = $ok && $result->isSuccess();
705 $this->recorder->record( $test, $result );
706 }
707 }
708
709 return $ok;
710 }
711
712 /**
713 * Get a Parser object
714 *
715 * @param string $preprocessor
716 * @return Parser
717 */
718 function getParser( $preprocessor = null ) {
719 global $wgParserConf;
720
721 $class = $wgParserConf['class'];
722 $parser = new $class( [ 'preprocessorClass' => $preprocessor ] + $wgParserConf );
723 ParserTestParserHook::setup( $parser );
724
725 return $parser;
726 }
727
728 /**
729 * Run a given wikitext input through a freshly-constructed wiki parser,
730 * and compare the output against the expected results.
731 * Prints status and explanatory messages to stdout.
732 *
733 * staticSetup() and setupWikiData() must be called before this function
734 * is entered.
735 *
736 * @param array $test The test parameters:
737 * - test: The test name
738 * - desc: The subtest description
739 * - input: Wikitext to try rendering
740 * - options: Array of test options
741 * - config: Overrides for global variables, one per line
742 *
743 * @return ParserTestResult or false if skipped
744 */
745 public function runTest( $test ) {
746 wfDebug( __METHOD__.": running {$test['desc']}" );
747 $opts = $this->parseOptions( $test['options'] );
748 $teardownGuard = $this->perTestSetup( $test );
749
750 $context = RequestContext::getMain();
751 $user = $context->getUser();
752 $options = ParserOptions::newFromContext( $context );
753
754 if ( isset( $opts['djvu'] ) ) {
755 if ( !$this->djVuSupport->isEnabled() ) {
756 $this->recorder->skipped( $test,
757 'djvu binaries do not exist or are not executable' );
758 return false;
759 }
760 }
761
762 if ( isset( $opts['tidy'] ) ) {
763 if ( !$this->tidySupport->isEnabled() ) {
764 $this->recorder->skipped( $test, 'tidy extension is not installed' );
765 return false;
766 } else {
767 $options->setTidy( true );
768 }
769 }
770
771 if ( isset( $opts['title'] ) ) {
772 $titleText = $opts['title'];
773 } else {
774 $titleText = 'Parser test';
775 }
776
777 $local = isset( $opts['local'] );
778 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
779 $parser = $this->getParser( $preprocessor );
780 $title = Title::newFromText( $titleText );
781
782 if ( isset( $opts['pst'] ) ) {
783 $out = $parser->preSaveTransform( $test['input'], $title, $user, $options );
784 } elseif ( isset( $opts['msg'] ) ) {
785 $out = $parser->transformMsg( $test['input'], $options, $title );
786 } elseif ( isset( $opts['section'] ) ) {
787 $section = $opts['section'];
788 $out = $parser->getSection( $test['input'], $section );
789 } elseif ( isset( $opts['replace'] ) ) {
790 $section = $opts['replace'][0];
791 $replace = $opts['replace'][1];
792 $out = $parser->replaceSection( $test['input'], $section, $replace );
793 } elseif ( isset( $opts['comment'] ) ) {
794 $out = Linker::formatComment( $test['input'], $title, $local );
795 } elseif ( isset( $opts['preload'] ) ) {
796 $out = $parser->getPreloadText( $test['input'], $title, $options );
797 } else {
798 $output = $parser->parse( $test['input'], $title, $options, true, true, 1337 );
799 $output->setTOCEnabled( !isset( $opts['notoc'] ) );
800 $out = $output->getText();
801 if ( isset( $opts['tidy'] ) ) {
802 $out = preg_replace( '/\s+$/', '', $out );
803 }
804
805 if ( isset( $opts['showtitle'] ) ) {
806 if ( $output->getTitleText() ) {
807 $title = $output->getTitleText();
808 }
809
810 $out = "$title\n$out";
811 }
812
813 if ( isset( $opts['showindicators'] ) ) {
814 $indicators = '';
815 foreach ( $output->getIndicators() as $id => $content ) {
816 $indicators .= "$id=$content\n";
817 }
818 $out = $indicators . $out;
819 }
820
821 if ( isset( $opts['ill'] ) ) {
822 $out = implode( ' ', $output->getLanguageLinks() );
823 } elseif ( isset( $opts['cat'] ) ) {
824 $out = '';
825 foreach ( $output->getCategories() as $name => $sortkey ) {
826 if ( $out !== '' ) {
827 $out .= "\n";
828 }
829 $out .= "cat=$name sort=$sortkey";
830 }
831 }
832 }
833
834 ScopedCallback::consume( $teardownGuard );
835
836 $expected = $test['result'];
837 if ( count( $this->normalizationFunctions ) ) {
838 $expected = ParserTestResultNormalizer::normalize(
839 $test['expected'], $this->normalizationFunctions );
840 $out = ParserTestResultNormalizer::normalize( $out, $this->normalizationFunctions );
841 }
842
843 $testResult = new ParserTestResult( $test, $expected, $out );
844 return $testResult;
845 }
846
847 /**
848 * Use a regex to find out the value of an option
849 * @param string $key Name of option val to retrieve
850 * @param array $opts Options array to look in
851 * @param mixed $default Default value returned if not found
852 * @return mixed
853 */
854 private static function getOptionValue( $key, $opts, $default ) {
855 $key = strtolower( $key );
856
857 if ( isset( $opts[$key] ) ) {
858 return $opts[$key];
859 } else {
860 return $default;
861 }
862 }
863
864 /**
865 * Given the options string, return an associative array of options.
866 * @todo Move this to TestFileReader
867 *
868 * @param string $instring
869 * @return array
870 */
871 private function parseOptions( $instring ) {
872 $opts = [];
873 // foo
874 // foo=bar
875 // foo="bar baz"
876 // foo=[[bar baz]]
877 // foo=bar,"baz quux"
878 // foo={...json...}
879 $defs = '(?(DEFINE)
880 (?<qstr> # Quoted string
881 "
882 (?:[^\\\\"] | \\\\.)*
883 "
884 )
885 (?<json>
886 \{ # Open bracket
887 (?:
888 [^"{}] | # Not a quoted string or object, or
889 (?&qstr) | # A quoted string, or
890 (?&json) # A json object (recursively)
891 )*
892 \} # Close bracket
893 )
894 (?<value>
895 (?:
896 (?&qstr) # Quoted val
897 |
898 \[\[
899 [^]]* # Link target
900 \]\]
901 |
902 [\w-]+ # Plain word
903 |
904 (?&json) # JSON object
905 )
906 )
907 )';
908 $regex = '/' . $defs . '\b
909 (?<k>[\w-]+) # Key
910 \b
911 (?:\s*
912 = # First sub-value
913 \s*
914 (?<v>
915 (?&value)
916 (?:\s*
917 , # Sub-vals 1..N
918 \s*
919 (?&value)
920 )*
921 )
922 )?
923 /x';
924 $valueregex = '/' . $defs . '(?&value)/x';
925
926 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
927 foreach ( $matches as $bits ) {
928 $key = strtolower( $bits['k'] );
929 if ( !isset( $bits['v'] ) ) {
930 $opts[$key] = true;
931 } else {
932 preg_match_all( $valueregex, $bits['v'], $vmatches );
933 $opts[$key] = array_map( [ $this, 'cleanupOption' ], $vmatches[0] );
934 if ( count( $opts[$key] ) == 1 ) {
935 $opts[$key] = $opts[$key][0];
936 }
937 }
938 }
939 }
940 return $opts;
941 }
942
943 private function cleanupOption( $opt ) {
944 if ( substr( $opt, 0, 1 ) == '"' ) {
945 return stripcslashes( substr( $opt, 1, -1 ) );
946 }
947
948 if ( substr( $opt, 0, 2 ) == '[[' ) {
949 return substr( $opt, 2, -2 );
950 }
951
952 if ( substr( $opt, 0, 1 ) == '{' ) {
953 return FormatJson::decode( $opt, true );
954 }
955 return $opt;
956 }
957
958 /**
959 * Do any required setup which is dependent on test options.
960 *
961 * @see staticSetup() for more information about setup/teardown
962 *
963 * @param array $test Test info supplied by TestFileReader
964 * @param callable|null $nextTeardown
965 * @return ScopedCallback
966 */
967 public function perTestSetup( $test, $nextTeardown = null ) {
968 $teardown = [];
969
970 $this->checkSetupDone( 'setupDatabase', 'setDatabase' );
971 $teardown[] = $this->markSetupDone( 'perTestSetup' );
972
973 $opts = $this->parseOptions( $test['options'] );
974 $config = $test['config'];
975
976 // Find out values for some special options.
977 $langCode =
978 self::getOptionValue( 'language', $opts, 'en' );
979 $variant =
980 self::getOptionValue( 'variant', $opts, false );
981 $maxtoclevel =
982 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
983 $linkHolderBatchSize =
984 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
985
986 $setup = [
987 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
988 'wgLanguageCode' => $langCode,
989 'wgRawHtml' => self::getOptionValue( 'wgRawHtml', $opts, false ),
990 'wgNamespacesWithSubpages' => [ 0 => isset( $opts['subpage'] ) ],
991 'wgMaxTocLevel' => $maxtoclevel,
992 'wgAllowExternalImages' => self::getOptionValue( 'wgAllowExternalImages', $opts, true ),
993 'wgThumbLimits' => [ self::getOptionValue( 'thumbsize', $opts, 180 ) ],
994 'wgDefaultLanguageVariant' => $variant,
995 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
996 // Set as a JSON object like:
997 // wgEnableMagicLinks={"ISBN":false, "PMID":false, "RFC":false}
998 'wgEnableMagicLinks' => self::getOptionValue( 'wgEnableMagicLinks', $opts, [] )
999 + [ 'ISBN' => true, 'PMID' => true, 'RFC' => true ],
1000 ];
1001
1002 if ( $config ) {
1003 $configLines = explode( "\n", $config );
1004
1005 foreach ( $configLines as $line ) {
1006 list( $var, $value ) = explode( '=', $line, 2 );
1007 $setup[$var] = eval( "return $value;" );
1008 }
1009 }
1010
1011 /** @since 1.20 */
1012 Hooks::run( 'ParserTestGlobals', [ &$setup ] );
1013
1014 // Create tidy driver
1015 if ( isset( $opts['tidy'] ) ) {
1016 // Cache a driver instance
1017 if ( $this->tidyDriver === null ) {
1018 $this->tidyDriver = MWTidy::factory( $this->tidySupport->getConfig() );
1019 }
1020 $tidy = $this->tidyDriver;
1021 } else {
1022 $tidy = false;
1023 }
1024 MWTidy::setInstance( $tidy );
1025 $teardown[] = function () {
1026 MWTidy::destroySingleton();
1027 };
1028
1029 // Set content language. This invalidates the magic word cache and title services
1030 wfDebug( "Setting up language $langCode" );
1031 $lang = Language::factory( $langCode );
1032 $setup['wgContLang'] = $lang;
1033 $reset = function () {
1034 MagicWord::clearCache();
1035 $this->resetTitleServices();
1036 };
1037 $setup[] = $reset;
1038 $teardown[] = $reset;
1039
1040 // Make a user object with the same language
1041 $user = new User;
1042 $user->setOption( 'language', $langCode );
1043 $setup['wgLang'] = $lang;
1044
1045 // We (re)set $wgThumbLimits to a single-element array above.
1046 $user->setOption( 'thumbsize', 0 );
1047
1048 $setup['wgUser'] = $user;
1049
1050 // And put both user and language into the context
1051 $context = RequestContext::getMain();
1052 $context->setUser( $user );
1053 $context->setLanguage( $lang );
1054 $teardown[] = function () use ( $context ) {
1055 // Reset context to the restored globals
1056 $context->setUser( $GLOBALS['wgUser'] );
1057 $context->setLanguage( $GLOBALS['wgContLang'] );
1058 };
1059
1060 $teardown[] = $this->executeSetupSnippets( $setup );
1061
1062 return $this->createTeardownObject( $teardown, $nextTeardown );
1063 }
1064
1065 /**
1066 * List of temporary tables to create, without prefix.
1067 * Some of these probably aren't necessary.
1068 * @return array
1069 */
1070 private function listTables() {
1071 $tables = [ 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
1072 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
1073 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
1074 'site_stats', 'ipblocks', 'image', 'oldimage',
1075 'recentchanges', 'watchlist', 'interwiki', 'logging', 'log_search',
1076 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
1077 'archive', 'user_groups', 'page_props', 'category'
1078 ];
1079
1080 if ( in_array( $this->db->getType(), [ 'mysql', 'sqlite', 'oracle' ] ) ) {
1081 array_push( $tables, 'searchindex' );
1082 }
1083
1084 // Allow extensions to add to the list of tables to duplicate;
1085 // may be necessary if they hook into page save or other code
1086 // which will require them while running tests.
1087 Hooks::run( 'ParserTestTables', [ &$tables ] );
1088
1089 return $tables;
1090 }
1091
1092 public function setDatabase( IDatabase $db ) {
1093 $this->db = $db;
1094 $this->setupDone['setDatabase'] = true;
1095 }
1096
1097 /**
1098 * Set up temporary DB tables.
1099 *
1100 * For best performance, call this once only for all tests. However, it can
1101 * be called at the start of each test if more isolation is desired.
1102 *
1103 * @todo: This is basically an unrefactored copy of
1104 * MediaWikiTestCase::setupAllTestDBs. They should be factored out somehow.
1105 *
1106 * Do not call this function from a MediaWikiTestCase subclass, since
1107 * MediaWikiTestCase does its own DB setup. Instead use setDatabase().
1108 *
1109 * @see staticSetup() for more information about setup/teardown
1110 *
1111 * @param ScopedCallback|null $nextTeardown The next teardown object
1112 * @return ScopedCallback The teardown object
1113 */
1114 public function setupDatabase( $nextTeardown = null ) {
1115 global $wgDBprefix;
1116
1117 $this->db = wfGetDB( DB_MASTER );
1118 $dbType = $this->db->getType();
1119
1120 if ( $dbType == 'oracle' ) {
1121 $suspiciousPrefixes = [ 'pt_', MediaWikiTestCase::ORA_DB_PREFIX ];
1122 } else {
1123 $suspiciousPrefixes = [ 'parsertest_', MediaWikiTestCase::DB_PREFIX ];
1124 }
1125 if ( in_array( $wgDBprefix, $suspiciousPrefixes ) ) {
1126 throw new MWException( "\$wgDBprefix=$wgDBprefix suggests DB setup is already done" );
1127 }
1128
1129 $teardown = [];
1130
1131 $teardown[] = $this->markSetupDone( 'setupDatabase' );
1132
1133 # CREATE TEMPORARY TABLE breaks if there is more than one server
1134 if ( wfGetLB()->getServerCount() != 1 ) {
1135 $this->useTemporaryTables = false;
1136 }
1137
1138 $temporary = $this->useTemporaryTables || $dbType == 'postgres';
1139 $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
1140
1141 $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
1142 $this->dbClone->useTemporaryTables( $temporary );
1143 $this->dbClone->cloneTableStructure();
1144
1145 if ( $dbType == 'oracle' ) {
1146 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1147 # Insert 0 user to prevent FK violations
1148
1149 # Anonymous user
1150 $this->db->insert( 'user', [
1151 'user_id' => 0,
1152 'user_name' => 'Anonymous' ] );
1153 }
1154
1155 $teardown[] = function () {
1156 $this->teardownDatabase();
1157 };
1158
1159 // Wipe some DB query result caches on setup and teardown
1160 $reset = function () {
1161 LinkCache::singleton()->clear();
1162
1163 // Clear the message cache
1164 MessageCache::singleton()->clear();
1165 };
1166 $reset();
1167 $teardown[] = $reset;
1168 return $this->createTeardownObject( $teardown, $nextTeardown );
1169 }
1170
1171 /**
1172 * Add data about uploads to the new test DB, and set up the upload
1173 * directory. This should be called after either setDatabase() or
1174 * setupDatabase().
1175 *
1176 * @param ScopedCallback|null $nextTeardown The next teardown object
1177 * @return ScopedCallback The teardown object
1178 */
1179 public function setupUploads( $nextTeardown = null ) {
1180 $teardown = [];
1181
1182 $this->checkSetupDone( 'setupDatabase', 'setDatabase' );
1183 $teardown[] = $this->markSetupDone( 'setupUploads' );
1184
1185 // Create the files in the upload directory (or pretend to create them
1186 // in a MockFileBackend). Append teardown callback.
1187 $teardown[] = $this->setupUploadBackend();
1188
1189 // Create a user
1190 $user = User::createNew( 'WikiSysop' );
1191
1192 // Register the uploads in the database
1193
1194 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
1195 # note that the size/width/height/bits/etc of the file
1196 # are actually set by inspecting the file itself; the arguments
1197 # to recordUpload2 have no effect. That said, we try to make things
1198 # match up so it is less confusing to readers of the code & tests.
1199 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', [
1200 'size' => 7881,
1201 'width' => 1941,
1202 'height' => 220,
1203 'bits' => 8,
1204 'media_type' => MEDIATYPE_BITMAP,
1205 'mime' => 'image/jpeg',
1206 'metadata' => serialize( [] ),
1207 'sha1' => Wikimedia\base_convert( '1', 16, 36, 31 ),
1208 'fileExists' => true
1209 ], $this->db->timestamp( '20010115123500' ), $user );
1210
1211 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Thumb.png' ) );
1212 # again, note that size/width/height below are ignored; see above.
1213 $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', [
1214 'size' => 22589,
1215 'width' => 135,
1216 'height' => 135,
1217 'bits' => 8,
1218 'media_type' => MEDIATYPE_BITMAP,
1219 'mime' => 'image/png',
1220 'metadata' => serialize( [] ),
1221 'sha1' => Wikimedia\base_convert( '2', 16, 36, 31 ),
1222 'fileExists' => true
1223 ], $this->db->timestamp( '20130225203040' ), $user );
1224
1225 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.svg' ) );
1226 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', [
1227 'size' => 12345,
1228 'width' => 240,
1229 'height' => 180,
1230 'bits' => 0,
1231 'media_type' => MEDIATYPE_DRAWING,
1232 'mime' => 'image/svg+xml',
1233 'metadata' => serialize( [] ),
1234 'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1235 'fileExists' => true
1236 ], $this->db->timestamp( '20010115123500' ), $user );
1237
1238 # This image will be blacklisted in [[MediaWiki:Bad image list]]
1239 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
1240 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', [
1241 'size' => 12345,
1242 'width' => 320,
1243 'height' => 240,
1244 'bits' => 24,
1245 'media_type' => MEDIATYPE_BITMAP,
1246 'mime' => 'image/jpeg',
1247 'metadata' => serialize( [] ),
1248 'sha1' => Wikimedia\base_convert( '3', 16, 36, 31 ),
1249 'fileExists' => true
1250 ], $this->db->timestamp( '20010115123500' ), $user );
1251
1252 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Video.ogv' ) );
1253 $image->recordUpload2( '', 'A pretty movie', 'Will it play', [
1254 'size' => 12345,
1255 'width' => 320,
1256 'height' => 240,
1257 'bits' => 0,
1258 'media_type' => MEDIATYPE_VIDEO,
1259 'mime' => 'application/ogg',
1260 'metadata' => serialize( [] ),
1261 'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1262 'fileExists' => true
1263 ], $this->db->timestamp( '20010115123500' ), $user );
1264
1265 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Audio.oga' ) );
1266 $image->recordUpload2( '', 'An awesome hitsong', 'Will it play', [
1267 'size' => 12345,
1268 'width' => 0,
1269 'height' => 0,
1270 'bits' => 0,
1271 'media_type' => MEDIATYPE_AUDIO,
1272 'mime' => 'application/ogg',
1273 'metadata' => serialize( [] ),
1274 'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1275 'fileExists' => true
1276 ], $this->db->timestamp( '20010115123500' ), $user );
1277
1278 # A DjVu file
1279 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'LoremIpsum.djvu' ) );
1280 $image->recordUpload2( '', 'Upload a DjVu', 'A DjVu', [
1281 'size' => 3249,
1282 'width' => 2480,
1283 'height' => 3508,
1284 'bits' => 0,
1285 'media_type' => MEDIATYPE_BITMAP,
1286 'mime' => 'image/vnd.djvu',
1287 'metadata' => '<?xml version="1.0" ?>
1288 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
1289 <DjVuXML>
1290 <HEAD></HEAD>
1291 <BODY><OBJECT height="3508" width="2480">
1292 <PARAM name="DPI" value="300" />
1293 <PARAM name="GAMMA" value="2.2" />
1294 </OBJECT>
1295 <OBJECT height="3508" width="2480">
1296 <PARAM name="DPI" value="300" />
1297 <PARAM name="GAMMA" value="2.2" />
1298 </OBJECT>
1299 <OBJECT height="3508" width="2480">
1300 <PARAM name="DPI" value="300" />
1301 <PARAM name="GAMMA" value="2.2" />
1302 </OBJECT>
1303 <OBJECT height="3508" width="2480">
1304 <PARAM name="DPI" value="300" />
1305 <PARAM name="GAMMA" value="2.2" />
1306 </OBJECT>
1307 <OBJECT height="3508" width="2480">
1308 <PARAM name="DPI" value="300" />
1309 <PARAM name="GAMMA" value="2.2" />
1310 </OBJECT>
1311 </BODY>
1312 </DjVuXML>',
1313 'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1314 'fileExists' => true
1315 ], $this->db->timestamp( '20010115123600' ), $user );
1316
1317 return $this->createTeardownObject( $teardown, $nextTeardown );
1318 }
1319
1320 /**
1321 * Helper for database teardown, called from the teardown closure. Destroy
1322 * the database clone and fix up some things that CloneDatabase doesn't fix.
1323 *
1324 * @todo Move most things here to CloneDatabase
1325 */
1326 private function teardownDatabase() {
1327 $this->checkSetupDone( 'setupDatabase' );
1328
1329 $this->dbClone->destroy();
1330 $this->databaseSetupDone = false;
1331
1332 if ( $this->useTemporaryTables ) {
1333 if ( $this->db->getType() == 'sqlite' ) {
1334 # Under SQLite the searchindex table is virtual and need
1335 # to be explicitly destroyed. See bug 29912
1336 # See also MediaWikiTestCase::destroyDB()
1337 wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
1338 $this->db->query( "DROP TABLE `parsertest_searchindex`" );
1339 }
1340 # Don't need to do anything
1341 return;
1342 }
1343
1344 $tables = $this->listTables();
1345
1346 foreach ( $tables as $table ) {
1347 if ( $this->db->getType() == 'oracle' ) {
1348 $this->db->query( "DROP TABLE pt_$table DROP CONSTRAINTS" );
1349 } else {
1350 $this->db->query( "DROP TABLE `parsertest_$table`" );
1351 }
1352 }
1353
1354 if ( $this->db->getType() == 'oracle' ) {
1355 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1356 }
1357 }
1358
1359 /**
1360 * Upload test files to the backend created by createRepoGroup().
1361 *
1362 * @return callable The teardown callback
1363 */
1364 private function setupUploadBackend() {
1365 global $IP;
1366
1367 $repo = RepoGroup::singleton()->getLocalRepo();
1368 $base = $repo->getZonePath( 'public' );
1369 $backend = $repo->getBackend();
1370 $backend->prepare( [ 'dir' => "$base/3/3a" ] );
1371 $backend->store( [
1372 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
1373 'dst' => "$base/3/3a/Foobar.jpg"
1374 ] );
1375 $backend->prepare( [ 'dir' => "$base/e/ea" ] );
1376 $backend->store( [
1377 'src' => "$IP/tests/phpunit/data/parser/wiki.png",
1378 'dst' => "$base/e/ea/Thumb.png"
1379 ] );
1380 $backend->prepare( [ 'dir' => "$base/0/09" ] );
1381 $backend->store( [
1382 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
1383 'dst' => "$base/0/09/Bad.jpg"
1384 ] );
1385 $backend->prepare( [ 'dir' => "$base/5/5f" ] );
1386 $backend->store( [
1387 'src' => "$IP/tests/phpunit/data/parser/LoremIpsum.djvu",
1388 'dst' => "$base/5/5f/LoremIpsum.djvu"
1389 ] );
1390
1391 // No helpful SVG file to copy, so make one ourselves
1392 $data = '<?xml version="1.0" encoding="utf-8"?>' .
1393 '<svg xmlns="http://www.w3.org/2000/svg"' .
1394 ' version="1.1" width="240" height="180"/>';
1395
1396 $backend->prepare( [ 'dir' => "$base/f/ff" ] );
1397 $backend->quickCreate( [
1398 'content' => $data, 'dst' => "$base/f/ff/Foobar.svg"
1399 ] );
1400
1401 return function () use ( $backend ) {
1402 if ( $backend instanceof MockFileBackend ) {
1403 // In memory backend, so dont bother cleaning them up.
1404 return;
1405 }
1406 $this->teardownUploadBackend();
1407 };
1408 }
1409
1410 /**
1411 * Remove the dummy uploads directory
1412 */
1413 private function teardownUploadBackend() {
1414 if ( $this->keepUploads ) {
1415 return;
1416 }
1417
1418 $repo = RepoGroup::singleton()->getLocalRepo();
1419 $public = $repo->getZonePath( 'public' );
1420
1421 $this->deleteFiles(
1422 [
1423 "$public/3/3a/Foobar.jpg",
1424 "$public/e/ea/Thumb.png",
1425 "$public/0/09/Bad.jpg",
1426 "$public/5/5f/LoremIpsum.djvu",
1427 "$public/f/ff/Foobar.svg",
1428 "$public/0/00/Video.ogv",
1429 "$public/4/41/Audio.oga",
1430 ]
1431 );
1432 }
1433
1434 /**
1435 * Delete the specified files and their parent directories
1436 * @param array $files File backend URIs mwstore://...
1437 */
1438 private function deleteFiles( $files ) {
1439 // Delete the files
1440 $backend = RepoGroup::singleton()->getLocalRepo()->getBackend();
1441 foreach ( $files as $file ) {
1442 $backend->delete( [ 'src' => $file ], [ 'force' => 1 ] );
1443 }
1444
1445 // Delete the parent directories
1446 foreach ( $files as $file ) {
1447 $tmp = FileBackend::parentStoragePath( $file );
1448 while ( $tmp ) {
1449 if ( !$backend->clean( [ 'dir' => $tmp ] )->isOK() ) {
1450 break;
1451 }
1452 $tmp = FileBackend::parentStoragePath( $tmp );
1453 }
1454 }
1455 }
1456
1457 /**
1458 * Add articles to the test DB.
1459 *
1460 * @param $articles Article info array from TestFileReader
1461 */
1462 public function addArticles( $articles ) {
1463 global $wgContLang;
1464 $setup = [];
1465 $teardown = [];
1466
1467 // Be sure ParserTestRunner::addArticle has correct language set,
1468 // so that system messages get into the right language cache
1469 if ( $wgContLang->getCode() !== 'en' ) {
1470 $setup['wgLanguageCode'] = 'en';
1471 $setup['wgContLang'] = Language::factory( 'en' );
1472 }
1473
1474 // Add special namespaces, in case that hasn't been done by staticSetup() yet
1475 $this->appendNamespaceSetup( $setup, $teardown );
1476
1477 // wgCapitalLinks obviously needs initialisation
1478 $setup['wgCapitalLinks'] = true;
1479
1480 $teardown[] = $this->executeSetupSnippets( $setup );
1481
1482 foreach ( $articles as $info ) {
1483 $this->addArticle( $info['name'], $info['text'], $info['file'], $info['line'] );
1484 }
1485
1486 // Wipe WANObjectCache process cache, which is invalidated by article insertion
1487 // due to T144706
1488 ObjectCache::getMainWANInstance()->clearProcessCache();
1489
1490 $this->executeSetupSnippets( $teardown );
1491 }
1492
1493 /**
1494 * Insert a temporary test article
1495 * @param string $name The title, including any prefix
1496 * @param string $text The article text
1497 * @param string $file The input file name
1498 * @param int|string $line The input line number, for reporting errors
1499 * @throws Exception
1500 * @throws MWException
1501 */
1502 private function addArticle( $name, $text, $file, $line ) {
1503 $text = self::chomp( $text );
1504 $name = self::chomp( $name );
1505
1506 $title = Title::newFromText( $name );
1507 wfDebug( __METHOD__ . ": adding $name" );
1508
1509 if ( is_null( $title ) ) {
1510 throw new MWException( "invalid title '$name' at $file:$line\n" );
1511 }
1512
1513 $page = WikiPage::factory( $title );
1514 $page->loadPageData( 'fromdbmaster' );
1515
1516 if ( $page->exists() ) {
1517 throw new MWException( "duplicate article '$name' at $file:$line\n" );
1518 }
1519
1520 $status = $page->doEditContent( ContentHandler::makeContent( $text, $title ), '', EDIT_NEW );
1521 if ( !$status->isOK() ) {
1522 throw new MWException( $status->getWikiText( false, false, 'en' ) );
1523 }
1524
1525 // The RepoGroup cache is invalidated by the creation of file redirects
1526 if ( $title->getNamespace() === NS_IMAGE ) {
1527 RepoGroup::singleton()->clearCache( $title );
1528 }
1529 }
1530
1531 /**
1532 * Check if a hook is installed
1533 *
1534 * @param string $name
1535 * @return bool True if tag hook is present
1536 */
1537 public function requireHook( $name ) {
1538 global $wgParser;
1539
1540 $wgParser->firstCallInit(); // make sure hooks are loaded.
1541 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1542 return true;
1543 } else {
1544 $this->recorder->warning( " This test suite requires the '$name' hook " .
1545 "extension, skipping." );
1546 return false;
1547 }
1548 }
1549
1550 /**
1551 * Check if a function hook is installed
1552 *
1553 * @param string $name
1554 * @return bool True if function hook is present
1555 */
1556 public function requireFunctionHook( $name ) {
1557 global $wgParser;
1558
1559 $wgParser->firstCallInit(); // make sure hooks are loaded.
1560
1561 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1562 return true;
1563 } else {
1564 $this->recorder->warning( " This test suite requires the '$name' function " .
1565 "hook extension, skipping." );
1566 return false;
1567 }
1568 }
1569
1570 /**
1571 * Check if a transparent tag hook is installed
1572 *
1573 * @param string $name
1574 * @return bool True if function hook is present
1575 */
1576 public function requireTransparentHook( $name ) {
1577 global $wgParser;
1578
1579 $wgParser->firstCallInit(); // make sure hooks are loaded.
1580
1581 if ( isset( $wgParser->mTransparentTagHooks[$name] ) ) {
1582 return true;
1583 } else {
1584 $this->recorder->warning( " This test suite requires the '$name' transparent " .
1585 "hook extension, skipping.\n" );
1586 return false;
1587 }
1588 }
1589
1590 /**
1591 * The ParserGetVariableValueTs hook, used to make sure time-related parser
1592 * functions give a persistent value.
1593 */
1594 static function getFakeTimestamp( &$parser, &$ts ) {
1595 $ts = 123; // parsed as '1970-01-01T00:02:03Z'
1596 return true;
1597 }
1598 }