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