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