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