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