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