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