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