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